diff --git a/buddybook/assets/ccip-DHJq9nI9.js b/buddybook/assets/ccip-DHJq9nI9.js new file mode 100644 index 0000000..69a8aaf --- /dev/null +++ b/buddybook/assets/ccip-DHJq9nI9.js @@ -0,0 +1 @@ +import{i as h,I as m,v as p,w,x as g,y as E,z as x,c as O,e as b,H as y,A as M}from"./index-B-6Lwopd.js";function R(s,e){if(!h(s,{strict:!1}))throw new m({address:s});if(!h(e,{strict:!1}))throw new m({address:e});return s.toLowerCase()===e.toLowerCase()}class $ extends p{constructor({callbackSelector:e,cause:a,data:n,extraData:c,sender:d,urls:t}){var i;super(a.shortMessage||"An error occurred while fetching for an offchain result.",{cause:a,metaMessages:[...a.metaMessages||[],(i=a.metaMessages)!=null&&i.length?"":[],"Offchain Gateway Call:",t&&[" Gateway URL(s):",...t.map(f=>` ${w(f)}`)],` Sender: ${d}`,` Data: ${n}`,` Callback selector: ${e}`,` Extra data: ${c}`].flat(),name:"OffchainLookupError"})}}class A extends p{constructor({result:e,url:a}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${w(a)}`,`Response: ${g(e)}`],name:"OffchainLookupResponseMalformedError"})}}class S extends p{constructor({sender:e,to:a}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${a}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}const T="0x556f1830",q={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function v(s,{blockNumber:e,blockTag:a,data:n,to:c}){const{args:d}=E({data:n,abi:[q]}),[t,i,f,r,o]=d,{ccipRead:u}=s,k=u&&typeof(u==null?void 0:u.request)=="function"?u.request:C;try{if(!R(c,t))throw new S({sender:t,to:c});const l=await k({data:f,sender:t,urls:i}),{data:L}=await x(s,{blockNumber:e,blockTag:a,data:O([r,b([{type:"bytes"},{type:"bytes"}],[l,o])]),to:c});return L}catch(l){throw new $({callbackSelector:r,cause:l,data:n,extraData:o,sender:t,urls:i})}}async function C({data:s,sender:e,urls:a}){var c;let n=new Error("An unknown error occurred.");for(let d=0;d0&&(s=n[0]),s instanceof Error)throw s;var u=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw u.context=s,u}var c=f[e];if(c===void 0)return!1;if(typeof c=="function")d(c,this,n);else for(var h=c.length,O=E(c,h),r=0;r0&&s.length>i&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=s.length,j(u)}return t}o.prototype.addListener=function(e,n){return g(this,e,n,!1)};o.prototype.on=o.prototype.addListener;o.prototype.prependListener=function(e,n){return g(this,e,n,!0)};function R(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=R.bind(r);return i.listener=n,r.wrapFn=i,i}o.prototype.once=function(e,n){return v(n),this.on(e,_(this,e,n)),this};o.prototype.prependOnceListener=function(e,n){return v(n),this.prependListener(e,_(this,e,n)),this};o.prototype.removeListener=function(e,n){var r,i,f,s,u;if(v(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(f=-1,s=r.length-1;s>=0;s--)if(r[s]===n||r[s].listener===n){u=r[s].listener,f=s;break}if(f<0)return this;f===0?r.shift():N(r,f),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,u||n)}return this};o.prototype.off=o.prototype.removeListener;o.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var f=Object.keys(r),s;for(i=0;i=0;i--)this.removeListener(e,n[i]);return this};function w(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?M(i):E(i,i.length)}o.prototype.listeners=function(e){return w(this,e,!0)};o.prototype.rawListeners=function(e){return w(this,e,!1)};o.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):b.call(t,e)};o.prototype.listenerCount=b;function b(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}o.prototype.eventNames=function(){return this._eventsCount>0?l(this._events):[]};function E(t,e){for(var n=new Array(e),r=0;r0?this.tail.next=s:this.head=s,this.tail=s,++this.length}},{key:"unshift",value:function(w){var s={data:w,next:this.head};this.length===0&&(this.tail=s),this.head=s,++this.length}},{key:"shift",value:function(){if(this.length!==0){var w=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,w}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(w){if(this.length===0)return"";for(var s=this.head,p=""+s.data;s=s.next;)p+=w+s.data;return p}},{key:"concat",value:function(w){if(this.length===0)return b.alloc(0);for(var s=b.allocUnsafe(w>>>0),p=this.head,y=0;p;)v(p.data,s,y),y+=p.data.length,p=p.next;return s}},{key:"consume",value:function(w,s){var p;return wS.length?S.length:w;if(T===S.length?y+=S:y+=S.slice(0,w),w-=T,w===0){T===S.length?(++p,s.next?this.head=s.next:this.head=this.tail=null):(this.head=s,s.data=S.slice(T));break}++p}return this.length-=p,y}},{key:"_getBuffer",value:function(w){var s=b.allocUnsafe(w),p=this.head,y=1;for(p.data.copy(s),w-=p.data.length;p=p.next;){var S=p.data,T=w>S.length?S.length:w;if(S.copy(s,s.length-w,0,T),w-=T,w===0){T===S.length?(++y,p.next?this.head=p.next:this.head=this.tail=null):(this.head=p,p.data=S.slice(T));break}++y}return this.length-=y,s}},{key:m,value:function(w,s){return u(this,t(t({},s),{},{depth:0,customInspect:!1}))}}]),R}(),Yt}function Gn(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(or,this,e)):process.nextTick(or,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(f){!t&&f?r._writableState?r._writableState.errorEmitted?process.nextTick(We,r):(r._writableState.errorEmitted=!0,process.nextTick(mr,r,f)):process.nextTick(mr,r,f):t?(process.nextTick(We,r),t(f)):process.nextTick(We,r)}),this)}function mr(e,t){or(e,t),We(e)}function We(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function Vn(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function or(e,t){e.emit("error",t)}function Kn(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}var nn={destroy:Gn,undestroy:Vn,errorOrDestroy:Kn},pe={};function Yn(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var an={};function X(e,t,r){r||(r=Error);function n(f,l,c){return typeof t=="string"?t:t(f,l,c)}var i=function(f){Yn(l,f);function l(c,d,b){return f.call(this,n(c,d,b))||this}return l}(r);i.prototype.name=r.name,i.prototype.code=e,an[e]=i}function Sr(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map(function(n){return String(n)}),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 Xn(e,t,r){return e.substr(0,t.length)===t}function Jn(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function Qn(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}X("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);X("ERR_INVALID_ARG_TYPE",function(e,t,r){var n;typeof t=="string"&&Xn(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be";var i;if(Jn(e," argument"))i="The ".concat(e," ").concat(n," ").concat(Sr(t,"type"));else{var f=Qn(e,".")?"property":"argument";i='The "'.concat(e,'" ').concat(f," ").concat(n," ").concat(Sr(t,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);X("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");X("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});X("ERR_STREAM_PREMATURE_CLOSE","Premature close");X("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});X("ERR_MULTIPLE_CALLBACK","Callback called multiple times");X("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");X("ERR_STREAM_WRITE_AFTER_END","write after end");X("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);X("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);X("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");pe.codes=an;var Zn=pe.codes.ERR_INVALID_OPT_VALUE;function ei(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function ti(e,t,r,n){var i=ei(t,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var f=n?r:"highWaterMark";throw new Zn(f,i)}return Math.floor(i)}return e.objectMode?16:16*1024}var on={getHighWaterMark:ti},ri=ni;function ni(e,t){if(Xt("noDeprecation"))return e;var r=!1;function n(){if(!r){if(Xt("throwDeprecation"))throw new Error(t);Xt("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}return n}function Xt(e){try{if(!Ee.localStorage)return!1}catch{return!1}var t=Ee.localStorage[e];return t==null?!1:String(t).toLowerCase()==="true"}var Jt,Rr;function fn(){if(Rr)return Jt;Rr=1,Jt=D;function e(_){var h=this;this.next=null,this.entry=null,this.finish=function(){ne(h,_)}}var t;D.WritableState=B;var r={deprecate:ri},n=rn,i=Le.Buffer,f=(typeof Ee<"u"?Ee:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function l(_){return i.from(_)}function c(_){return i.isBuffer(_)||_ instanceof f}var d=nn,b=on,E=b.getHighWaterMark,u=pe.codes,m=u.ERR_INVALID_ARG_TYPE,v=u.ERR_METHOD_NOT_IMPLEMENTED,R=u.ERR_MULTIPLE_CALLBACK,A=u.ERR_STREAM_CANNOT_PIPE,w=u.ERR_STREAM_DESTROYED,s=u.ERR_STREAM_NULL_VALUES,p=u.ERR_STREAM_WRITE_AFTER_END,y=u.ERR_UNKNOWN_ENCODING,S=d.errorOrDestroy;J(D,n);function T(){}function B(_,h,x){t=t||me(),_=_||{},typeof x!="boolean"&&(x=h instanceof t),this.objectMode=!!_.objectMode,x&&(this.objectMode=this.objectMode||!!_.writableObjectMode),this.highWaterMark=E(this,_,"writableHighWaterMark",x),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var k=_.decodeStrings===!1;this.decodeStrings=!k,this.defaultEncoding=_.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(L){le(h,L)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=_.emitClose!==!1,this.autoDestroy=!!_.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}B.prototype.getBuffer=function(){for(var h=this.bufferedRequest,x=[];h;)x.push(h),h=h.next;return x},function(){try{Object.defineProperty(B.prototype,"buffer",{get:r.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var O;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(O=Function.prototype[Symbol.hasInstance],Object.defineProperty(D,Symbol.hasInstance,{value:function(h){return O.call(this,h)?!0:this!==D?!1:h&&h._writableState instanceof B}})):O=function(h){return h instanceof this};function D(_){t=t||me();var h=this instanceof t;if(!h&&!O.call(D,this))return new D(_);this._writableState=new B(_,this,h),this.writable=!0,_&&(typeof _.write=="function"&&(this._write=_.write),typeof _.writev=="function"&&(this._writev=_.writev),typeof _.destroy=="function"&&(this._destroy=_.destroy),typeof _.final=="function"&&(this._final=_.final)),n.call(this)}D.prototype.pipe=function(){S(this,new A)};function M(_,h){var x=new p;S(_,x),process.nextTick(h,x)}function F(_,h,x,k){var L;return x===null?L=new s:typeof x!="string"&&!h.objectMode&&(L=new m("chunk",["string","Buffer"],x)),L?(S(_,L),process.nextTick(k,L),!1):!0}D.prototype.write=function(_,h,x){var k=this._writableState,L=!1,a=!k.objectMode&&c(_);return a&&!i.isBuffer(_)&&(_=l(_)),typeof h=="function"&&(x=h,h=null),a?h="buffer":h||(h=k.defaultEncoding),typeof x!="function"&&(x=T),k.ending?M(this,x):(a||F(this,k,_,x))&&(k.pendingcb++,L=Z(this,k,a,_,h,x)),L},D.prototype.cork=function(){this._writableState.corked++},D.prototype.uncork=function(){var _=this._writableState;_.corked&&(_.corked--,!_.writing&&!_.corked&&!_.bufferProcessing&&_.bufferedRequest&&Y(this,_))},D.prototype.setDefaultEncoding=function(h){if(typeof h=="string"&&(h=h.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((h+"").toLowerCase())>-1))throw new y(h);return this._writableState.defaultEncoding=h,this},Object.defineProperty(D.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function W(_,h,x){return!_.objectMode&&_.decodeStrings!==!1&&typeof h=="string"&&(h=i.from(h,x)),h}Object.defineProperty(D.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function Z(_,h,x,k,L,a){if(!x){var o=W(h,k,L);k!==o&&(x=!0,L="buffer",k=o)}var g=h.objectMode?1:k.length;h.length+=g;var C=h.length */var Ar;function ii(){return Ar||(Ar=1,function(e,t){var r=Le,n=r.Buffer;function i(l,c){for(var d in l)c[d]=l[d]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=f);function f(l,c,d){return n(l,c,d)}f.prototype=Object.create(n.prototype),i(n,f),f.from=function(l,c,d){if(typeof l=="number")throw new TypeError("Argument must not be a number");return n(l,c,d)},f.alloc=function(l,c,d){if(typeof l!="number")throw new TypeError("Argument must be a number");var b=n(l);return c!==void 0?typeof d=="string"?b.fill(c,d):b.fill(c):b.fill(0),b},f.allocUnsafe=function(l){if(typeof l!="number")throw new TypeError("Argument must be a number");return n(l)},f.allocUnsafeSlow=function(l){if(typeof l!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(l)}}(qe,qe.exports)),qe.exports}var Cr;function Br(){if(Cr)return Zt;Cr=1;var e=ii().Buffer,t=e.isEncoding||function(s){switch(s=""+s,s&&s.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(s){if(!s)return"utf8";for(var p;;)switch(s){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return s;default:if(p)return;s=(""+s).toLowerCase(),p=!0}}function n(s){var p=r(s);if(typeof p!="string"&&(e.isEncoding===t||!t(s)))throw new Error("Unknown encoding: "+s);return p||s}Zt.StringDecoder=i;function i(s){this.encoding=n(s);var p;switch(this.encoding){case"utf16le":this.text=u,this.end=m,p=4;break;case"utf8":this.fillLast=d,p=4;break;case"base64":this.text=v,this.end=R,p=3;break;default:this.write=A,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(p)}i.prototype.write=function(s){if(s.length===0)return"";var p,y;if(this.lastNeed){if(p=this.fillLast(s),p===void 0)return"";y=this.lastNeed,this.lastNeed=0}else y=0;return y>5===6?2:s>>4===14?3:s>>3===30?4:s>>6===2?-1:-2}function l(s,p,y){var S=p.length-1;if(S=0?(T>0&&(s.lastNeed=T-1),T):--S=0?(T>0&&(s.lastNeed=T-2),T):--S=0?(T>0&&(T===2?T=0:s.lastNeed=T-3),T):0))}function c(s,p,y){if((p[0]&192)!==128)return s.lastNeed=0,"�";if(s.lastNeed>1&&p.length>1){if((p[1]&192)!==128)return s.lastNeed=1,"�";if(s.lastNeed>2&&p.length>2&&(p[2]&192)!==128)return s.lastNeed=2,"�"}}function d(s){var p=this.lastTotal-this.lastNeed,y=c(this,s);if(y!==void 0)return y;if(this.lastNeed<=s.length)return s.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);s.copy(this.lastChar,p,0,s.length),this.lastNeed-=s.length}function b(s,p){var y=l(this,s,p);if(!this.lastNeed)return s.toString("utf8",p);this.lastTotal=y;var S=s.length-(y-this.lastNeed);return s.copy(this.lastChar,0,S),s.toString("utf8",p,S)}function E(s){var p=s&&s.length?this.write(s):"";return this.lastNeed?p+"�":p}function u(s,p){if((s.length-p)%2===0){var y=s.toString("utf16le",p);if(y){var S=y.charCodeAt(y.length-1);if(S>=55296&&S<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=s[s.length-2],this.lastChar[1]=s[s.length-1],y.slice(0,-1)}return y}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=s[s.length-1],s.toString("utf16le",p,s.length-1)}function m(s){var p=s&&s.length?this.write(s):"";if(this.lastNeed){var y=this.lastTotal-this.lastNeed;return p+this.lastChar.toString("utf16le",0,y)}return p}function v(s,p){var y=(s.length-p)%3;return y===0?s.toString("base64",p):(this.lastNeed=3-y,this.lastTotal=3,y===1?this.lastChar[0]=s[s.length-1]:(this.lastChar[0]=s[s.length-2],this.lastChar[1]=s[s.length-1]),s.toString("base64",p,s.length-y))}function R(s){var p=s&&s.length?this.write(s):"";return this.lastNeed?p+this.lastChar.toString("base64",0,3-this.lastNeed):p}function A(s){return s.toString(this.encoding)}function w(s){return s&&s.length?this.write(s):""}return Zt}var kr=pe.codes.ERR_STREAM_PREMATURE_CLOSE;function ai(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if(typeof o!="string"&&!N.objectMode&&Object.getPrototypeOf(o)!==n.prototype&&(o=f(o)),C)N.endEmitted?T(a,new s):W(a,N,o,!0);else if(N.ended)T(a,new A);else{if(N.destroyed)return!1;N.reading=!1,N.decoder&&!g?(o=N.decoder.write(o),N.objectMode||o.length!==0?W(a,N,o,!1):Y(a,N)):W(a,N,o,!1)}else C||(N.reading=!1,Y(a,N))}return!N.ended&&(N.length=q?a=q:(a--,a|=a>>>1,a|=a>>>2,a|=a>>>4,a|=a>>>8,a|=a>>>16,a++),a}function G(a,o){return a<=0||o.length===0&&o.ended?0:o.objectMode?1:a!==a?o.flowing&&o.length?o.buffer.head.data.length:o.length:(a>o.highWaterMark&&(o.highWaterMark=z(a)),a<=o.length?a:o.ended?o.length:(o.needReadable=!0,0))}M.prototype.read=function(a){d("read",a),a=parseInt(a,10);var o=this._readableState,g=a;if(a!==0&&(o.emittedReadable=!1),a===0&&o.needReadable&&((o.highWaterMark!==0?o.length>=o.highWaterMark:o.length>0)||o.ended))return d("read: emitReadable",o.length,o.ended),o.length===0&&o.ended?x(this):K(this),null;if(a=G(a,o),a===0&&o.ended)return o.length===0&&x(this),null;var C=o.needReadable;d("need readable",C),(o.length===0||o.length-a0?U=h(a,o):U=null,U===null?(o.needReadable=o.length<=o.highWaterMark,a=0):(o.length-=a,o.awaitDrain=0),o.length===0&&(o.ended||(o.needReadable=!0),g!==a&&o.ended&&x(this)),U!==null&&this.emit("data",U),U};function le(a,o){if(d("onEofChunk"),!o.ended){if(o.decoder){var g=o.decoder.end();g&&g.length&&(o.buffer.push(g),o.length+=o.objectMode?1:g.length)}o.ended=!0,o.sync?K(a):(o.needReadable=!1,o.emittedReadable||(o.emittedReadable=!0,ee(a)))}}function K(a){var o=a._readableState;d("emitReadable",o.needReadable,o.emittedReadable),o.needReadable=!1,o.emittedReadable||(d("emitReadable",o.flowing),o.emittedReadable=!0,process.nextTick(ee,a))}function ee(a){var o=a._readableState;d("emitReadable_",o.destroyed,o.length,o.ended),!o.destroyed&&(o.length||o.ended)&&(a.emit("readable"),o.emittedReadable=!1),o.needReadable=!o.flowing&&!o.ended&&o.length<=o.highWaterMark,_(a)}function Y(a,o){o.readingMore||(o.readingMore=!0,process.nextTick(te,a,o))}function te(a,o){for(;!o.reading&&!o.ended&&(o.length1&&L(C.pipes,a)!==-1)&&!Ce&&(d("false write response, pause",C.awaitDrain),C.awaitDrain++),g.pause())}function ye(ae){d("onerror",ae),_e(),a.removeListener("error",ye),t(a,"error")===0&&T(a,ae)}O(a,"error",ye);function we(){a.removeListener("finish",xe),_e()}a.once("close",we);function xe(){d("onfinish"),a.removeListener("close",we),_e()}a.once("finish",xe);function _e(){d("unpipe"),g.unpipe(a)}return a.emit("pipe",g),C.flowing||(d("pipe resume"),g.resume()),a};function ue(a){return function(){var g=a._readableState;d("pipeOnDrain",g.awaitDrain),g.awaitDrain&&g.awaitDrain--,g.awaitDrain===0&&t(a,"data")&&(g.flowing=!0,_(a))}}M.prototype.unpipe=function(a){var o=this._readableState,g={hasUnpiped:!1};if(o.pipesCount===0)return this;if(o.pipesCount===1)return a&&a!==o.pipes?this:(a||(a=o.pipes),o.pipes=null,o.pipesCount=0,o.flowing=!1,a&&a.emit("unpipe",this,g),this);if(!a){var C=o.pipes,U=o.pipesCount;o.pipes=null,o.pipesCount=0,o.flowing=!1;for(var N=0;N0,C.flowing!==!1&&this.resume()):a==="readable"&&!C.endEmitted&&!C.readableListening&&(C.readableListening=C.needReadable=!0,C.flowing=!1,C.emittedReadable=!1,d("on readable",C.length,C.reading),C.length?K(this):C.reading||process.nextTick(V,this)),g},M.prototype.addListener=M.prototype.on,M.prototype.removeListener=function(a,o){var g=r.prototype.removeListener.call(this,a,o);return a==="readable"&&process.nextTick(re,this),g},M.prototype.removeAllListeners=function(a){var o=r.prototype.removeAllListeners.apply(this,arguments);return(a==="readable"||a===void 0)&&process.nextTick(re,this),o};function re(a){var o=a._readableState;o.readableListening=a.listenerCount("readable")>0,o.resumeScheduled&&!o.paused?o.flowing=!0:a.listenerCount("data")>0&&a.resume()}function V(a){d("readable nexttick read 0"),a.read(0)}M.prototype.resume=function(){var a=this._readableState;return a.flowing||(d("resume"),a.flowing=!a.readableListening,he(this,a)),a.paused=!1,this};function he(a,o){o.resumeScheduled||(o.resumeScheduled=!0,process.nextTick(ne,a,o))}function ne(a,o){d("resume",o.reading),o.reading||a.read(0),o.resumeScheduled=!1,a.emit("resume"),_(a),o.flowing&&!o.reading&&a.read(0)}M.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function _(a){var o=a._readableState;for(d("flow",o.flowing);o.flowing&&a.read()!==null;);}M.prototype.wrap=function(a){var o=this,g=this._readableState,C=!1;a.on("end",function(){if(d("wrapped end"),g.decoder&&!g.ended){var P=g.decoder.end();P&&P.length&&o.push(P)}o.push(null)}),a.on("data",function(P){if(d("wrapped data"),g.decoder&&(P=g.decoder.write(P)),!(g.objectMode&&P==null)&&!(!g.objectMode&&(!P||!P.length))){var ie=o.push(P);ie||(C=!0,a.pause())}});for(var U in a)this[U]===void 0&&typeof a[U]=="function"&&(this[U]=function(ie){return function(){return a[ie].apply(a,arguments)}}(U));for(var N=0;N=o.length?(o.decoder?g=o.buffer.join(""):o.buffer.length===1?g=o.buffer.first():g=o.buffer.concat(o.length),o.buffer.clear()):g=o.buffer.consume(a,o.decoder),g}function x(a){var o=a._readableState;d("endReadable",o.endEmitted),o.endEmitted||(o.ended=!0,process.nextTick(k,o,a))}function k(a,o){if(d("endReadableNT",a.endEmitted,a.length),!a.endEmitted&&a.length===0&&(a.endEmitted=!0,o.readable=!1,o.emit("end"),a.autoDestroy)){var g=o._writableState;(!g||g.autoDestroy&&g.finished)&&o.destroy()}}typeof Symbol=="function"&&(M.from=function(a,o){return S===void 0&&(S=li()),S(M,a,o)});function L(a,o){for(var g=0,C=a.length;g0;return xi(l,d,b,function(E){i||(i=E),E&&f.forEach(Or),!d&&(f.forEach(Or),n(i))})});return t.reduce(Ei)}var Ri=Si;(function(e,t){t=e.exports=ln(),t.Stream=t,t.Readable=t,t.Writable=fn(),t.Duplex=me(),t.Transform=un,t.PassThrough=bi,t.finished=pr,t.pipeline=Ri})(ar,ar.exports);var cn=ar.exports;const{Transform:Ti}=cn;var Ai=e=>class dn extends Ti{constructor(r,n,i,f,l){super(l),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._hashBitLength=f,this._options=l,this._state=new e,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let f=null;try{this.update(r,n)}catch(l){f=l}i(f)}_flush(r){let n=null;try{this.push(this.digest())}catch(i){n=i}r(n)}update(r,n){if(!Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return Buffer.isBuffer(r)||(r=Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const r=new dn(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}};const{Transform:Ci}=cn;var Bi=e=>class pn extends Ci{constructor(r,n,i,f){super(f),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._options=f,this._state=new e,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let f=null;try{this.update(r,n)}catch(l){f=l}i(f)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return Buffer.isBuffer(r)||(r=Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let i=this._state.squeeze(r);return n!==void 0&&(i=i.toString(n)),i}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const r=new pn(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}};const ki=Ai,Mi=Bi;var Di=function(e){const t=ki(e),r=Mi(e);return function(n,i){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new t(1152,448,null,224,i);case"keccak256":return new t(1088,512,null,256,i);case"keccak384":return new t(832,768,null,384,i);case"keccak512":return new t(576,1024,null,512,i);case"sha3-224":return new t(1152,448,6,224,i);case"sha3-256":return new t(1088,512,6,256,i);case"sha3-384":return new t(832,768,6,384,i);case"sha3-512":return new t(576,1024,6,512,i);case"shake128":return new r(1344,256,31,i);case"shake256":return new r(1088,512,31,i);default:throw new Error("Invald algorithm: "+n)}}},bn={};const Ir=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];bn.p1600=function(e){for(let t=0;t<24;++t){const r=e[0]^e[10]^e[20]^e[30]^e[40],n=e[1]^e[11]^e[21]^e[31]^e[41],i=e[2]^e[12]^e[22]^e[32]^e[42],f=e[3]^e[13]^e[23]^e[33]^e[43],l=e[4]^e[14]^e[24]^e[34]^e[44],c=e[5]^e[15]^e[25]^e[35]^e[45],d=e[6]^e[16]^e[26]^e[36]^e[46],b=e[7]^e[17]^e[27]^e[37]^e[47],E=e[8]^e[18]^e[28]^e[38]^e[48],u=e[9]^e[19]^e[29]^e[39]^e[49];let m=E^(i<<1|f>>>31),v=u^(f<<1|i>>>31);const R=e[0]^m,A=e[1]^v,w=e[10]^m,s=e[11]^v,p=e[20]^m,y=e[21]^v,S=e[30]^m,T=e[31]^v,B=e[40]^m,O=e[41]^v;m=r^(l<<1|c>>>31),v=n^(c<<1|l>>>31);const D=e[2]^m,M=e[3]^v,F=e[12]^m,W=e[13]^v,Z=e[22]^m,q=e[23]^v,z=e[32]^m,G=e[33]^v,le=e[42]^m,K=e[43]^v;m=i^(d<<1|b>>>31),v=f^(b<<1|d>>>31);const ee=e[4]^m,Y=e[5]^v,te=e[14]^m,ue=e[15]^v,re=e[24]^m,V=e[25]^v,he=e[34]^m,ne=e[35]^v,_=e[44]^m,h=e[45]^v;m=l^(E<<1|u>>>31),v=c^(u<<1|E>>>31);const x=e[6]^m,k=e[7]^v,L=e[16]^m,a=e[17]^v,o=e[26]^m,g=e[27]^v,C=e[36]^m,U=e[37]^v,N=e[46]^m,P=e[47]^v;m=d^(r<<1|n>>>31),v=b^(n<<1|r>>>31);const ie=e[8]^m,ce=e[9]^v,Ce=e[18]^m,He=e[19]^v,Be=e[28]^m,ye=e[29]^v,we=e[38]^m,xe=e[39]^v,_e=e[48]^m,ae=e[49]^v,Q=R,et=A,tt=s<<4|w>>>28,rt=w<<4|s>>>28,nt=p<<3|y>>>29,it=y<<3|p>>>29,at=T<<9|S>>>23,ot=S<<9|T>>>23,ft=B<<18|O>>>14,st=O<<18|B>>>14,lt=D<<1|M>>>31,ut=M<<1|D>>>31,ht=W<<12|F>>>20,_t=F<<12|W>>>20,ct=Z<<10|q>>>22,dt=q<<10|Z>>>22,pt=G<<13|z>>>19,bt=z<<13|G>>>19,vt=le<<2|K>>>30,gt=K<<2|le>>>30,yt=Y<<30|ee>>>2,wt=ee<<30|Y>>>2,xt=te<<6|ue>>>26,Et=ue<<6|te>>>26,mt=V<<11|re>>>21,St=re<<11|V>>>21,Rt=he<<15|ne>>>17,Tt=ne<<15|he>>>17,At=h<<29|_>>>3,Ct=_<<29|h>>>3,Bt=x<<28|k>>>4,kt=k<<28|x>>>4,Mt=a<<23|L>>>9,Dt=L<<23|a>>>9,Nt=o<<25|g>>>7,Lt=g<<25|o>>>7,Pt=C<<21|U>>>11,Ot=U<<21|C>>>11,It=P<<24|N>>>8,$t=N<<24|P>>>8,Ft=ie<<27|ce>>>5,Ut=ce<<27|ie>>>5,Ht=Ce<<20|He>>>12,qt=He<<20|Ce>>>12,jt=ye<<7|Be>>>25,Wt=Be<<7|ye>>>25,zt=we<<8|xe>>>24,Gt=xe<<8|we>>>24,Vt=_e<<14|ae>>>18,Kt=ae<<14|_e>>>18;e[0]=Q^~ht&mt,e[1]=et^~_t&St,e[10]=Bt^~Ht&nt,e[11]=kt^~qt&it,e[20]=lt^~xt&Nt,e[21]=ut^~Et&Lt,e[30]=Ft^~tt&ct,e[31]=Ut^~rt&dt,e[40]=yt^~Mt&jt,e[41]=wt^~Dt&Wt,e[2]=ht^~mt&Pt,e[3]=_t^~St&Ot,e[12]=Ht^~nt&pt,e[13]=qt^~it&bt,e[22]=xt^~Nt&zt,e[23]=Et^~Lt&Gt,e[32]=tt^~ct&Rt,e[33]=rt^~dt&Tt,e[42]=Mt^~jt&at,e[43]=Dt^~Wt&ot,e[4]=mt^~Pt&Vt,e[5]=St^~Ot&Kt,e[14]=nt^~pt&At,e[15]=it^~bt&Ct,e[24]=Nt^~zt&ft,e[25]=Lt^~Gt&st,e[34]=ct^~Rt&It,e[35]=dt^~Tt&$t,e[44]=jt^~at&vt,e[45]=Wt^~ot>,e[6]=Pt^~Vt&Q,e[7]=Ot^~Kt&et,e[16]=pt^~At&Bt,e[17]=bt^~Ct&kt,e[26]=zt^~ft<,e[27]=Gt^~st&ut,e[36]=Rt^~It&Ft,e[37]=Tt^~$t&Ut,e[46]=at^~vt&yt,e[47]=ot^~gt&wt,e[8]=Vt^~Q&ht,e[9]=Kt^~et&_t,e[18]=At^~Bt&Ht,e[19]=Ct^~kt&qt,e[28]=ft^~lt&xt,e[29]=st^~ut&Et,e[38]=It^~Ft&tt,e[39]=$t^~Ut&rt,e[48]=vt^~yt&Mt,e[49]=gt^~wt&Dt,e[0]^=Ir[t*2],e[1]^=Ir[t*2+1]}};const Ge=bn;function Te(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}Te.prototype.initialize=function(e,t){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=e/8,this.count=0,this.squeezing=!1};Te.prototype.absorb=function(e){for(let t=0;t>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(Ge.p1600(this.state),this.count=0);return t};Te.prototype.copy=function(e){for(let t=0;t<50;++t)e.state[t]=this.state[t];e.blockSize=this.blockSize,e.count=this.count,e.squeezing=this.squeezing};var Ni=Te,Xa=Di(Ni),vn={exports:{}},fr={exports:{}};(function(e,t){var r=Le,n=r.Buffer;function i(l,c){for(var d in l)c[d]=l[d]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=f);function f(l,c,d){return n(l,c,d)}i(n,f),f.from=function(l,c,d){if(typeof l=="number")throw new TypeError("Argument must not be a number");return n(l,c,d)},f.alloc=function(l,c,d){if(typeof l!="number")throw new TypeError("Argument must be a number");var b=n(l);return c!==void 0?typeof d=="string"?b.fill(c,d):b.fill(c):b.fill(0),b},f.allocUnsafe=function(l){if(typeof l!="number")throw new TypeError("Argument must be a number");return n(l)},f.allocUnsafeSlow=function(l){if(typeof l!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(l)}})(fr,fr.exports);var be=fr.exports,gn=be.Buffer;function Xe(e,t){this._block=gn.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}Xe.prototype.update=function(e,t){typeof e=="string"&&(t=t||"utf8",e=gn.from(e,t));for(var r=this._block,n=this._blockSize,i=e.length,f=this._len,l=0;l=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=this._len*8;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(r&4294967295)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var f=this._hash();return e?f.toString(e):f};Xe.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var Ae=Xe,Li=J,yn=Ae,Pi=be.Buffer,Oi=[1518500249,1859775393,-1894007588,-899497514],Ii=new Array(80);function Pe(){this.init(),this._w=Ii,yn.call(this,64,56)}Li(Pe,yn);Pe.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function $i(e){return e<<5|e>>>27}function Fi(e){return e<<30|e>>>2}function Ui(e,t,r,n){return e===0?t&r|~t&n:e===2?t&r|t&n|r&n:t^r^n}Pe.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,f=this._d|0,l=this._e|0,c=0;c<16;++c)t[c]=e.readInt32BE(c*4);for(;c<80;++c)t[c]=t[c-3]^t[c-8]^t[c-14]^t[c-16];for(var d=0;d<80;++d){var b=~~(d/20),E=$i(r)+Ui(b,n,i,f)+l+t[d]+Oi[b]|0;l=f,f=i,i=Fi(n),n=r,r=E}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=f+this._d|0,this._e=l+this._e|0};Pe.prototype._hash=function(){var e=Pi.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var Hi=Pe,qi=J,wn=Ae,ji=be.Buffer,Wi=[1518500249,1859775393,-1894007588,-899497514],zi=new Array(80);function Oe(){this.init(),this._w=zi,wn.call(this,64,56)}qi(Oe,wn);Oe.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function Gi(e){return e<<1|e>>>31}function Vi(e){return e<<5|e>>>27}function Ki(e){return e<<30|e>>>2}function Yi(e,t,r,n){return e===0?t&r|~t&n:e===2?t&r|t&n|r&n:t^r^n}Oe.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,f=this._d|0,l=this._e|0,c=0;c<16;++c)t[c]=e.readInt32BE(c*4);for(;c<80;++c)t[c]=Gi(t[c-3]^t[c-8]^t[c-14]^t[c-16]);for(var d=0;d<80;++d){var b=~~(d/20),E=Vi(r)+Yi(b,n,i,f)+l+t[d]+Wi[b]|0;l=f,f=i,i=Ki(n),n=r,r=E}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=f+this._d|0,this._e=l+this._e|0};Oe.prototype._hash=function(){var e=ji.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var Xi=Oe,Ji=J,xn=Ae,Qi=be.Buffer,Zi=[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],ea=new Array(64);function Ie(){this.init(),this._w=ea,xn.call(this,64,56)}Ji(Ie,xn);Ie.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function ta(e,t,r){return r^e&(t^r)}function ra(e,t,r){return e&t|r&(e|t)}function na(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function ia(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function aa(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}function oa(e){return(e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10}Ie.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,f=this._d|0,l=this._e|0,c=this._f|0,d=this._g|0,b=this._h|0,E=0;E<16;++E)t[E]=e.readInt32BE(E*4);for(;E<64;++E)t[E]=oa(t[E-2])+t[E-7]+aa(t[E-15])+t[E-16]|0;for(var u=0;u<64;++u){var m=b+ia(l)+ta(l,c,d)+Zi[u]+t[u]|0,v=na(r)+ra(r,n,i)|0;b=d,d=c,c=l,l=f+m|0,f=i,i=n,n=r,r=m+v|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=f+this._d|0,this._e=l+this._e|0,this._f=c+this._f|0,this._g=d+this._g|0,this._h=b+this._h|0};Ie.prototype._hash=function(){var e=Qi.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e};var En=Ie,fa=J,sa=En,la=Ae,ua=be.Buffer,ha=new Array(64);function Je(){this.init(),this._w=ha,la.call(this,64,56)}fa(Je,sa);Je.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this};Je.prototype._hash=function(){var e=ua.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e};var _a=Je,ca=J,mn=Ae,da=be.Buffer,$r=[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],pa=new Array(160);function $e(){this.init(),this._w=pa,mn.call(this,128,112)}ca($e,mn);$e.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function Fr(e,t,r){return r^e&(t^r)}function Ur(e,t,r){return e&t|r&(e|t)}function Hr(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function qr(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function ba(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function va(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function ga(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function ya(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function j(e,t){return e>>>0>>0?1:0}$e.prototype._update=function(e){for(var t=this._w,r=this._ah|0,n=this._bh|0,i=this._ch|0,f=this._dh|0,l=this._eh|0,c=this._fh|0,d=this._gh|0,b=this._hh|0,E=this._al|0,u=this._bl|0,m=this._cl|0,v=this._dl|0,R=this._el|0,A=this._fl|0,w=this._gl|0,s=this._hl|0,p=0;p<32;p+=2)t[p]=e.readInt32BE(p*4),t[p+1]=e.readInt32BE(p*4+4);for(;p<160;p+=2){var y=t[p-30],S=t[p-15*2+1],T=ba(y,S),B=va(S,y);y=t[p-2*2],S=t[p-2*2+1];var O=ga(y,S),D=ya(S,y),M=t[p-7*2],F=t[p-7*2+1],W=t[p-16*2],Z=t[p-16*2+1],q=B+F|0,z=T+M+j(q,B)|0;q=q+D|0,z=z+O+j(q,D)|0,q=q+Z|0,z=z+W+j(q,Z)|0,t[p]=z,t[p+1]=q}for(var G=0;G<160;G+=2){z=t[G],q=t[G+1];var le=Ur(r,n,i),K=Ur(E,u,m),ee=Hr(r,E),Y=Hr(E,r),te=qr(l,R),ue=qr(R,l),re=$r[G],V=$r[G+1],he=Fr(l,c,d),ne=Fr(R,A,w),_=s+ue|0,h=b+te+j(_,s)|0;_=_+ne|0,h=h+he+j(_,ne)|0,_=_+V|0,h=h+re+j(_,V)|0,_=_+q|0,h=h+z+j(_,q)|0;var x=Y+K|0,k=ee+le+j(x,Y)|0;b=d,s=w,d=c,w=A,c=l,A=R,R=v+_|0,l=f+h+j(R,v)|0,f=i,v=m,i=n,m=u,n=r,u=E,E=_+x|0,r=h+k+j(E,_)|0}this._al=this._al+E|0,this._bl=this._bl+u|0,this._cl=this._cl+m|0,this._dl=this._dl+v|0,this._el=this._el+R|0,this._fl=this._fl+A|0,this._gl=this._gl+w|0,this._hl=this._hl+s|0,this._ah=this._ah+r+j(this._al,E)|0,this._bh=this._bh+n+j(this._bl,u)|0,this._ch=this._ch+i+j(this._cl,m)|0,this._dh=this._dh+f+j(this._dl,v)|0,this._eh=this._eh+l+j(this._el,R)|0,this._fh=this._fh+c+j(this._fl,A)|0,this._gh=this._gh+d+j(this._gl,w)|0,this._hh=this._hh+b+j(this._hl,s)|0};$e.prototype._hash=function(){var e=da.allocUnsafe(64);function t(r,n,i){e.writeInt32BE(r,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e};var Sn=$e,wa=J,xa=Sn,Ea=Ae,ma=be.Buffer,Sa=new Array(160);function Qe(){this.init(),this._w=Sa,Ea.call(this,128,112)}wa(Qe,xa);Qe.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this};Qe.prototype._hash=function(){var e=ma.allocUnsafe(48);function t(r,n,i){e.writeInt32BE(r,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e};var Ra=Qe,ve=vn.exports=function(t){t=t.toLowerCase();var r=ve[t];if(!r)throw new Error(t+" is not supported (we accept pull requests)");return new r};ve.sha=Hi;ve.sha1=Xi;ve.sha224=_a;ve.sha256=En;ve.sha384=Ra;ve.sha512=Sn;var Ja=vn.exports,Fe,$,Rn,Tn,de,jr,An,sr,br,lr,ur,Cn,Ne={},Bn=[],Ta=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ze=Array.isArray;function oe(e,t){for(var r in t)e[r]=t[r];return e}function kn(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function hr(e,t,r){var n,i,f,l={};for(f in t)f=="key"?n=t[f]:f=="ref"?i=t[f]:l[f]=t[f];if(arguments.length>2&&(l.children=arguments.length>3?Fe.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(f in e.defaultProps)l[f]===void 0&&(l[f]=e.defaultProps[f]);return ke(e,l,n,i,null)}function ke(e,t,r,n,i){var f={type:e,props:t,key:r,ref:n,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:i??++Rn,__i:-1,__u:0};return i==null&&$.vnode!=null&&$.vnode(f),f}function Aa(){return{current:null}}function Ue(e){return e.children}function Me(e,t){this.props=e,this.context=t}function Se(e,t){if(t==null)return e.__?Se(e.__,e.__i+1):null;for(var r;tt&&de.sort(sr));Ve.__r=0}function Dn(e,t,r,n,i,f,l,c,d,b,E){var u,m,v,R,A,w=n&&n.__k||Bn,s=t.length;for(r.__d=d,Ca(r,t,w),d=r.__d,u=0;u0?ke(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):i).__=e,i.__b=e.__b+1,f=null,(c=i.__i=Ba(i,r,l,E))!==-1&&(E--,(f=r[c])&&(f.__u|=131072)),f==null||f.__v===null?(c==-1&&u--,typeof i.type!="function"&&(i.__u|=65536)):c!==l&&(c==l-1?u--:c==l+1?u++:(c>l?u--:u++,i.__u|=65536))):i=e.__k[n]=null;if(E)for(n=0;n(d!=null&&!(131072&d.__u)?1:0))for(;l>=0||c=0){if((d=t[l])&&!(131072&d.__u)&&i==d.key&&f===d.type)return l;l--}if(c2&&(c.children=arguments.length>3?Fe.call(arguments,2):r),ke(e.type,c,n||e.key,i||e.ref,null)}function Na(e,t){var r={__c:t="__cC"+Cn++,__:e,Consumer:function(n,i){return n.children(i)},Provider:function(n){var i,f;return this.getChildContext||(i=new Set,(f={})[t]=this,this.getChildContext=function(){return f},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(l){this.props.value!==l.value&&i.forEach(function(c){c.__e=!0,_r(c)})},this.sub=function(l){i.add(l);var c=l.componentWillUnmount;l.componentWillUnmount=function(){i&&i.delete(l),c&&c.call(l)}}),n.children}};return r.Provider.__=r.Consumer.contextType=r}Fe=Bn.slice,$={__e:function(e,t,r,n){for(var i,f,l;t=t.__;)if((i=t.__c)&&!i.__)try{if((f=i.constructor)&&f.getDerivedStateFromError!=null&&(i.setState(f.getDerivedStateFromError(e)),l=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,n||{}),l=i.__d),l)return i.__E=i}catch(c){e=c}throw e}},Rn=0,Tn=function(e){return e!=null&&e.constructor==null},Me.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=oe({},this.state),typeof e=="function"&&(e=e(oe({},r),this.props)),e&&oe(r,e),e!=null&&this.__v&&(t&&this._sb.push(t),_r(this))},Me.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),_r(this))},Me.prototype.render=Ue,de=[],An=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,sr=function(e,t){return e.__v.__b-t.__v.__b},Ve.__r=0,br=0,lr=zr(!1),ur=zr(!0),Cn=0;const La=Object.freeze(Object.defineProperty({__proto__:null,Component:Me,Fragment:Ue,cloneElement:Da,createContext:Na,createElement:hr,createRef:Aa,h:hr,hydrate:$n,get isValidElement(){return Tn},get options(){return $},render:In,toChildArray:Ln},Symbol.toStringTag,{value:"Module"})),Qa=dr(La);var se,I,ir,Gr,Re=0,Fn=[],H=$,Vr=H.__b,Kr=H.__r,Yr=H.diffed,Xr=H.__c,Jr=H.unmount,Qr=H.__;function ge(e,t){H.__h&&H.__h(I,e,Re||t),Re=0;var r=I.__H||(I.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function Un(e){return Re=1,Hn(jn,e)}function Hn(e,t,r){var n=ge(se++,2);if(n.t=e,!n.__c&&(n.__=[r?r(t):jn(void 0,t),function(c){var d=n.__N?n.__N[0]:n.__[0],b=n.t(d,c);d!==b&&(n.__N=[b,n.__[1]],n.__c.setState({}))}],n.__c=I,!I.u)){var i=function(c,d,b){if(!n.__c.__H)return!0;var E=n.__c.__H.__.filter(function(m){return!!m.__c});if(E.every(function(m){return!m.__N}))return!f||f.call(this,c,d,b);var u=!1;return E.forEach(function(m){if(m.__N){var v=m.__[0];m.__=m.__N,m.__N=void 0,v!==m.__[0]&&(u=!0)}}),!(!u&&n.__c.props===c)&&(!f||f.call(this,c,d,b))};I.u=!0;var f=I.shouldComponentUpdate,l=I.componentWillUpdate;I.componentWillUpdate=function(c,d,b){if(this.__e){var E=f;f=void 0,i(c,d,b),f=E}l&&l.call(this,c,d,b)},I.shouldComponentUpdate=i}return n.__N||n.__}function Pa(e,t){var r=ge(se++,3);!H.__s&&wr(r.__H,t)&&(r.__=e,r.i=t,I.__H.__h.push(r))}function qn(e,t){var r=ge(se++,4);!H.__s&&wr(r.__H,t)&&(r.__=e,r.i=t,I.__h.push(r))}function Oa(e){return Re=5,yr(function(){return{current:e}},[])}function Ia(e,t,r){Re=6,qn(function(){return typeof e=="function"?(e(t()),function(){return e(null)}):e?(e.current=t(),function(){return e.current=null}):void 0},r==null?r:r.concat(e))}function yr(e,t){var r=ge(se++,7);return wr(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function $a(e,t){return Re=8,yr(function(){return e},t)}function Fa(e){var t=I.context[e.__c],r=ge(se++,9);return r.c=e,t?(r.__==null&&(r.__=!0,t.sub(I)),t.props.value):e.__}function Ua(e,t){H.useDebugValue&&H.useDebugValue(t?t(e):e)}function Ha(e){var t=ge(se++,10),r=Un();return t.__=e,I.componentDidCatch||(I.componentDidCatch=function(n,i){t.__&&t.__(n,i),r[1](n)}),[r[0],function(){r[1](void 0)}]}function qa(){var e=ge(se++,11);if(!e.__){for(var t=I.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var r=t.__m||(t.__m=[0,0]);e.__="P"+r[0]+"-"+r[1]++}return e.__}function ja(){for(var e;e=Fn.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(ze),e.__H.__h.forEach(cr),e.__H.__h=[]}catch(t){e.__H.__h=[],H.__e(t,e.__v)}}H.__b=function(e){I=null,Vr&&Vr(e)},H.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Qr&&Qr(e,t)},H.__r=function(e){Kr&&Kr(e),se=0;var t=(I=e.__c).__H;t&&(ir===I?(t.__h=[],I.__h=[],t.__.forEach(function(r){r.__N&&(r.__=r.__N),r.i=r.__N=void 0})):(t.__h.forEach(ze),t.__h.forEach(cr),t.__h=[],se=0)),ir=I},H.diffed=function(e){Yr&&Yr(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Fn.push(t)!==1&&Gr===H.requestAnimationFrame||((Gr=H.requestAnimationFrame)||Wa)(ja)),t.__H.__.forEach(function(r){r.i&&(r.__H=r.i),r.i=void 0})),ir=I=null},H.__c=function(e,t){t.some(function(r){try{r.__h.forEach(ze),r.__h=r.__h.filter(function(n){return!n.__||cr(n)})}catch(n){t.some(function(i){i.__h&&(i.__h=[])}),t=[],H.__e(n,r.__v)}}),Xr&&Xr(e,t)},H.unmount=function(e){Jr&&Jr(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{ze(n)}catch(i){t=i}}),r.__H=void 0,t&&H.__e(t,r.__v))};var Zr=typeof requestAnimationFrame=="function";function Wa(e){var t,r=function(){clearTimeout(n),Zr&&cancelAnimationFrame(t),setTimeout(e)},n=setTimeout(r,100);Zr&&(t=requestAnimationFrame(r))}function ze(e){var t=I,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),I=t}function cr(e){var t=I;e.__c=e.__(),I=t}function wr(e,t){return!e||e.length!==t.length||t.some(function(r,n){return r!==e[n]})}function jn(e,t){return typeof t=="function"?t(e):t}const za=Object.freeze(Object.defineProperty({__proto__:null,useCallback:$a,useContext:Fa,useDebugValue:Ua,useEffect:Pa,useErrorBoundary:Ha,useId:qa,useImperativeHandle:Ia,useLayoutEffect:qn,useMemo:yr,useReducer:Hn,useRef:Oa,useState:Un},Symbol.toStringTag,{value:"Module"})),Za=dr(za);export{Za as a,Ya as b,Xa as j,Qa as r,Ja as s}; diff --git a/buddybook/assets/index-B-6Lwopd.js b/buddybook/assets/index-B-6Lwopd.js new file mode 100644 index 0000000..da539c3 --- /dev/null +++ b/buddybook/assets/index-B-6Lwopd.js @@ -0,0 +1,4272 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-D2uqR4Ry.js","assets/hooks.module-D7M4pAco.js","assets/events-BzDGR98G.js","assets/inherits_browser-BwZ6FBWK.js","assets/index-FH8NN1-S.js","assets/index-Dz_NkDRB.js","assets/index.es-KLKTVizS.js"])))=>i.map(i=>d[i]); +var lu=Object.defineProperty;var Fs=et=>{throw TypeError(et)};var uu=(et,o,tt)=>o in et?lu(et,o,{enumerable:!0,configurable:!0,writable:!0,value:tt}):et[o]=tt;var wt=(et,o,tt)=>uu(et,typeof o!="symbol"?o+"":o,tt),as=(et,o,tt)=>o.has(et)||Fs("Cannot "+tt);var Lt=(et,o,tt)=>(as(et,o,"read from private field"),tt?tt.call(et):o.get(et)),hr=(et,o,tt)=>o.has(et)?Fs("Cannot add the same private member more than once"):o instanceof WeakSet?o.add(et):o.set(et,tt),ur=(et,o,tt,rt)=>(as(et,o,"write to private field"),rt?rt.call(et,tt):o.set(et,tt),tt),fr=(et,o,tt)=>(as(et,o,"access private method"),tt);var Cn=(et,o,tt,rt)=>({set _(nt){ur(et,o,nt,tt)},get _(){return Lt(et,o,rt)}});function _mergeNamespaces(et,o){for(var tt=0;ttrt[nt]})}}}return Object.freeze(Object.defineProperty(et,Symbol.toStringTag,{value:"Module"}))}(function(){const o=document.createElement("link").relList;if(o&&o.supports&&o.supports("modulepreload"))return;for(const nt of document.querySelectorAll('link[rel="modulepreload"]'))rt(nt);new MutationObserver(nt=>{for(const ot of nt)if(ot.type==="childList")for(const it of ot.addedNodes)it.tagName==="LINK"&&it.rel==="modulepreload"&&rt(it)}).observe(document,{childList:!0,subtree:!0});function tt(nt){const ot={};return nt.integrity&&(ot.integrity=nt.integrity),nt.referrerPolicy&&(ot.referrerPolicy=nt.referrerPolicy),nt.crossOrigin==="use-credentials"?ot.credentials="include":nt.crossOrigin==="anonymous"?ot.credentials="omit":ot.credentials="same-origin",ot}function rt(nt){if(nt.ep)return;nt.ep=!0;const ot=tt(nt);fetch(nt.href,ot)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(et){return et&&et.__esModule&&Object.prototype.hasOwnProperty.call(et,"default")?et.default:et}function getAugmentedNamespace(et){if(et.__esModule)return et;var o=et.default;if(typeof o=="function"){var tt=function rt(){return this instanceof rt?Reflect.construct(o,arguments,this.constructor):o.apply(this,arguments)};tt.prototype=o.prototype}else tt={};return Object.defineProperty(tt,"__esModule",{value:!0}),Object.keys(et).forEach(function(rt){var nt=Object.getOwnPropertyDescriptor(et,rt);Object.defineProperty(tt,rt,nt.get?nt:{enumerable:!0,get:function(){return et[rt]}})}),tt}var jsxRuntime={exports:{}},reactJsxRuntime_production_min={},react={exports:{}},react_production_min={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var l$4=Symbol.for("react.element"),n$5=Symbol.for("react.portal"),p$6=Symbol.for("react.fragment"),q$6=Symbol.for("react.strict_mode"),r$5=Symbol.for("react.profiler"),t$4=Symbol.for("react.provider"),u$3=Symbol.for("react.context"),v$5=Symbol.for("react.forward_ref"),w$4=Symbol.for("react.suspense"),x$2=Symbol.for("react.memo"),y$3=Symbol.for("react.lazy"),z$4=Symbol.iterator;function A$2(et){return et===null||typeof et!="object"?null:(et=z$4&&et[z$4]||et["@@iterator"],typeof et=="function"?et:null)}var B$2={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C$2=Object.assign,D$2={};function E$2(et,o,tt){this.props=et,this.context=o,this.refs=D$2,this.updater=tt||B$2}E$2.prototype.isReactComponent={};E$2.prototype.setState=function(et,o){if(typeof et!="object"&&typeof et!="function"&&et!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,et,o,"setState")};E$2.prototype.forceUpdate=function(et){this.updater.enqueueForceUpdate(this,et,"forceUpdate")};function F$1(){}F$1.prototype=E$2.prototype;function G$2(et,o,tt){this.props=et,this.context=o,this.refs=D$2,this.updater=tt||B$2}var H$2=G$2.prototype=new F$1;H$2.constructor=G$2;C$2(H$2,E$2.prototype);H$2.isPureReactComponent=!0;var I$2=Array.isArray,J$1=Object.prototype.hasOwnProperty,K$2={current:null},L$2={key:!0,ref:!0,__self:!0,__source:!0};function M$2(et,o,tt){var rt,nt={},ot=null,it=null;if(o!=null)for(rt in o.ref!==void 0&&(it=o.ref),o.key!==void 0&&(ot=""+o.key),o)J$1.call(o,rt)&&!L$2.hasOwnProperty(rt)&&(nt[rt]=o[rt]);var st=arguments.length-2;if(st===1)nt.children=tt;else if(1>>1,Kt=Bt[Xt];if(0>>1;Xtnt(tr,jt))ztnt(lr,tr)?(Bt[Xt]=lr,Bt[zt]=jt,Xt=zt):(Bt[Xt]=tr,Bt[Gt]=jt,Xt=Gt);else if(ztnt(lr,jt))Bt[Xt]=lr,Bt[zt]=jt,Xt=zt;else break e}}return Wt}function nt(Bt,Wt){var jt=Bt.sortIndex-Wt.sortIndex;return jt!==0?jt:Bt.id-Wt.id}if(typeof performance=="object"&&typeof performance.now=="function"){var ot=performance;et.unstable_now=function(){return ot.now()}}else{var it=Date,st=it.now();et.unstable_now=function(){return it.now()-st}}var at=[],ct=[],lt=1,dt=null,ht=3,mt=!1,ft=!1,pt=!1,gt=typeof setTimeout=="function"?setTimeout:null,yt=typeof clearTimeout=="function"?clearTimeout:null,bt=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function xt(Bt){for(var Wt=tt(ct);Wt!==null;){if(Wt.callback===null)rt(ct);else if(Wt.startTime<=Bt)rt(ct),Wt.sortIndex=Wt.expirationTime,o(at,Wt);else break;Wt=tt(ct)}}function vt(Bt){if(pt=!1,xt(Bt),!ft)if(tt(at)!==null)ft=!0,Qt(Et);else{var Wt=tt(ct);Wt!==null&&Vt(vt,Wt.startTime-Bt)}}function Et(Bt,Wt){ft=!1,pt&&(pt=!1,yt(At),At=-1),mt=!0;var jt=ht;try{for(xt(Wt),dt=tt(at);dt!==null&&(!(dt.expirationTime>Wt)||Bt&&!Ot());){var Xt=dt.callback;if(typeof Xt=="function"){dt.callback=null,ht=dt.priorityLevel;var Kt=Xt(dt.expirationTime<=Wt);Wt=et.unstable_now(),typeof Kt=="function"?dt.callback=Kt:dt===tt(at)&&rt(at),xt(Wt)}else rt(at);dt=tt(at)}if(dt!==null)var Pt=!0;else{var Gt=tt(ct);Gt!==null&&Vt(vt,Gt.startTime-Wt),Pt=!1}return Pt}finally{dt=null,ht=jt,mt=!1}}var Ct=!1,St=null,At=-1,kt=5,It=-1;function Ot(){return!(et.unstable_now()-ItBt||125Xt?(Bt.sortIndex=jt,o(ct,Bt),tt(at)===null&&Bt===tt(ct)&&(pt?(yt(At),At=-1):pt=!0,Vt(vt,jt-Xt))):(Bt.sortIndex=Kt,o(at,Bt),ft||mt||(ft=!0,Qt(Et))),Bt},et.unstable_shouldYield=Ot,et.unstable_wrapCallback=function(Bt){var Wt=ht;return function(){var jt=ht;ht=Wt;try{return Bt.apply(this,arguments)}finally{ht=jt}}}})(scheduler_production_min);scheduler.exports=scheduler_production_min;var schedulerExports=scheduler.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var aa=reactExports,ca$1=schedulerExports;function p$4(et){for(var o="https://reactjs.org/docs/error-decoder.html?invariant="+et,tt=1;tt"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ja=Object.prototype.hasOwnProperty,ka=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,la={},ma={};function oa(et){return ja.call(ma,et)?!0:ja.call(la,et)?!1:ka.test(et)?ma[et]=!0:(la[et]=!0,!1)}function pa(et,o,tt,rt){if(tt!==null&&tt.type===0)return!1;switch(typeof o){case"function":case"symbol":return!0;case"boolean":return rt?!1:tt!==null?!tt.acceptsBooleans:(et=et.toLowerCase().slice(0,5),et!=="data-"&&et!=="aria-");default:return!1}}function qa(et,o,tt,rt){if(o===null||typeof o>"u"||pa(et,o,tt,rt))return!0;if(rt)return!1;if(tt!==null)switch(tt.type){case 3:return!o;case 4:return o===!1;case 5:return isNaN(o);case 6:return isNaN(o)||1>o}return!1}function v$4(et,o,tt,rt,nt,ot,it){this.acceptsBooleans=o===2||o===3||o===4,this.attributeName=rt,this.attributeNamespace=nt,this.mustUseProperty=tt,this.propertyName=et,this.type=o,this.sanitizeURL=ot,this.removeEmptyString=it}var z$3={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(et){z$3[et]=new v$4(et,0,!1,et,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(et){var o=et[0];z$3[o]=new v$4(o,1,!1,et[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(et){z$3[et]=new v$4(et,2,!1,et.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(et){z$3[et]=new v$4(et,2,!1,et,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(et){z$3[et]=new v$4(et,3,!1,et.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(et){z$3[et]=new v$4(et,3,!0,et,null,!1,!1)});["capture","download"].forEach(function(et){z$3[et]=new v$4(et,4,!1,et,null,!1,!1)});["cols","rows","size","span"].forEach(function(et){z$3[et]=new v$4(et,6,!1,et,null,!1,!1)});["rowSpan","start"].forEach(function(et){z$3[et]=new v$4(et,5,!1,et.toLowerCase(),null,!1,!1)});var ra$1=/[\-:]([a-z])/g;function sa(et){return et[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(et){var o=et.replace(ra$1,sa);z$3[o]=new v$4(o,1,!1,et,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(et){var o=et.replace(ra$1,sa);z$3[o]=new v$4(o,1,!1,et,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(et){var o=et.replace(ra$1,sa);z$3[o]=new v$4(o,1,!1,et,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(et){z$3[et]=new v$4(et,1,!1,et.toLowerCase(),null,!1,!1)});z$3.xlinkHref=new v$4("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(et){z$3[et]=new v$4(et,1,!1,et.toLowerCase(),null,!0,!0)});function ta(et,o,tt,rt){var nt=z$3.hasOwnProperty(o)?z$3[o]:null;(nt!==null?nt.type!==0:rt||!(2st||nt[it]!==ot[st]){var at=` +`+nt[it].replace(" at new "," at ");return et.displayName&&at.includes("")&&(at=at.replace("",et.displayName)),at}while(1<=it&&0<=st);break}}}finally{Na=!1,Error.prepareStackTrace=tt}return(et=et?et.displayName||et.name:"")?Ma(et):""}function Pa(et){switch(et.tag){case 5:return Ma(et.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return et=Oa(et.type,!1),et;case 11:return et=Oa(et.type.render,!1),et;case 1:return et=Oa(et.type,!0),et;default:return""}}function Qa(et){if(et==null)return null;if(typeof et=="function")return et.displayName||et.name||null;if(typeof et=="string")return et;switch(et){case ya:return"Fragment";case wa:return"Portal";case Aa:return"Profiler";case za:return"StrictMode";case Ea:return"Suspense";case Fa:return"SuspenseList"}if(typeof et=="object")switch(et.$$typeof){case Ca:return(et.displayName||"Context")+".Consumer";case Ba:return(et._context.displayName||"Context")+".Provider";case Da:var o=et.render;return et=et.displayName,et||(et=o.displayName||o.name||"",et=et!==""?"ForwardRef("+et+")":"ForwardRef"),et;case Ga:return o=et.displayName||null,o!==null?o:Qa(et.type)||"Memo";case Ha:o=et._payload,et=et._init;try{return Qa(et(o))}catch{}}return null}function Ra(et){var o=et.type;switch(et.tag){case 24:return"Cache";case 9:return(o.displayName||"Context")+".Consumer";case 10:return(o._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return et=o.render,et=et.displayName||et.name||"",o.displayName||(et!==""?"ForwardRef("+et+")":"ForwardRef");case 7:return"Fragment";case 5:return o;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Qa(o);case 8:return o===za?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof o=="function")return o.displayName||o.name||null;if(typeof o=="string")return o}return null}function Sa(et){switch(typeof et){case"boolean":case"number":case"string":case"undefined":return et;case"object":return et;default:return""}}function Ta(et){var o=et.type;return(et=et.nodeName)&&et.toLowerCase()==="input"&&(o==="checkbox"||o==="radio")}function Ua(et){var o=Ta(et)?"checked":"value",tt=Object.getOwnPropertyDescriptor(et.constructor.prototype,o),rt=""+et[o];if(!et.hasOwnProperty(o)&&typeof tt<"u"&&typeof tt.get=="function"&&typeof tt.set=="function"){var nt=tt.get,ot=tt.set;return Object.defineProperty(et,o,{configurable:!0,get:function(){return nt.call(this)},set:function(it){rt=""+it,ot.call(this,it)}}),Object.defineProperty(et,o,{enumerable:tt.enumerable}),{getValue:function(){return rt},setValue:function(it){rt=""+it},stopTracking:function(){et._valueTracker=null,delete et[o]}}}}function Va(et){et._valueTracker||(et._valueTracker=Ua(et))}function Wa(et){if(!et)return!1;var o=et._valueTracker;if(!o)return!0;var tt=o.getValue(),rt="";return et&&(rt=Ta(et)?et.checked?"true":"false":et.value),et=rt,et!==tt?(o.setValue(et),!0):!1}function Xa(et){if(et=et||(typeof document<"u"?document:void 0),typeof et>"u")return null;try{return et.activeElement||et.body}catch{return et.body}}function Ya(et,o){var tt=o.checked;return A$1({},o,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:tt??et._wrapperState.initialChecked})}function Za(et,o){var tt=o.defaultValue==null?"":o.defaultValue,rt=o.checked!=null?o.checked:o.defaultChecked;tt=Sa(o.value!=null?o.value:tt),et._wrapperState={initialChecked:rt,initialValue:tt,controlled:o.type==="checkbox"||o.type==="radio"?o.checked!=null:o.value!=null}}function ab(et,o){o=o.checked,o!=null&&ta(et,"checked",o,!1)}function bb(et,o){ab(et,o);var tt=Sa(o.value),rt=o.type;if(tt!=null)rt==="number"?(tt===0&&et.value===""||et.value!=tt)&&(et.value=""+tt):et.value!==""+tt&&(et.value=""+tt);else if(rt==="submit"||rt==="reset"){et.removeAttribute("value");return}o.hasOwnProperty("value")?cb$1(et,o.type,tt):o.hasOwnProperty("defaultValue")&&cb$1(et,o.type,Sa(o.defaultValue)),o.checked==null&&o.defaultChecked!=null&&(et.defaultChecked=!!o.defaultChecked)}function db(et,o,tt){if(o.hasOwnProperty("value")||o.hasOwnProperty("defaultValue")){var rt=o.type;if(!(rt!=="submit"&&rt!=="reset"||o.value!==void 0&&o.value!==null))return;o=""+et._wrapperState.initialValue,tt||o===et.value||(et.value=o),et.defaultValue=o}tt=et.name,tt!==""&&(et.name=""),et.defaultChecked=!!et._wrapperState.initialChecked,tt!==""&&(et.name=tt)}function cb$1(et,o,tt){(o!=="number"||Xa(et.ownerDocument)!==et)&&(tt==null?et.defaultValue=""+et._wrapperState.initialValue:et.defaultValue!==""+tt&&(et.defaultValue=""+tt))}var eb=Array.isArray;function fb(et,o,tt,rt){if(et=et.options,o){o={};for(var nt=0;nt"+o.valueOf().toString()+"",o=mb.firstChild;et.firstChild;)et.removeChild(et.firstChild);for(;o.firstChild;)et.appendChild(o.firstChild)}});function ob(et,o){if(o){var tt=et.firstChild;if(tt&&tt===et.lastChild&&tt.nodeType===3){tt.nodeValue=o;return}}et.textContent=o}var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(et){qb.forEach(function(o){o=o+et.charAt(0).toUpperCase()+et.substring(1),pb[o]=pb[et]})});function rb(et,o,tt){return o==null||typeof o=="boolean"||o===""?"":tt||typeof o!="number"||o===0||pb.hasOwnProperty(et)&&pb[et]?(""+o).trim():o+"px"}function sb(et,o){et=et.style;for(var tt in o)if(o.hasOwnProperty(tt)){var rt=tt.indexOf("--")===0,nt=rb(tt,o[tt],rt);tt==="float"&&(tt="cssFloat"),rt?et.setProperty(tt,nt):et[tt]=nt}}var tb=A$1({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ub(et,o){if(o){if(tb[et]&&(o.children!=null||o.dangerouslySetInnerHTML!=null))throw Error(p$4(137,et));if(o.dangerouslySetInnerHTML!=null){if(o.children!=null)throw Error(p$4(60));if(typeof o.dangerouslySetInnerHTML!="object"||!("__html"in o.dangerouslySetInnerHTML))throw Error(p$4(61))}if(o.style!=null&&typeof o.style!="object")throw Error(p$4(62))}}function vb(et,o){if(et.indexOf("-")===-1)return typeof o.is=="string";switch(et){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var wb=null;function xb(et){return et=et.target||et.srcElement||window,et.correspondingUseElement&&(et=et.correspondingUseElement),et.nodeType===3?et.parentNode:et}var yb=null,zb=null,Ab=null;function Bb(et){if(et=Cb(et)){if(typeof yb!="function")throw Error(p$4(280));var o=et.stateNode;o&&(o=Db(o),yb(et.stateNode,et.type,o))}}function Eb(et){zb?Ab?Ab.push(et):Ab=[et]:zb=et}function Fb(){if(zb){var et=zb,o=Ab;if(Ab=zb=null,Bb(et),o)for(et=0;et>>=0,et===0?32:31-(pc(et)/qc|0)|0}var rc=64,sc=4194304;function tc(et){switch(et&-et){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return et&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return et&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return et}}function uc(et,o){var tt=et.pendingLanes;if(tt===0)return 0;var rt=0,nt=et.suspendedLanes,ot=et.pingedLanes,it=tt&268435455;if(it!==0){var st=it&~nt;st!==0?rt=tc(st):(ot&=it,ot!==0&&(rt=tc(ot)))}else it=tt&~nt,it!==0?rt=tc(it):ot!==0&&(rt=tc(ot));if(rt===0)return 0;if(o!==0&&o!==rt&&!(o&nt)&&(nt=rt&-rt,ot=o&-o,nt>=ot||nt===16&&(ot&4194240)!==0))return o;if(rt&4&&(rt|=tt&16),o=et.entangledLanes,o!==0)for(et=et.entanglements,o&=rt;0tt;tt++)o.push(et);return o}function Ac(et,o,tt){et.pendingLanes|=o,o!==536870912&&(et.suspendedLanes=0,et.pingedLanes=0),et=et.eventTimes,o=31-oc(o),et[o]=tt}function Bc(et,o){var tt=et.pendingLanes&~o;et.pendingLanes=o,et.suspendedLanes=0,et.pingedLanes=0,et.expiredLanes&=o,et.mutableReadLanes&=o,et.entangledLanes&=o,o=et.entanglements;var rt=et.eventTimes;for(et=et.expirationTimes;0=be$1),ee$1=" ",fe$1=!1;function ge$1(et,o){switch(et){case"keyup":return $d.indexOf(o.keyCode)!==-1;case"keydown":return o.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function he$1(et){return et=et.detail,typeof et=="object"&&"data"in et?et.data:null}var ie$1=!1;function je$1(et,o){switch(et){case"compositionend":return he$1(o);case"keypress":return o.which!==32?null:(fe$1=!0,ee$1);case"textInput":return et=o.data,et===ee$1&&fe$1?null:et;default:return null}}function ke$1(et,o){if(ie$1)return et==="compositionend"||!ae$1&&ge$1(et,o)?(et=nd(),md=ld=kd=null,ie$1=!1,et):null;switch(et){case"paste":return null;case"keypress":if(!(o.ctrlKey||o.altKey||o.metaKey)||o.ctrlKey&&o.altKey){if(o.char&&1=o)return{node:tt,offset:o-et};et=rt}e:{for(;tt;){if(tt.nextSibling){tt=tt.nextSibling;break e}tt=tt.parentNode}tt=void 0}tt=Je(tt)}}function Le$1(et,o){return et&&o?et===o?!0:et&&et.nodeType===3?!1:o&&o.nodeType===3?Le$1(et,o.parentNode):"contains"in et?et.contains(o):et.compareDocumentPosition?!!(et.compareDocumentPosition(o)&16):!1:!1}function Me$1(){for(var et=window,o=Xa();o instanceof et.HTMLIFrameElement;){try{var tt=typeof o.contentWindow.location.href=="string"}catch{tt=!1}if(tt)et=o.contentWindow;else break;o=Xa(et.document)}return o}function Ne$1(et){var o=et&&et.nodeName&&et.nodeName.toLowerCase();return o&&(o==="input"&&(et.type==="text"||et.type==="search"||et.type==="tel"||et.type==="url"||et.type==="password")||o==="textarea"||et.contentEditable==="true")}function Oe$1(et){var o=Me$1(),tt=et.focusedElem,rt=et.selectionRange;if(o!==tt&&tt&&tt.ownerDocument&&Le$1(tt.ownerDocument.documentElement,tt)){if(rt!==null&&Ne$1(tt)){if(o=rt.start,et=rt.end,et===void 0&&(et=o),"selectionStart"in tt)tt.selectionStart=o,tt.selectionEnd=Math.min(et,tt.value.length);else if(et=(o=tt.ownerDocument||document)&&o.defaultView||window,et.getSelection){et=et.getSelection();var nt=tt.textContent.length,ot=Math.min(rt.start,nt);rt=rt.end===void 0?ot:Math.min(rt.end,nt),!et.extend&&ot>rt&&(nt=rt,rt=ot,ot=nt),nt=Ke(tt,ot);var it=Ke(tt,rt);nt&&it&&(et.rangeCount!==1||et.anchorNode!==nt.node||et.anchorOffset!==nt.offset||et.focusNode!==it.node||et.focusOffset!==it.offset)&&(o=o.createRange(),o.setStart(nt.node,nt.offset),et.removeAllRanges(),ot>rt?(et.addRange(o),et.extend(it.node,it.offset)):(o.setEnd(it.node,it.offset),et.addRange(o)))}}for(o=[],et=tt;et=et.parentNode;)et.nodeType===1&&o.push({element:et,left:et.scrollLeft,top:et.scrollTop});for(typeof tt.focus=="function"&&tt.focus(),tt=0;tt=document.documentMode,Qe=null,Re$1=null,Se$1=null,Te$1=!1;function Ue(et,o,tt){var rt=tt.window===tt?tt.document:tt.nodeType===9?tt:tt.ownerDocument;Te$1||Qe==null||Qe!==Xa(rt)||(rt=Qe,"selectionStart"in rt&&Ne$1(rt)?rt={start:rt.selectionStart,end:rt.selectionEnd}:(rt=(rt.ownerDocument&&rt.ownerDocument.defaultView||window).getSelection(),rt={anchorNode:rt.anchorNode,anchorOffset:rt.anchorOffset,focusNode:rt.focusNode,focusOffset:rt.focusOffset}),Se$1&&Ie(Se$1,rt)||(Se$1=rt,rt=oe$1(Re$1,"onSelect"),0Tf||(et.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G$1(et,o){Tf++,Sf[Tf]=et.current,et.current=o}var Vf={},H$1=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(et,o){var tt=et.type.contextTypes;if(!tt)return Vf;var rt=et.stateNode;if(rt&&rt.__reactInternalMemoizedUnmaskedChildContext===o)return rt.__reactInternalMemoizedMaskedChildContext;var nt={},ot;for(ot in tt)nt[ot]=o[ot];return rt&&(et=et.stateNode,et.__reactInternalMemoizedUnmaskedChildContext=o,et.__reactInternalMemoizedMaskedChildContext=nt),nt}function Zf(et){return et=et.childContextTypes,et!=null}function $f(){E$1(Wf),E$1(H$1)}function ag(et,o,tt){if(H$1.current!==Vf)throw Error(p$4(168));G$1(H$1,o),G$1(Wf,tt)}function bg(et,o,tt){var rt=et.stateNode;if(o=o.childContextTypes,typeof rt.getChildContext!="function")return tt;rt=rt.getChildContext();for(var nt in rt)if(!(nt in o))throw Error(p$4(108,Ra(et)||"Unknown",nt));return A$1({},tt,rt)}function cg(et){return et=(et=et.stateNode)&&et.__reactInternalMemoizedMergedChildContext||Vf,Xf=H$1.current,G$1(H$1,et),G$1(Wf,Wf.current),!0}function dg(et,o,tt){var rt=et.stateNode;if(!rt)throw Error(p$4(169));tt?(et=bg(et,o,Xf),rt.__reactInternalMemoizedMergedChildContext=et,E$1(Wf),E$1(H$1),G$1(H$1,et)):E$1(Wf),G$1(Wf,tt)}var eg=null,fg=!1,gg=!1;function hg(et){eg===null?eg=[et]:eg.push(et)}function ig(et){fg=!0,hg(et)}function jg(){if(!gg&&eg!==null){gg=!0;var et=0,o=C$1;try{var tt=eg;for(C$1=1;et>=it,nt-=it,rg=1<<32-oc(o)+nt|tt<At?(kt=St,St=null):kt=St.sibling;var It=ht(yt,St,xt[At],vt);if(It===null){St===null&&(St=kt);break}et&&St&&It.alternate===null&&o(yt,St),bt=ot(It,bt,At),Ct===null?Et=It:Ct.sibling=It,Ct=It,St=kt}if(At===xt.length)return tt(yt,St),I$1&&tg(yt,At),Et;if(St===null){for(;AtAt?(kt=St,St=null):kt=St.sibling;var Ot=ht(yt,St,It.value,vt);if(Ot===null){St===null&&(St=kt);break}et&&St&&Ot.alternate===null&&o(yt,St),bt=ot(Ot,bt,At),Ct===null?Et=Ot:Ct.sibling=Ot,Ct=Ot,St=kt}if(It.done)return tt(yt,St),I$1&&tg(yt,At),Et;if(St===null){for(;!It.done;At++,It=xt.next())It=dt(yt,It.value,vt),It!==null&&(bt=ot(It,bt,At),Ct===null?Et=It:Ct.sibling=It,Ct=It);return I$1&&tg(yt,At),Et}for(St=rt(yt,St);!It.done;At++,It=xt.next())It=mt(St,yt,At,It.value,vt),It!==null&&(et&&It.alternate!==null&&St.delete(It.key===null?At:It.key),bt=ot(It,bt,At),Ct===null?Et=It:Ct.sibling=It,Ct=It);return et&&St.forEach(function(Nt){return o(yt,Nt)}),I$1&&tg(yt,At),Et}function gt(yt,bt,xt,vt){if(typeof xt=="object"&&xt!==null&&xt.type===ya&&xt.key===null&&(xt=xt.props.children),typeof xt=="object"&&xt!==null){switch(xt.$$typeof){case va:e:{for(var Et=xt.key,Ct=bt;Ct!==null;){if(Ct.key===Et){if(Et=xt.type,Et===ya){if(Ct.tag===7){tt(yt,Ct.sibling),bt=nt(Ct,xt.props.children),bt.return=yt,yt=bt;break e}}else if(Ct.elementType===Et||typeof Et=="object"&&Et!==null&&Et.$$typeof===Ha&&Ng(Et)===Ct.type){tt(yt,Ct.sibling),bt=nt(Ct,xt.props),bt.ref=Lg(yt,Ct,xt),bt.return=yt,yt=bt;break e}tt(yt,Ct);break}else o(yt,Ct);Ct=Ct.sibling}xt.type===ya?(bt=Tg(xt.props.children,yt.mode,vt,xt.key),bt.return=yt,yt=bt):(vt=Rg(xt.type,xt.key,xt.props,null,yt.mode,vt),vt.ref=Lg(yt,bt,xt),vt.return=yt,yt=vt)}return it(yt);case wa:e:{for(Ct=xt.key;bt!==null;){if(bt.key===Ct)if(bt.tag===4&&bt.stateNode.containerInfo===xt.containerInfo&&bt.stateNode.implementation===xt.implementation){tt(yt,bt.sibling),bt=nt(bt,xt.children||[]),bt.return=yt,yt=bt;break e}else{tt(yt,bt);break}else o(yt,bt);bt=bt.sibling}bt=Sg(xt,yt.mode,vt),bt.return=yt,yt=bt}return it(yt);case Ha:return Ct=xt._init,gt(yt,bt,Ct(xt._payload),vt)}if(eb(xt))return ft(yt,bt,xt,vt);if(Ka(xt))return pt(yt,bt,xt,vt);Mg(yt,xt)}return typeof xt=="string"&&xt!==""||typeof xt=="number"?(xt=""+xt,bt!==null&&bt.tag===6?(tt(yt,bt.sibling),bt=nt(bt,xt),bt.return=yt,yt=bt):(tt(yt,bt),bt=Qg(xt,yt.mode,vt),bt.return=yt,yt=bt),it(yt)):tt(yt,bt)}return gt}var Ug=Og(!0),Vg=Og(!1),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null}function ah(et){var o=Wg.current;E$1(Wg),et._currentValue=o}function bh(et,o,tt){for(;et!==null;){var rt=et.alternate;if((et.childLanes&o)!==o?(et.childLanes|=o,rt!==null&&(rt.childLanes|=o)):rt!==null&&(rt.childLanes&o)!==o&&(rt.childLanes|=o),et===tt)break;et=et.return}}function ch(et,o){Xg=et,Zg=Yg=null,et=et.dependencies,et!==null&&et.firstContext!==null&&(et.lanes&o&&(dh=!0),et.firstContext=null)}function eh(et){var o=et._currentValue;if(Zg!==et)if(et={context:et,memoizedValue:o,next:null},Yg===null){if(Xg===null)throw Error(p$4(308));Yg=et,Xg.dependencies={lanes:0,firstContext:et}}else Yg=Yg.next=et;return o}var fh=null;function gh(et){fh===null?fh=[et]:fh.push(et)}function hh(et,o,tt,rt){var nt=o.interleaved;return nt===null?(tt.next=tt,gh(o)):(tt.next=nt.next,nt.next=tt),o.interleaved=tt,ih(et,rt)}function ih(et,o){et.lanes|=o;var tt=et.alternate;for(tt!==null&&(tt.lanes|=o),tt=et,et=et.return;et!==null;)et.childLanes|=o,tt=et.alternate,tt!==null&&(tt.childLanes|=o),tt=et,et=et.return;return tt.tag===3?tt.stateNode:null}var jh=!1;function kh(et){et.updateQueue={baseState:et.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function lh(et,o){et=et.updateQueue,o.updateQueue===et&&(o.updateQueue={baseState:et.baseState,firstBaseUpdate:et.firstBaseUpdate,lastBaseUpdate:et.lastBaseUpdate,shared:et.shared,effects:et.effects})}function mh(et,o){return{eventTime:et,lane:o,tag:0,payload:null,callback:null,next:null}}function nh(et,o,tt){var rt=et.updateQueue;if(rt===null)return null;if(rt=rt.shared,K$1&2){var nt=rt.pending;return nt===null?o.next=o:(o.next=nt.next,nt.next=o),rt.pending=o,ih(et,tt)}return nt=rt.interleaved,nt===null?(o.next=o,gh(rt)):(o.next=nt.next,nt.next=o),rt.interleaved=o,ih(et,tt)}function oh(et,o,tt){if(o=o.updateQueue,o!==null&&(o=o.shared,(tt&4194240)!==0)){var rt=o.lanes;rt&=et.pendingLanes,tt|=rt,o.lanes=tt,Cc(et,tt)}}function ph(et,o){var tt=et.updateQueue,rt=et.alternate;if(rt!==null&&(rt=rt.updateQueue,tt===rt)){var nt=null,ot=null;if(tt=tt.firstBaseUpdate,tt!==null){do{var it={eventTime:tt.eventTime,lane:tt.lane,tag:tt.tag,payload:tt.payload,callback:tt.callback,next:null};ot===null?nt=ot=it:ot=ot.next=it,tt=tt.next}while(tt!==null);ot===null?nt=ot=o:ot=ot.next=o}else nt=ot=o;tt={baseState:rt.baseState,firstBaseUpdate:nt,lastBaseUpdate:ot,shared:rt.shared,effects:rt.effects},et.updateQueue=tt;return}et=tt.lastBaseUpdate,et===null?tt.firstBaseUpdate=o:et.next=o,tt.lastBaseUpdate=o}function qh(et,o,tt,rt){var nt=et.updateQueue;jh=!1;var ot=nt.firstBaseUpdate,it=nt.lastBaseUpdate,st=nt.shared.pending;if(st!==null){nt.shared.pending=null;var at=st,ct=at.next;at.next=null,it===null?ot=ct:it.next=ct,it=at;var lt=et.alternate;lt!==null&&(lt=lt.updateQueue,st=lt.lastBaseUpdate,st!==it&&(st===null?lt.firstBaseUpdate=ct:st.next=ct,lt.lastBaseUpdate=at))}if(ot!==null){var dt=nt.baseState;it=0,lt=ct=at=null,st=ot;do{var ht=st.lane,mt=st.eventTime;if((rt&ht)===ht){lt!==null&&(lt=lt.next={eventTime:mt,lane:0,tag:st.tag,payload:st.payload,callback:st.callback,next:null});e:{var ft=et,pt=st;switch(ht=o,mt=tt,pt.tag){case 1:if(ft=pt.payload,typeof ft=="function"){dt=ft.call(mt,dt,ht);break e}dt=ft;break e;case 3:ft.flags=ft.flags&-65537|128;case 0:if(ft=pt.payload,ht=typeof ft=="function"?ft.call(mt,dt,ht):ft,ht==null)break e;dt=A$1({},dt,ht);break e;case 2:jh=!0}}st.callback!==null&&st.lane!==0&&(et.flags|=64,ht=nt.effects,ht===null?nt.effects=[st]:ht.push(st))}else mt={eventTime:mt,lane:ht,tag:st.tag,payload:st.payload,callback:st.callback,next:null},lt===null?(ct=lt=mt,at=dt):lt=lt.next=mt,it|=ht;if(st=st.next,st===null){if(st=nt.shared.pending,st===null)break;ht=st,st=ht.next,ht.next=null,nt.lastBaseUpdate=ht,nt.shared.pending=null}}while(!0);if(lt===null&&(at=dt),nt.baseState=at,nt.firstBaseUpdate=ct,nt.lastBaseUpdate=lt,o=nt.shared.interleaved,o!==null){nt=o;do it|=nt.lane,nt=nt.next;while(nt!==o)}else ot===null&&(nt.shared.lanes=0);rh|=it,et.lanes=it,et.memoizedState=dt}}function sh(et,o,tt){if(et=o.effects,o.effects=null,et!==null)for(o=0;ott?tt:4,et(!0);var rt=Gh.transition;Gh.transition={};try{et(!1),o()}finally{C$1=tt,Gh.transition=rt}}function wi(){return Uh().memoizedState}function xi(et,o,tt){var rt=yi(et);if(tt={lane:rt,action:tt,hasEagerState:!1,eagerState:null,next:null},zi(et))Ai(o,tt);else if(tt=hh(et,o,tt,rt),tt!==null){var nt=R();gi(tt,et,rt,nt),Bi(tt,o,rt)}}function ii(et,o,tt){var rt=yi(et),nt={lane:rt,action:tt,hasEagerState:!1,eagerState:null,next:null};if(zi(et))Ai(o,nt);else{var ot=et.alternate;if(et.lanes===0&&(ot===null||ot.lanes===0)&&(ot=o.lastRenderedReducer,ot!==null))try{var it=o.lastRenderedState,st=ot(it,tt);if(nt.hasEagerState=!0,nt.eagerState=st,He(st,it)){var at=o.interleaved;at===null?(nt.next=nt,gh(o)):(nt.next=at.next,at.next=nt),o.interleaved=nt;return}}catch{}finally{}tt=hh(et,o,nt,rt),tt!==null&&(nt=R(),gi(tt,et,rt,nt),Bi(tt,o,rt))}}function zi(et){var o=et.alternate;return et===M$1||o!==null&&o===M$1}function Ai(et,o){Jh=Ih=!0;var tt=et.pending;tt===null?o.next=o:(o.next=tt.next,tt.next=o),et.pending=o}function Bi(et,o,tt){if(tt&4194240){var rt=o.lanes;rt&=et.pendingLanes,tt|=rt,o.lanes=tt,Cc(et,tt)}}var Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},Oh={readContext:eh,useCallback:function(et,o){return Th().memoizedState=[et,o===void 0?null:o],et},useContext:eh,useEffect:mi,useImperativeHandle:function(et,o,tt){return tt=tt!=null?tt.concat([et]):null,ki(4194308,4,pi.bind(null,o,et),tt)},useLayoutEffect:function(et,o){return ki(4194308,4,et,o)},useInsertionEffect:function(et,o){return ki(4,2,et,o)},useMemo:function(et,o){var tt=Th();return o=o===void 0?null:o,et=et(),tt.memoizedState=[et,o],et},useReducer:function(et,o,tt){var rt=Th();return o=tt!==void 0?tt(o):o,rt.memoizedState=rt.baseState=o,et={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:et,lastRenderedState:o},rt.queue=et,et=et.dispatch=xi.bind(null,M$1,et),[rt.memoizedState,et]},useRef:function(et){var o=Th();return et={current:et},o.memoizedState=et},useState:hi,useDebugValue:ri,useDeferredValue:function(et){return Th().memoizedState=et},useTransition:function(){var et=hi(!1),o=et[0];return et=vi.bind(null,et[1]),Th().memoizedState=et,[o,et]},useMutableSource:function(){},useSyncExternalStore:function(et,o,tt){var rt=M$1,nt=Th();if(I$1){if(tt===void 0)throw Error(p$4(407));tt=tt()}else{if(tt=o(),Q$1===null)throw Error(p$4(349));Hh&30||di(rt,o,tt)}nt.memoizedState=tt;var ot={value:tt,getSnapshot:o};return nt.queue=ot,mi(ai.bind(null,rt,ot,et),[et]),rt.flags|=2048,bi(9,ci.bind(null,rt,ot,tt,o),void 0,null),tt},useId:function(){var et=Th(),o=Q$1.identifierPrefix;if(I$1){var tt=sg,rt=rg;tt=(rt&~(1<<32-oc(rt)-1)).toString(32)+tt,o=":"+o+"R"+tt,tt=Kh++,0<\/script>",et=et.removeChild(et.firstChild)):typeof rt.is=="string"?et=it.createElement(tt,{is:rt.is}):(et=it.createElement(tt),tt==="select"&&(it=et,rt.multiple?it.multiple=!0:rt.size&&(it.size=rt.size))):et=it.createElementNS(et,tt),et[Of]=o,et[Pf]=rt,zj(et,o,!1,!1),o.stateNode=et;e:{switch(it=vb(tt,rt),tt){case"dialog":D$1("cancel",et),D$1("close",et),nt=rt;break;case"iframe":case"object":case"embed":D$1("load",et),nt=rt;break;case"video":case"audio":for(nt=0;ntGj&&(o.flags|=128,rt=!0,Dj(ot,!1),o.lanes=4194304)}else{if(!rt)if(et=Ch(it),et!==null){if(o.flags|=128,rt=!0,tt=et.updateQueue,tt!==null&&(o.updateQueue=tt,o.flags|=4),Dj(ot,!0),ot.tail===null&&ot.tailMode==="hidden"&&!it.alternate&&!I$1)return S$1(o),null}else 2*B$1()-ot.renderingStartTime>Gj&&tt!==1073741824&&(o.flags|=128,rt=!0,Dj(ot,!1),o.lanes=4194304);ot.isBackwards?(it.sibling=o.child,o.child=it):(tt=ot.last,tt!==null?tt.sibling=it:o.child=it,ot.last=it)}return ot.tail!==null?(o=ot.tail,ot.rendering=o,ot.tail=o.sibling,ot.renderingStartTime=B$1(),o.sibling=null,tt=L$1.current,G$1(L$1,rt?tt&1|2:tt&1),o):(S$1(o),null);case 22:case 23:return Hj(),rt=o.memoizedState!==null,et!==null&&et.memoizedState!==null!==rt&&(o.flags|=8192),rt&&o.mode&1?fj&1073741824&&(S$1(o),o.subtreeFlags&6&&(o.flags|=8192)):S$1(o),null;case 24:return null;case 25:return null}throw Error(p$4(156,o.tag))}function Ij(et,o){switch(wg(o),o.tag){case 1:return Zf(o.type)&&$f(),et=o.flags,et&65536?(o.flags=et&-65537|128,o):null;case 3:return zh(),E$1(Wf),E$1(H$1),Eh(),et=o.flags,et&65536&&!(et&128)?(o.flags=et&-65537|128,o):null;case 5:return Bh(o),null;case 13:if(E$1(L$1),et=o.memoizedState,et!==null&&et.dehydrated!==null){if(o.alternate===null)throw Error(p$4(340));Ig()}return et=o.flags,et&65536?(o.flags=et&-65537|128,o):null;case 19:return E$1(L$1),null;case 4:return zh(),null;case 10:return ah(o.type._context),null;case 22:case 23:return Hj(),null;case 24:return null;default:return null}}var Jj=!1,U$1=!1,Kj=typeof WeakSet=="function"?WeakSet:Set,V$2=null;function Lj(et,o){var tt=et.ref;if(tt!==null)if(typeof tt=="function")try{tt(null)}catch(rt){W$1(et,o,rt)}else tt.current=null}function Mj(et,o,tt){try{tt()}catch(rt){W$1(et,o,rt)}}var Nj=!1;function Oj(et,o){if(Cf=dd,et=Me$1(),Ne$1(et)){if("selectionStart"in et)var tt={start:et.selectionStart,end:et.selectionEnd};else e:{tt=(tt=et.ownerDocument)&&tt.defaultView||window;var rt=tt.getSelection&&tt.getSelection();if(rt&&rt.rangeCount!==0){tt=rt.anchorNode;var nt=rt.anchorOffset,ot=rt.focusNode;rt=rt.focusOffset;try{tt.nodeType,ot.nodeType}catch{tt=null;break e}var it=0,st=-1,at=-1,ct=0,lt=0,dt=et,ht=null;t:for(;;){for(var mt;dt!==tt||nt!==0&&dt.nodeType!==3||(st=it+nt),dt!==ot||rt!==0&&dt.nodeType!==3||(at=it+rt),dt.nodeType===3&&(it+=dt.nodeValue.length),(mt=dt.firstChild)!==null;)ht=dt,dt=mt;for(;;){if(dt===et)break t;if(ht===tt&&++ct===nt&&(st=it),ht===ot&&++lt===rt&&(at=it),(mt=dt.nextSibling)!==null)break;dt=ht,ht=dt.parentNode}dt=mt}tt=st===-1||at===-1?null:{start:st,end:at}}else tt=null}tt=tt||{start:0,end:0}}else tt=null;for(Df={focusedElem:et,selectionRange:tt},dd=!1,V$2=o;V$2!==null;)if(o=V$2,et=o.child,(o.subtreeFlags&1028)!==0&&et!==null)et.return=o,V$2=et;else for(;V$2!==null;){o=V$2;try{var ft=o.alternate;if(o.flags&1024)switch(o.tag){case 0:case 11:case 15:break;case 1:if(ft!==null){var pt=ft.memoizedProps,gt=ft.memoizedState,yt=o.stateNode,bt=yt.getSnapshotBeforeUpdate(o.elementType===o.type?pt:Ci(o.type,pt),gt);yt.__reactInternalSnapshotBeforeUpdate=bt}break;case 3:var xt=o.stateNode.containerInfo;xt.nodeType===1?xt.textContent="":xt.nodeType===9&&xt.documentElement&&xt.removeChild(xt.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p$4(163))}}catch(vt){W$1(o,o.return,vt)}if(et=o.sibling,et!==null){et.return=o.return,V$2=et;break}V$2=o.return}return ft=Nj,Nj=!1,ft}function Pj(et,o,tt){var rt=o.updateQueue;if(rt=rt!==null?rt.lastEffect:null,rt!==null){var nt=rt=rt.next;do{if((nt.tag&et)===et){var ot=nt.destroy;nt.destroy=void 0,ot!==void 0&&Mj(o,tt,ot)}nt=nt.next}while(nt!==rt)}}function Qj(et,o){if(o=o.updateQueue,o=o!==null?o.lastEffect:null,o!==null){var tt=o=o.next;do{if((tt.tag&et)===et){var rt=tt.create;tt.destroy=rt()}tt=tt.next}while(tt!==o)}}function Rj(et){var o=et.ref;if(o!==null){var tt=et.stateNode;switch(et.tag){case 5:et=tt;break;default:et=tt}typeof o=="function"?o(et):o.current=et}}function Sj(et){var o=et.alternate;o!==null&&(et.alternate=null,Sj(o)),et.child=null,et.deletions=null,et.sibling=null,et.tag===5&&(o=et.stateNode,o!==null&&(delete o[Of],delete o[Pf],delete o[of],delete o[Qf],delete o[Rf])),et.stateNode=null,et.return=null,et.dependencies=null,et.memoizedProps=null,et.memoizedState=null,et.pendingProps=null,et.stateNode=null,et.updateQueue=null}function Tj(et){return et.tag===5||et.tag===3||et.tag===4}function Uj(et){e:for(;;){for(;et.sibling===null;){if(et.return===null||Tj(et.return))return null;et=et.return}for(et.sibling.return=et.return,et=et.sibling;et.tag!==5&&et.tag!==6&&et.tag!==18;){if(et.flags&2||et.child===null||et.tag===4)continue e;et.child.return=et,et=et.child}if(!(et.flags&2))return et.stateNode}}function Vj(et,o,tt){var rt=et.tag;if(rt===5||rt===6)et=et.stateNode,o?tt.nodeType===8?tt.parentNode.insertBefore(et,o):tt.insertBefore(et,o):(tt.nodeType===8?(o=tt.parentNode,o.insertBefore(et,tt)):(o=tt,o.appendChild(et)),tt=tt._reactRootContainer,tt!=null||o.onclick!==null||(o.onclick=Bf));else if(rt!==4&&(et=et.child,et!==null))for(Vj(et,o,tt),et=et.sibling;et!==null;)Vj(et,o,tt),et=et.sibling}function Wj(et,o,tt){var rt=et.tag;if(rt===5||rt===6)et=et.stateNode,o?tt.insertBefore(et,o):tt.appendChild(et);else if(rt!==4&&(et=et.child,et!==null))for(Wj(et,o,tt),et=et.sibling;et!==null;)Wj(et,o,tt),et=et.sibling}var X$1=null,Xj=!1;function Yj(et,o,tt){for(tt=tt.child;tt!==null;)Zj(et,o,tt),tt=tt.sibling}function Zj(et,o,tt){if(lc&&typeof lc.onCommitFiberUnmount=="function")try{lc.onCommitFiberUnmount(kc,tt)}catch{}switch(tt.tag){case 5:U$1||Lj(tt,o);case 6:var rt=X$1,nt=Xj;X$1=null,Yj(et,o,tt),X$1=rt,Xj=nt,X$1!==null&&(Xj?(et=X$1,tt=tt.stateNode,et.nodeType===8?et.parentNode.removeChild(tt):et.removeChild(tt)):X$1.removeChild(tt.stateNode));break;case 18:X$1!==null&&(Xj?(et=X$1,tt=tt.stateNode,et.nodeType===8?Kf(et.parentNode,tt):et.nodeType===1&&Kf(et,tt),bd(et)):Kf(X$1,tt.stateNode));break;case 4:rt=X$1,nt=Xj,X$1=tt.stateNode.containerInfo,Xj=!0,Yj(et,o,tt),X$1=rt,Xj=nt;break;case 0:case 11:case 14:case 15:if(!U$1&&(rt=tt.updateQueue,rt!==null&&(rt=rt.lastEffect,rt!==null))){nt=rt=rt.next;do{var ot=nt,it=ot.destroy;ot=ot.tag,it!==void 0&&(ot&2||ot&4)&&Mj(tt,o,it),nt=nt.next}while(nt!==rt)}Yj(et,o,tt);break;case 1:if(!U$1&&(Lj(tt,o),rt=tt.stateNode,typeof rt.componentWillUnmount=="function"))try{rt.props=tt.memoizedProps,rt.state=tt.memoizedState,rt.componentWillUnmount()}catch(st){W$1(tt,o,st)}Yj(et,o,tt);break;case 21:Yj(et,o,tt);break;case 22:tt.mode&1?(U$1=(rt=U$1)||tt.memoizedState!==null,Yj(et,o,tt),U$1=rt):Yj(et,o,tt);break;default:Yj(et,o,tt)}}function ak(et){var o=et.updateQueue;if(o!==null){et.updateQueue=null;var tt=et.stateNode;tt===null&&(tt=et.stateNode=new Kj),o.forEach(function(rt){var nt=bk.bind(null,et,rt);tt.has(rt)||(tt.add(rt),rt.then(nt,nt))})}}function ck(et,o){var tt=o.deletions;if(tt!==null)for(var rt=0;rtnt&&(nt=it),rt&=~ot}if(rt=nt,rt=B$1()-rt,rt=(120>rt?120:480>rt?480:1080>rt?1080:1920>rt?1920:3e3>rt?3e3:4320>rt?4320:1960*lk(rt/1960))-rt,10et?16:et,wk===null)var rt=!1;else{if(et=wk,wk=null,xk=0,K$1&6)throw Error(p$4(331));var nt=K$1;for(K$1|=4,V$2=et.current;V$2!==null;){var ot=V$2,it=ot.child;if(V$2.flags&16){var st=ot.deletions;if(st!==null){for(var at=0;atB$1()-fk?Kk(et,0):rk|=tt),Dk(et,o)}function Yk(et,o){o===0&&(et.mode&1?(o=sc,sc<<=1,!(sc&130023424)&&(sc=4194304)):o=1);var tt=R();et=ih(et,o),et!==null&&(Ac(et,o,tt),Dk(et,tt))}function uj(et){var o=et.memoizedState,tt=0;o!==null&&(tt=o.retryLane),Yk(et,tt)}function bk(et,o){var tt=0;switch(et.tag){case 13:var rt=et.stateNode,nt=et.memoizedState;nt!==null&&(tt=nt.retryLane);break;case 19:rt=et.stateNode;break;default:throw Error(p$4(314))}rt!==null&&rt.delete(o),Yk(et,tt)}var Vk;Vk=function(et,o,tt){if(et!==null)if(et.memoizedProps!==o.pendingProps||Wf.current)dh=!0;else{if(!(et.lanes&tt)&&!(o.flags&128))return dh=!1,yj(et,o,tt);dh=!!(et.flags&131072)}else dh=!1,I$1&&o.flags&1048576&&ug(o,ng,o.index);switch(o.lanes=0,o.tag){case 2:var rt=o.type;ij(et,o),et=o.pendingProps;var nt=Yf(o,H$1.current);ch(o,tt),nt=Nh(null,o,rt,et,nt,tt);var ot=Sh();return o.flags|=1,typeof nt=="object"&&nt!==null&&typeof nt.render=="function"&&nt.$$typeof===void 0?(o.tag=1,o.memoizedState=null,o.updateQueue=null,Zf(rt)?(ot=!0,cg(o)):ot=!1,o.memoizedState=nt.state!==null&&nt.state!==void 0?nt.state:null,kh(o),nt.updater=Ei,o.stateNode=nt,nt._reactInternals=o,Ii(o,rt,et,tt),o=jj(null,o,rt,!0,ot,tt)):(o.tag=0,I$1&&ot&&vg(o),Xi(null,o,nt,tt),o=o.child),o;case 16:rt=o.elementType;e:{switch(ij(et,o),et=o.pendingProps,nt=rt._init,rt=nt(rt._payload),o.type=rt,nt=o.tag=Zk(rt),et=Ci(rt,et),nt){case 0:o=cj(null,o,rt,et,tt);break e;case 1:o=hj(null,o,rt,et,tt);break e;case 11:o=Yi(null,o,rt,et,tt);break e;case 14:o=$i(null,o,rt,Ci(rt.type,et),tt);break e}throw Error(p$4(306,rt,""))}return o;case 0:return rt=o.type,nt=o.pendingProps,nt=o.elementType===rt?nt:Ci(rt,nt),cj(et,o,rt,nt,tt);case 1:return rt=o.type,nt=o.pendingProps,nt=o.elementType===rt?nt:Ci(rt,nt),hj(et,o,rt,nt,tt);case 3:e:{if(kj(o),et===null)throw Error(p$4(387));rt=o.pendingProps,ot=o.memoizedState,nt=ot.element,lh(et,o),qh(o,rt,null,tt);var it=o.memoizedState;if(rt=it.element,ot.isDehydrated)if(ot={element:rt,isDehydrated:!1,cache:it.cache,pendingSuspenseBoundaries:it.pendingSuspenseBoundaries,transitions:it.transitions},o.updateQueue.baseState=ot,o.memoizedState=ot,o.flags&256){nt=Ji(Error(p$4(423)),o),o=lj(et,o,rt,tt,nt);break e}else if(rt!==nt){nt=Ji(Error(p$4(424)),o),o=lj(et,o,rt,tt,nt);break e}else for(yg=Lf(o.stateNode.containerInfo.firstChild),xg=o,I$1=!0,zg=null,tt=Vg(o,null,rt,tt),o.child=tt;tt;)tt.flags=tt.flags&-3|4096,tt=tt.sibling;else{if(Ig(),rt===nt){o=Zi(et,o,tt);break e}Xi(et,o,rt,tt)}o=o.child}return o;case 5:return Ah(o),et===null&&Eg(o),rt=o.type,nt=o.pendingProps,ot=et!==null?et.memoizedProps:null,it=nt.children,Ef(rt,nt)?it=null:ot!==null&&Ef(rt,ot)&&(o.flags|=32),gj(et,o),Xi(et,o,it,tt),o.child;case 6:return et===null&&Eg(o),null;case 13:return oj(et,o,tt);case 4:return yh(o,o.stateNode.containerInfo),rt=o.pendingProps,et===null?o.child=Ug(o,null,rt,tt):Xi(et,o,rt,tt),o.child;case 11:return rt=o.type,nt=o.pendingProps,nt=o.elementType===rt?nt:Ci(rt,nt),Yi(et,o,rt,nt,tt);case 7:return Xi(et,o,o.pendingProps,tt),o.child;case 8:return Xi(et,o,o.pendingProps.children,tt),o.child;case 12:return Xi(et,o,o.pendingProps.children,tt),o.child;case 10:e:{if(rt=o.type._context,nt=o.pendingProps,ot=o.memoizedProps,it=nt.value,G$1(Wg,rt._currentValue),rt._currentValue=it,ot!==null)if(He(ot.value,it)){if(ot.children===nt.children&&!Wf.current){o=Zi(et,o,tt);break e}}else for(ot=o.child,ot!==null&&(ot.return=o);ot!==null;){var st=ot.dependencies;if(st!==null){it=ot.child;for(var at=st.firstContext;at!==null;){if(at.context===rt){if(ot.tag===1){at=mh(-1,tt&-tt),at.tag=2;var ct=ot.updateQueue;if(ct!==null){ct=ct.shared;var lt=ct.pending;lt===null?at.next=at:(at.next=lt.next,lt.next=at),ct.pending=at}}ot.lanes|=tt,at=ot.alternate,at!==null&&(at.lanes|=tt),bh(ot.return,tt,o),st.lanes|=tt;break}at=at.next}}else if(ot.tag===10)it=ot.type===o.type?null:ot.child;else if(ot.tag===18){if(it=ot.return,it===null)throw Error(p$4(341));it.lanes|=tt,st=it.alternate,st!==null&&(st.lanes|=tt),bh(it,tt,o),it=ot.sibling}else it=ot.child;if(it!==null)it.return=ot;else for(it=ot;it!==null;){if(it===o){it=null;break}if(ot=it.sibling,ot!==null){ot.return=it.return,it=ot;break}it=it.return}ot=it}Xi(et,o,nt.children,tt),o=o.child}return o;case 9:return nt=o.type,rt=o.pendingProps.children,ch(o,tt),nt=eh(nt),rt=rt(nt),o.flags|=1,Xi(et,o,rt,tt),o.child;case 14:return rt=o.type,nt=Ci(rt,o.pendingProps),nt=Ci(rt.type,nt),$i(et,o,rt,nt,tt);case 15:return bj(et,o,o.type,o.pendingProps,tt);case 17:return rt=o.type,nt=o.pendingProps,nt=o.elementType===rt?nt:Ci(rt,nt),ij(et,o),o.tag=1,Zf(rt)?(et=!0,cg(o)):et=!1,ch(o,tt),Gi(o,rt,nt),Ii(o,rt,nt,tt),jj(null,o,rt,!0,et,tt);case 19:return xj(et,o,tt);case 22:return dj(et,o,tt)}throw Error(p$4(156,o.tag))};function Fk(et,o){return ac(et,o)}function $k(et,o,tt,rt){this.tag=et,this.key=tt,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=o,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=rt,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Bg(et,o,tt,rt){return new $k(et,o,tt,rt)}function aj(et){return et=et.prototype,!(!et||!et.isReactComponent)}function Zk(et){if(typeof et=="function")return aj(et)?1:0;if(et!=null){if(et=et.$$typeof,et===Da)return 11;if(et===Ga)return 14}return 2}function Pg(et,o){var tt=et.alternate;return tt===null?(tt=Bg(et.tag,o,et.key,et.mode),tt.elementType=et.elementType,tt.type=et.type,tt.stateNode=et.stateNode,tt.alternate=et,et.alternate=tt):(tt.pendingProps=o,tt.type=et.type,tt.flags=0,tt.subtreeFlags=0,tt.deletions=null),tt.flags=et.flags&14680064,tt.childLanes=et.childLanes,tt.lanes=et.lanes,tt.child=et.child,tt.memoizedProps=et.memoizedProps,tt.memoizedState=et.memoizedState,tt.updateQueue=et.updateQueue,o=et.dependencies,tt.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext},tt.sibling=et.sibling,tt.index=et.index,tt.ref=et.ref,tt}function Rg(et,o,tt,rt,nt,ot){var it=2;if(rt=et,typeof et=="function")aj(et)&&(it=1);else if(typeof et=="string")it=5;else e:switch(et){case ya:return Tg(tt.children,nt,ot,o);case za:it=8,nt|=8;break;case Aa:return et=Bg(12,tt,o,nt|2),et.elementType=Aa,et.lanes=ot,et;case Ea:return et=Bg(13,tt,o,nt),et.elementType=Ea,et.lanes=ot,et;case Fa:return et=Bg(19,tt,o,nt),et.elementType=Fa,et.lanes=ot,et;case Ia:return pj(tt,nt,ot,o);default:if(typeof et=="object"&&et!==null)switch(et.$$typeof){case Ba:it=10;break e;case Ca:it=9;break e;case Da:it=11;break e;case Ga:it=14;break e;case Ha:it=16,rt=null;break e}throw Error(p$4(130,et==null?et:typeof et,""))}return o=Bg(it,tt,o,nt),o.elementType=et,o.type=rt,o.lanes=ot,o}function Tg(et,o,tt,rt){return et=Bg(7,et,rt,o),et.lanes=tt,et}function pj(et,o,tt,rt){return et=Bg(22,et,rt,o),et.elementType=Ia,et.lanes=tt,et.stateNode={isHidden:!1},et}function Qg(et,o,tt){return et=Bg(6,et,null,o),et.lanes=tt,et}function Sg(et,o,tt){return o=Bg(4,et.children!==null?et.children:[],et.key,o),o.lanes=tt,o.stateNode={containerInfo:et.containerInfo,pendingChildren:null,implementation:et.implementation},o}function al(et,o,tt,rt,nt){this.tag=o,this.containerInfo=et,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zc(0),this.expirationTimes=zc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zc(0),this.identifierPrefix=rt,this.onRecoverableError=nt,this.mutableSourceEagerHydrationData=null}function bl(et,o,tt,rt,nt,ot,it,st,at){return et=new al(et,o,tt,st,at),o===1?(o=1,ot===!0&&(o|=8)):o=0,ot=Bg(3,null,null,o),et.current=ot,ot.stateNode=et,ot.memoizedState={element:rt,isDehydrated:tt,cache:null,transitions:null,pendingSuspenseBoundaries:null},kh(ot),et}function cl(et,o,tt){var rt=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE)}catch(et){console.error(et)}}checkDCE(),reactDom.exports=reactDom_production_min;var reactDomExports=reactDom.exports;const ReactDOM=getDefaultExportFromCjs(reactDomExports);var createRoot,m$5=reactDomExports;createRoot=m$5.createRoot,m$5.hydrateRoot;const version$8="2.21.28";let errorConfig={getDocsUrl:({docsBaseUrl:et,docsPath:o="",docsSlug:tt})=>o?`${et??"https://viem.sh"}${o}${tt?`#${tt}`:""}`:void 0,version:version$8},BaseError$3=class $s extends Error{constructor(o,tt={}){var st;const rt=(()=>{var at;return tt.cause instanceof $s?tt.cause.details:(at=tt.cause)!=null&&at.message?tt.cause.message:tt.details})(),nt=tt.cause instanceof $s&&tt.cause.docsPath||tt.docsPath,ot=(st=errorConfig.getDocsUrl)==null?void 0:st.call(errorConfig,{...tt,docsPath:nt}),it=[o||"An error occurred.","",...tt.metaMessages?[...tt.metaMessages,""]:[],...ot?[`Docs: ${ot}`]:[],...rt?[`Details: ${rt}`]:[],`Version: ${errorConfig.version}`].join(` +`);super(it,tt.cause?{cause:tt.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=rt,this.docsPath=nt,this.metaMessages=tt.metaMessages,this.name=tt.name??this.name,this.shortMessage=o,this.version=version$8}walk(o){return walk(this,o)}};function walk(et,o){return o!=null&&o(et)?et:et&&typeof et=="object"&&"cause"in et?walk(et.cause,o):o?null:et}class IntegerOutOfRangeError extends BaseError$3{constructor({max:o,min:tt,signed:rt,size:nt,value:ot}){super(`Number "${ot}" is not in safe ${nt?`${nt*8}-bit ${rt?"signed":"unsigned"} `:""}integer range ${o?`(${tt} to ${o})`:`(above ${tt})`}`,{name:"IntegerOutOfRangeError"})}}class InvalidBytesBooleanError extends BaseError$3{constructor(o){super(`Bytes value "${o}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class SizeOverflowError extends BaseError$3{constructor({givenSize:o,maxSize:tt}){super(`Size cannot exceed ${tt} bytes. Given size: ${o} bytes.`,{name:"SizeOverflowError"})}}class SliceOffsetOutOfBoundsError extends BaseError$3{constructor({offset:o,position:tt,size:rt}){super(`Slice ${tt==="start"?"starting":"ending"} at offset "${o}" is out-of-bounds (size: ${rt}).`,{name:"SliceOffsetOutOfBoundsError"})}}class SizeExceedsPaddingSizeError extends BaseError$3{constructor({size:o,targetSize:tt,type:rt}){super(`${rt.charAt(0).toUpperCase()}${rt.slice(1).toLowerCase()} size (${o}) exceeds padding size (${tt}).`,{name:"SizeExceedsPaddingSizeError"})}}class InvalidBytesLengthError extends BaseError$3{constructor({size:o,targetSize:tt,type:rt}){super(`${rt.charAt(0).toUpperCase()}${rt.slice(1).toLowerCase()} is expected to be ${tt} ${rt} long, but is ${o} ${rt} long.`,{name:"InvalidBytesLengthError"})}}function pad(et,{dir:o,size:tt=32}={}){return typeof et=="string"?padHex(et,{dir:o,size:tt}):padBytes(et,{dir:o,size:tt})}function padHex(et,{dir:o,size:tt=32}={}){if(tt===null)return et;const rt=et.replace("0x","");if(rt.length>tt*2)throw new SizeExceedsPaddingSizeError({size:Math.ceil(rt.length/2),targetSize:tt,type:"hex"});return`0x${rt[o==="right"?"padEnd":"padStart"](tt*2,"0")}`}function padBytes(et,{dir:o,size:tt=32}={}){if(tt===null)return et;if(et.length>tt)throw new SizeExceedsPaddingSizeError({size:et.length,targetSize:tt,type:"bytes"});const rt=new Uint8Array(tt);for(let nt=0;nt=charCodeMap.zero&&et<=charCodeMap.nine)return et-charCodeMap.zero;if(et>=charCodeMap.A&&et<=charCodeMap.F)return et-(charCodeMap.A-10);if(et>=charCodeMap.a&&et<=charCodeMap.f)return et-(charCodeMap.a-10)}function hexToBytes$3(et,o={}){let tt=et;o.size&&(assertSize(tt,{size:o.size}),tt=pad(tt,{dir:"right",size:o.size}));let rt=tt.slice(2);rt.length%2&&(rt=`0${rt}`);const nt=rt.length/2,ot=new Uint8Array(nt);for(let it=0,st=0;ito)throw new SizeOverflowError({givenSize:size$2(et),maxSize:o})}function hexToBigInt(et,o={}){const{signed:tt}=o;o.size&&assertSize(et,{size:o.size});const rt=BigInt(et);if(!tt)return rt;const nt=(et.length-2)/2,ot=(1n<o.toString(16).padStart(2,"0"));function toHex(et,o={}){return typeof et=="number"||typeof et=="bigint"?numberToHex(et,o):typeof et=="string"?stringToHex(et,o):typeof et=="boolean"?boolToHex(et,o):bytesToHex$3(et,o)}function boolToHex(et,o={}){const tt=`0x${Number(et)}`;return typeof o.size=="number"?(assertSize(tt,{size:o.size}),pad(tt,{size:o.size})):tt}function bytesToHex$3(et,o={}){let tt="";for(let nt=0;ntot||ntformatAbiParam(tt,{includeName:o})).join(o?", ":","):""}function formatAbiParam(et,{includeName:o}){return et.type.startsWith("tuple")?`(${formatAbiParams(et.components,{includeName:o})})${et.type.slice(5)}`:et.type+(o&&et.name?` ${et.name}`:"")}class AbiConstructorNotFoundError extends BaseError$3{constructor({docsPath:o}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(` +`),{docsPath:o,name:"AbiConstructorNotFoundError"})}}class AbiConstructorParamsNotFoundError extends BaseError$3{constructor({docsPath:o}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(` +`),{docsPath:o,name:"AbiConstructorParamsNotFoundError"})}}class AbiDecodingDataSizeTooSmallError extends BaseError$3{constructor({data:o,params:tt,size:rt}){super([`Data size of ${rt} bytes is too small for given parameters.`].join(` +`),{metaMessages:[`Params: (${formatAbiParams(tt,{includeName:!0})})`,`Data: ${o} (${rt} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=o,this.params=tt,this.size=rt}}class AbiDecodingZeroDataError extends BaseError$3{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class AbiEncodingArrayLengthMismatchError extends BaseError$3{constructor({expectedLength:o,givenLength:tt,type:rt}){super([`ABI encoding array length mismatch for type ${rt}.`,`Expected length: ${o}`,`Given length: ${tt}`].join(` +`),{name:"AbiEncodingArrayLengthMismatchError"})}}class AbiEncodingBytesSizeMismatchError extends BaseError$3{constructor({expectedSize:o,value:tt}){super(`Size of bytes "${tt}" (bytes${size$2(tt)}) does not match expected size (bytes${o}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class AbiEncodingLengthMismatchError extends BaseError$3{constructor({expectedLength:o,givenLength:tt}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${o}`,`Given length (values): ${tt}`].join(` +`),{name:"AbiEncodingLengthMismatchError"})}}class AbiErrorSignatureNotFoundError extends BaseError$3{constructor(o,{docsPath:tt}){super([`Encoded error signature "${o}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${o}.`].join(` +`),{docsPath:tt,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=o}}class AbiFunctionNotFoundError extends BaseError$3{constructor(o,{docsPath:tt}={}){super([`Function ${o?`"${o}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(` +`),{docsPath:tt,name:"AbiFunctionNotFoundError"})}}class AbiFunctionOutputsNotFoundError extends BaseError$3{constructor(o,{docsPath:tt}){super([`Function "${o}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(` +`),{docsPath:tt,name:"AbiFunctionOutputsNotFoundError"})}}class AbiItemAmbiguityError extends BaseError$3{constructor(o,tt){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${o.type}\` in \`${formatAbiItem$1(o.abiItem)}\`, and`,`\`${tt.type}\` in \`${formatAbiItem$1(tt.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}class BytesSizeMismatchError extends BaseError$3{constructor({expectedSize:o,givenSize:tt}){super(`Expected bytes${o}, got bytes${tt}.`,{name:"BytesSizeMismatchError"})}}class InvalidAbiEncodingTypeError extends BaseError$3{constructor(o,{docsPath:tt}){super([`Type "${o}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(` +`),{docsPath:tt,name:"InvalidAbiEncodingType"})}}class InvalidAbiDecodingTypeError extends BaseError$3{constructor(o,{docsPath:tt}){super([`Type "${o}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(` +`),{docsPath:tt,name:"InvalidAbiDecodingType"})}}class InvalidArrayError extends BaseError$3{constructor(o){super([`Value "${o}" is not a valid array.`].join(` +`),{name:"InvalidArrayError"})}}class InvalidDefinitionTypeError extends BaseError$3{constructor(o){super([`"${o}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(` +`),{name:"InvalidDefinitionTypeError"})}}function concat$6(et){return typeof et[0]=="string"?concatHex(et):concatBytes$3(et)}function concatBytes$3(et){let o=0;for(const nt of et)o+=nt.length;const tt=new Uint8Array(o);let rt=0;for(const nt of et)tt.set(nt,rt),rt+=nt.length;return tt}function concatHex(et){return`0x${et.reduce((o,tt)=>o+tt.replace("0x",""),"")}`}class InvalidAddressError extends BaseError$3{constructor({address:o}){super(`Address "${o}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class LruMap extends Map{constructor(o){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=o}get(o){const tt=super.get(o);return super.has(o)&&tt!==void 0&&(this.delete(o),super.set(o,tt)),tt}set(o,tt){if(super.set(o,tt),this.maxSize&&this.size>this.maxSize){const rt=this.keys().next().value;rt&&this.delete(rt)}return this}}function number$4(et){if(!Number.isSafeInteger(et)||et<0)throw new Error(`positive integer expected, not ${et}`)}function isBytes$3(et){return et instanceof Uint8Array||et!=null&&typeof et=="object"&&et.constructor.name==="Uint8Array"}function bytes$1(et,...o){if(!isBytes$3(et))throw new Error("Uint8Array expected");if(o.length>0&&!o.includes(et.length))throw new Error(`Uint8Array expected of length ${o}, not of length=${et.length}`)}function hash$1(et){if(typeof et!="function"||typeof et.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number$4(et.outputLen),number$4(et.blockLen)}function exists$1(et,o=!0){if(et.destroyed)throw new Error("Hash instance has been destroyed");if(o&&et.finished)throw new Error("Hash#digest() has already been called")}function output$1(et,o){bytes$1(et);const tt=o.outputLen;if(et.length>_32n&U32_MASK64)}:{h:Number(et>>_32n&U32_MASK64)|0,l:Number(et&U32_MASK64)|0}}function split$1(et,o=!1){let tt=new Uint32Array(et.length),rt=new Uint32Array(et.length);for(let nt=0;ntBigInt(et>>>0)<<_32n|BigInt(o>>>0),shrSH=(et,o,tt)=>et>>>tt,shrSL=(et,o,tt)=>et<<32-tt|o>>>tt,rotrSH=(et,o,tt)=>et>>>tt|o<<32-tt,rotrSL=(et,o,tt)=>et<<32-tt|o>>>tt,rotrBH=(et,o,tt)=>et<<64-tt|o>>>tt-32,rotrBL=(et,o,tt)=>et>>>tt-32|o<<64-tt,rotr32H=(et,o)=>o,rotr32L=(et,o)=>et,rotlSH=(et,o,tt)=>et<>>32-tt,rotlSL=(et,o,tt)=>o<>>32-tt,rotlBH=(et,o,tt)=>o<>>64-tt,rotlBL=(et,o,tt)=>et<>>64-tt;function add(et,o,tt,rt){const nt=(o>>>0)+(rt>>>0);return{h:et+tt+(nt/2**32|0)|0,l:nt|0}}const add3L=(et,o,tt)=>(et>>>0)+(o>>>0)+(tt>>>0),add3H=(et,o,tt,rt)=>o+tt+rt+(et/2**32|0)|0,add4L=(et,o,tt,rt)=>(et>>>0)+(o>>>0)+(tt>>>0)+(rt>>>0),add4H=(et,o,tt,rt,nt)=>o+tt+rt+nt+(et/2**32|0)|0,add5L=(et,o,tt,rt,nt)=>(et>>>0)+(o>>>0)+(tt>>>0)+(rt>>>0)+(nt>>>0),add5H=(et,o,tt,rt,nt,ot)=>o+tt+rt+nt+ot+(et/2**32|0)|0,u64={fromBig,split:split$1,toBig,shrSH,shrSL,rotrSH,rotrSL,rotrBH,rotrBL,rotr32H,rotr32L,rotlSH,rotlSL,rotlBH,rotlBL,add,add3L,add3H,add4L,add4H,add5H,add5L},crypto$2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u32$1=et=>new Uint32Array(et.buffer,et.byteOffset,Math.floor(et.byteLength/4)),createView$1=et=>new DataView(et.buffer,et.byteOffset,et.byteLength),rotr=(et,o)=>et<<32-o|et>>>o,isLE$1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,byteSwap=et=>et<<24&4278190080|et<<8&16711680|et>>>8&65280|et>>>24&255;function byteSwap32(et){for(let o=0;oet().update(toBytes$2(rt)).digest(),tt=et();return o.outputLen=tt.outputLen,o.blockLen=tt.blockLen,o.create=()=>et(),o}function randomBytes$1(et=32){if(crypto$2&&typeof crypto$2.getRandomValues=="function")return crypto$2.getRandomValues(new Uint8Array(et));if(crypto$2&&typeof crypto$2.randomBytes=="function")return crypto$2.randomBytes(et);throw new Error("crypto.getRandomValues must be defined")}const SHA3_PI=[],SHA3_ROTL=[],_SHA3_IOTA=[],_0n$7=BigInt(0),_1n$9=BigInt(1),_2n$6=BigInt(2),_7n=BigInt(7),_256n=BigInt(256),_0x71n=BigInt(113);for(let et=0,o=_1n$9,tt=1,rt=0;et<24;et++){[tt,rt]=[rt,(2*tt+3*rt)%5],SHA3_PI.push(2*(5*rt+tt)),SHA3_ROTL.push((et+1)*(et+2)/2%64);let nt=_0n$7;for(let ot=0;ot<7;ot++)o=(o<<_1n$9^(o>>_7n)*_0x71n)%_256n,o&_2n$6&&(nt^=_1n$9<<(_1n$9<tt>32?rotlBH(et,o,tt):rotlSH(et,o,tt),rotlL=(et,o,tt)=>tt>32?rotlBL(et,o,tt):rotlSL(et,o,tt);function keccakP(et,o=24){const tt=new Uint32Array(10);for(let rt=24-o;rt<24;rt++){for(let it=0;it<10;it++)tt[it]=et[it]^et[it+10]^et[it+20]^et[it+30]^et[it+40];for(let it=0;it<10;it+=2){const st=(it+8)%10,at=(it+2)%10,ct=tt[at],lt=tt[at+1],dt=rotlH(ct,lt,1)^tt[st],ht=rotlL(ct,lt,1)^tt[st+1];for(let mt=0;mt<50;mt+=10)et[it+mt]^=dt,et[it+mt+1]^=ht}let nt=et[2],ot=et[3];for(let it=0;it<24;it++){const st=SHA3_ROTL[it],at=rotlH(nt,ot,st),ct=rotlL(nt,ot,st),lt=SHA3_PI[it];nt=et[lt],ot=et[lt+1],et[lt]=at,et[lt+1]=ct}for(let it=0;it<50;it+=10){for(let st=0;st<10;st++)tt[st]=et[it+st];for(let st=0;st<10;st++)et[it+st]^=~tt[(st+2)%10]&tt[(st+4)%10]}et[0]^=SHA3_IOTA_H[rt],et[1]^=SHA3_IOTA_L[rt]}tt.fill(0)}class Keccak extends Hash{constructor(o,tt,rt,nt=!1,ot=24){if(super(),this.blockLen=o,this.suffix=tt,this.outputLen=rt,this.enableXOF=nt,this.rounds=ot,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,number$4(rt),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=u32$1(this.state)}keccak(){isLE$1||byteSwap32(this.state32),keccakP(this.state32,this.rounds),isLE$1||byteSwap32(this.state32),this.posOut=0,this.pos=0}update(o){exists$1(this);const{blockLen:tt,state:rt}=this;o=toBytes$2(o);const nt=o.length;for(let ot=0;ot=rt&&this.keccak();const it=Math.min(rt-this.posOut,ot-nt);o.set(tt.subarray(this.posOut,this.posOut+it),nt),this.posOut+=it,nt+=it}return o}xofInto(o){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(o)}xof(o){return number$4(o),this.xofInto(new Uint8Array(o))}digestInto(o){if(output$1(o,this),this.finished)throw new Error("digest() was already called");return this.writeInto(o),this.destroy(),o}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(o){const{blockLen:tt,suffix:rt,outputLen:nt,rounds:ot,enableXOF:it}=this;return o||(o=new Keccak(tt,rt,nt,it,ot)),o.state32.set(this.state32),o.pos=this.pos,o.posOut=this.posOut,o.finished=this.finished,o.rounds=ot,o.suffix=rt,o.outputLen=nt,o.enableXOF=it,o.destroyed=this.destroyed,o}}const gen=(et,o,tt)=>wrapConstructor(()=>new Keccak(o,et,tt)),keccak_256=gen(1,136,256/8);function keccak256$1(et,o){const tt=o||"hex",rt=keccak_256(isHex(et,{strict:!1})?toBytes$3(et):et);return tt==="bytes"?rt:toHex(rt)}const checksumAddressCache=new LruMap(8192);function checksumAddress(et,o){if(checksumAddressCache.has(`${et}.${o}`))return checksumAddressCache.get(`${et}.${o}`);const tt=o?`${o}${et.toLowerCase()}`:et.substring(2).toLowerCase(),rt=keccak256$1(stringToBytes(tt),"bytes"),nt=(o?tt.substring(`${o}0x`.length):tt).split("");for(let it=0;it<40;it+=2)rt[it>>1]>>4>=8&&nt[it]&&(nt[it]=nt[it].toUpperCase()),(rt[it>>1]&15)>=8&&nt[it+1]&&(nt[it+1]=nt[it+1].toUpperCase());const ot=`0x${nt.join("")}`;return checksumAddressCache.set(`${et}.${o}`,ot),ot}function getAddress(et,o){if(!isAddress(et,{strict:!1}))throw new InvalidAddressError({address:et});return checksumAddress(et,o)}const addressRegex=/^0x[a-fA-F0-9]{40}$/,isAddressCache=new LruMap(8192);function isAddress(et,o){const{strict:tt=!0}=o??{},rt=`${et}.${tt}`;if(isAddressCache.has(rt))return isAddressCache.get(rt);const nt=addressRegex.test(et)?et.toLowerCase()===et?!0:tt?checksumAddress(et)===et:!0:!1;return isAddressCache.set(rt,nt),nt}function slice(et,o,tt,{strict:rt}={}){return isHex(et,{strict:!1})?sliceHex(et,o,tt,{strict:rt}):sliceBytes(et,o,tt,{strict:rt})}function assertStartOffset(et,o){if(typeof o=="number"&&o>0&&o>size$2(et)-1)throw new SliceOffsetOutOfBoundsError({offset:o,position:"start",size:size$2(et)})}function assertEndOffset(et,o,tt){if(typeof o=="number"&&typeof tt=="number"&&size$2(et)!==tt-o)throw new SliceOffsetOutOfBoundsError({offset:tt,position:"end",size:size$2(et)})}function sliceBytes(et,o,tt,{strict:rt}={}){assertStartOffset(et,o);const nt=et.slice(o,tt);return rt&&assertEndOffset(nt,o,tt),nt}function sliceHex(et,o,tt,{strict:rt}={}){assertStartOffset(et,o);const nt=`0x${et.replace("0x","").slice((o??0)*2,(tt??et.length)*2)}`;return rt&&assertEndOffset(nt,o,tt),nt}function encodeAbiParameters(et,o){if(et.length!==o.length)throw new AbiEncodingLengthMismatchError({expectedLength:et.length,givenLength:o.length});const tt=prepareParams({params:et,values:o}),rt=encodeParams(tt);return rt.length===0?"0x":rt}function prepareParams({params:et,values:o}){const tt=[];for(let rt=0;rt0?concat$6([st,it]):st}}if(nt)return{dynamic:!0,encoded:it}}return{dynamic:!1,encoded:concat$6(ot.map(({encoded:it})=>it))}}function encodeBytes(et,{param:o}){const[,tt]=o.type.split("bytes"),rt=size$2(et);if(!tt){let nt=et;return rt%32!==0&&(nt=padHex(nt,{dir:"right",size:Math.ceil((et.length-2)/2/32)*32})),{dynamic:!0,encoded:concat$6([padHex(numberToHex(rt,{size:32})),nt])}}if(rt!==Number.parseInt(tt))throw new AbiEncodingBytesSizeMismatchError({expectedSize:Number.parseInt(tt),value:et});return{dynamic:!1,encoded:padHex(et,{dir:"right"})}}function encodeBool(et){if(typeof et!="boolean")throw new BaseError$3(`Invalid boolean value: "${et}" (type: ${typeof et}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:padHex(boolToHex(et))}}function encodeNumber(et,{signed:o}){return{dynamic:!1,encoded:numberToHex(et,{size:32,signed:o})}}function encodeString(et){const o=stringToHex(et),tt=Math.ceil(size$2(o)/32),rt=[];for(let nt=0;ntnt))}}function getArrayComponents(et){const o=et.match(/^(.*)\[(\d+)?\]$/);return o?[o[2]?Number(o[2]):null,o[1]]:void 0}const docsPath$2="/docs/contract/encodeDeployData";function encodeDeployData(et){const{abi:o,args:tt,bytecode:rt}=et;if(!tt||tt.length===0)return rt;const nt=o.find(it=>"type"in it&&it.type==="constructor");if(!nt)throw new AbiConstructorNotFoundError({docsPath:docsPath$2});if(!("inputs"in nt))throw new AbiConstructorParamsNotFoundError({docsPath:docsPath$2});if(!nt.inputs||nt.inputs.length===0)throw new AbiConstructorParamsNotFoundError({docsPath:docsPath$2});const ot=encodeAbiParameters(nt.inputs,tt);return concatHex([rt,ot])}function parseAccount(et){return typeof et=="string"?{address:et,type:"json-rpc"}:et}class AccountNotFoundError extends BaseError$3{constructor({docsPath:o}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(` +`),{docsPath:o,docsSlug:"account",name:"AccountNotFoundError"})}}const scriptRel="modulepreload",assetsURL=function(et){return"/"+et},seen={},__vitePreload=function(o,tt,rt){let nt=Promise.resolve();if(tt&&tt.length>0){document.getElementsByTagName("link");const it=document.querySelector("meta[property=csp-nonce]"),st=(it==null?void 0:it.nonce)||(it==null?void 0:it.getAttribute("nonce"));nt=Promise.allSettled(tt.map(at=>{if(at=assetsURL(at),at in seen)return;seen[at]=!0;const ct=at.endsWith(".css"),lt=ct?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${at}"]${lt}`))return;const dt=document.createElement("link");if(dt.rel=ct?"stylesheet":scriptRel,ct||(dt.as="script"),dt.crossOrigin="",dt.href=at,st&&dt.setAttribute("nonce",st),document.head.appendChild(dt),ct)return new Promise((ht,mt)=>{dt.addEventListener("load",ht),dt.addEventListener("error",()=>mt(new Error(`Unable to preload CSS for ${at}`)))})}))}function ot(it){const st=new Event("vite:preloadError",{cancelable:!0});if(st.payload=it,window.dispatchEvent(st),!st.defaultPrevented)throw it}return nt.then(it=>{for(const st of it||[])st.status==="rejected"&&ot(st.reason);return o().catch(ot)})};class NegativeOffsetError extends BaseError$3{constructor({offset:o}){super(`Offset \`${o}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class PositionOutOfBoundsError extends BaseError$3{constructor({length:o,position:tt}){super(`Position \`${tt}\` is out of bounds (\`0 < position < ${o}\`).`,{name:"PositionOutOfBoundsError"})}}class RecursiveReadLimitExceededError extends BaseError$3{constructor({count:o,limit:tt}){super(`Recursive read limit of \`${tt}\` exceeded (recursive read count: \`${o}\`).`,{name:"RecursiveReadLimitExceededError"})}}const staticCursor={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new RecursiveReadLimitExceededError({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(et){if(et<0||et>this.bytes.length-1)throw new PositionOutOfBoundsError({length:this.bytes.length,position:et})},decrementPosition(et){if(et<0)throw new NegativeOffsetError({offset:et});const o=this.position-et;this.assertPosition(o),this.position=o},getReadCount(et){return this.positionReadCount.get(et||this.position)||0},incrementPosition(et){if(et<0)throw new NegativeOffsetError({offset:et});const o=this.position+et;this.assertPosition(o),this.position=o},inspectByte(et){const o=et??this.position;return this.assertPosition(o),this.bytes[o]},inspectBytes(et,o){const tt=o??this.position;return this.assertPosition(tt+et-1),this.bytes.subarray(tt,tt+et)},inspectUint8(et){const o=et??this.position;return this.assertPosition(o),this.bytes[o]},inspectUint16(et){const o=et??this.position;return this.assertPosition(o+1),this.dataView.getUint16(o)},inspectUint24(et){const o=et??this.position;return this.assertPosition(o+2),(this.dataView.getUint16(o)<<8)+this.dataView.getUint8(o+2)},inspectUint32(et){const o=et??this.position;return this.assertPosition(o+3),this.dataView.getUint32(o)},pushByte(et){this.assertPosition(this.position),this.bytes[this.position]=et,this.position++},pushBytes(et){this.assertPosition(this.position+et.length-1),this.bytes.set(et,this.position),this.position+=et.length},pushUint8(et){this.assertPosition(this.position),this.bytes[this.position]=et,this.position++},pushUint16(et){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,et),this.position+=2},pushUint24(et){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,et>>8),this.dataView.setUint8(this.position+2,et&255),this.position+=3},pushUint32(et){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,et),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const et=this.inspectByte();return this.position++,et},readBytes(et,o){this.assertReadLimit(),this._touch();const tt=this.inspectBytes(et);return this.position+=o??et,tt},readUint8(){this.assertReadLimit(),this._touch();const et=this.inspectUint8();return this.position+=1,et},readUint16(){this.assertReadLimit(),this._touch();const et=this.inspectUint16();return this.position+=2,et},readUint24(){this.assertReadLimit(),this._touch();const et=this.inspectUint24();return this.position+=3,et},readUint32(){this.assertReadLimit(),this._touch();const et=this.inspectUint32();return this.position+=4,et},get remaining(){return this.bytes.length-this.position},setPosition(et){const o=this.position;return this.assertPosition(et),this.position=et,()=>this.position=o},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const et=this.getReadCount();this.positionReadCount.set(this.position,et+1),et>0&&this.recursiveReadCount++}};function createCursor(et,{recursiveReadLimit:o=8192}={}){const tt=Object.create(staticCursor);return tt.bytes=et,tt.dataView=new DataView(et.buffer,et.byteOffset,et.byteLength),tt.positionReadCount=new Map,tt.recursiveReadLimit=o,tt}function toRlp(et,o="hex"){const tt=getEncodable(et),rt=createCursor(new Uint8Array(tt.length));return tt.encode(rt),o==="hex"?bytesToHex$3(rt.bytes):rt.bytes}function getEncodable(et){return Array.isArray(et)?getEncodableList(et.map(o=>getEncodable(o))):getEncodableBytes(et)}function getEncodableList(et){const o=et.reduce((nt,ot)=>nt+ot.length,0),tt=getSizeOfLength(o);return{length:o<=55?1+o:1+tt+o,encode(nt){o<=55?nt.pushByte(192+o):(nt.pushByte(247+tt),tt===1?nt.pushUint8(o):tt===2?nt.pushUint16(o):tt===3?nt.pushUint24(o):nt.pushUint32(o));for(const{encode:ot}of et)ot(nt)}}}function getEncodableBytes(et){const o=typeof et=="string"?hexToBytes$3(et):et,tt=getSizeOfLength(o.length);return{length:o.length===1&&o[0]<128?1:o.length<=55?1+o.length:1+tt+o.length,encode(nt){o.length===1&&o[0]<128?nt.pushBytes(o):o.length<=55?(nt.pushByte(128+o.length),nt.pushBytes(o)):(nt.pushByte(183+tt),tt===1?nt.pushUint8(o.length):tt===2?nt.pushUint16(o.length):tt===3?nt.pushUint24(o.length):nt.pushUint32(o.length),nt.pushBytes(o))}}}function getSizeOfLength(et){if(et<2**8)return 1;if(et<2**16)return 2;if(et<2**24)return 3;if(et<2**32)return 4;throw new BaseError$3("Length is too large.")}class ChainDoesNotSupportContract extends BaseError$3{constructor({blockNumber:o,chain:tt,contract:rt}){super(`Chain "${tt.name}" does not support contract "${rt.name}".`,{metaMessages:["This could be due to any of the following:",...o&&rt.blockCreated&&rt.blockCreated>o?[`- The contract "${rt.name}" was not deployed until block ${rt.blockCreated} (current block ${o}).`]:[`- The chain does not have the contract "${rt.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class ClientChainNotConfiguredError extends BaseError$3{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class InvalidChainIdError extends BaseError$3{constructor({chainId:o}){super(typeof o=="number"?`Chain ID "${o}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const etherUnits={gwei:9,wei:18},gweiUnits={ether:-9,wei:9},weiUnits={ether:-18,gwei:-9};function formatUnits(et,o){let tt=et.toString();const rt=tt.startsWith("-");rt&&(tt=tt.slice(1)),tt=tt.padStart(o,"0");let[nt,ot]=[tt.slice(0,tt.length-o),tt.slice(tt.length-o)];return ot=ot.replace(/(0+)$/,""),`${rt?"-":""}${nt||"0"}${ot?`.${ot}`:""}`}function formatGwei(et,o="wei"){return formatUnits(et,gweiUnits[o])}class ExecutionRevertedError extends BaseError$3{constructor({cause:o,message:tt}={}){var nt;const rt=(nt=tt==null?void 0:tt.replace("execution reverted: ",""))==null?void 0:nt.replace("execution reverted","");super(`Execution reverted ${rt?`with reason: ${rt}`:"for an unknown reason"}.`,{cause:o,name:"ExecutionRevertedError"})}}Object.defineProperty(ExecutionRevertedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ExecutionRevertedError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class FeeCapTooHighError extends BaseError$3{constructor({cause:o,maxFeePerGas:tt}={}){super(`The fee cap (\`maxFeePerGas\`${tt?` = ${formatGwei(tt)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:o,name:"FeeCapTooHighError"})}}Object.defineProperty(FeeCapTooHighError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class FeeCapTooLowError extends BaseError$3{constructor({cause:o,maxFeePerGas:tt}={}){super(`The fee cap (\`maxFeePerGas\`${tt?` = ${formatGwei(tt)}`:""} gwei) cannot be lower than the block base fee.`,{cause:o,name:"FeeCapTooLowError"})}}Object.defineProperty(FeeCapTooLowError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class NonceTooHighError extends BaseError$3{constructor({cause:o,nonce:tt}={}){super(`Nonce provided for the transaction ${tt?`(${tt}) `:""}is higher than the next one expected.`,{cause:o,name:"NonceTooHighError"})}}Object.defineProperty(NonceTooHighError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class NonceTooLowError extends BaseError$3{constructor({cause:o,nonce:tt}={}){super([`Nonce provided for the transaction ${tt?`(${tt}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(` +`),{cause:o,name:"NonceTooLowError"})}}Object.defineProperty(NonceTooLowError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class NonceMaxValueError extends BaseError$3{constructor({cause:o,nonce:tt}={}){super(`Nonce provided for the transaction ${tt?`(${tt}) `:""}exceeds the maximum allowed nonce.`,{cause:o,name:"NonceMaxValueError"})}}Object.defineProperty(NonceMaxValueError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class InsufficientFundsError extends BaseError$3{constructor({cause:o}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(` +`),{cause:o,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(InsufficientFundsError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class IntrinsicGasTooHighError extends BaseError$3{constructor({cause:o,gas:tt}={}){super(`The amount of gas ${tt?`(${tt}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:o,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(IntrinsicGasTooHighError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class IntrinsicGasTooLowError extends BaseError$3{constructor({cause:o,gas:tt}={}){super(`The amount of gas ${tt?`(${tt}) `:""}provided for the transaction is too low.`,{cause:o,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(IntrinsicGasTooLowError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class TransactionTypeNotSupportedError extends BaseError$3{constructor({cause:o}){super("The transaction type is not supported for this chain.",{cause:o,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(TransactionTypeNotSupportedError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class TipAboveFeeCapError extends BaseError$3{constructor({cause:o,maxPriorityFeePerGas:tt,maxFeePerGas:rt}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${tt?` = ${formatGwei(tt)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${rt?` = ${formatGwei(rt)} gwei`:""}).`].join(` +`),{cause:o,name:"TipAboveFeeCapError"})}}Object.defineProperty(TipAboveFeeCapError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class UnknownNodeError extends BaseError$3{constructor({cause:o}){super(`An error occurred while executing: ${o==null?void 0:o.shortMessage}`,{cause:o,name:"UnknownNodeError"})}}function formatEther(et,o="wei"){return formatUnits(et,etherUnits[o])}function prettyPrint(et){const o=Object.entries(et).map(([rt,nt])=>nt===void 0||nt===!1?null:[rt,nt]).filter(Boolean),tt=o.reduce((rt,[nt])=>Math.max(rt,nt.length),0);return o.map(([rt,nt])=>` ${`${rt}:`.padEnd(tt+1)} ${nt}`).join(` +`)}class FeeConflictError extends BaseError$3{constructor(){super(["Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.","Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."].join(` +`),{name:"FeeConflictError"})}}class InvalidLegacyVError extends BaseError$3{constructor({v:o}){super(`Invalid \`v\` value "${o}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class InvalidSerializableTransactionError extends BaseError$3{constructor({transaction:o}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",prettyPrint(o),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class InvalidStorageKeySizeError extends BaseError$3{constructor({storageKey:o}){super(`Size for storage key "${o}" is invalid. Expected 32 bytes. Got ${Math.floor((o.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}const stringify$2=(et,o,tt)=>JSON.stringify(et,(rt,nt)=>typeof nt=="bigint"?nt.toString():nt,tt),getContractAddress=et=>et,getUrl=et=>et;class HttpRequestError extends BaseError$3{constructor({body:o,cause:tt,details:rt,headers:nt,status:ot,url:it}){super("HTTP request failed.",{cause:tt,details:rt,metaMessages:[ot&&`Status: ${ot}`,`URL: ${getUrl(it)}`,o&&`Request body: ${stringify$2(o)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=o,this.headers=nt,this.status=ot,this.url=it}}class RpcRequestError extends BaseError$3{constructor({body:o,error:tt,url:rt}){super("RPC Request failed.",{cause:tt,details:tt.message,metaMessages:[`URL: ${getUrl(rt)}`,`Request body: ${stringify$2(o)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=tt.code}}let TimeoutError$4=class extends BaseError$3{constructor({body:o,url:tt}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${getUrl(tt)}`,`Request body: ${stringify$2(o)}`],name:"TimeoutError"})}};const unknownErrorCode=-1;class RpcError extends BaseError$3{constructor(o,{code:tt,docsPath:rt,metaMessages:nt,name:ot,shortMessage:it}){super(it,{cause:o,docsPath:rt,metaMessages:nt||(o==null?void 0:o.metaMessages),name:ot||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=ot||o.name,this.code=o instanceof RpcRequestError?o.code:tt??unknownErrorCode}}class ProviderRpcError extends RpcError{constructor(o,tt){super(o,tt),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=tt.data}}class ParseRpcError extends RpcError{constructor(o){super(o,{code:ParseRpcError.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(ParseRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class InvalidRequestRpcError extends RpcError{constructor(o){super(o,{code:InvalidRequestRpcError.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(InvalidRequestRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class MethodNotFoundRpcError extends RpcError{constructor(o,{method:tt}={}){super(o,{code:MethodNotFoundRpcError.code,name:"MethodNotFoundRpcError",shortMessage:`The method${tt?` "${tt}"`:""} does not exist / is not available.`})}}Object.defineProperty(MethodNotFoundRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class InvalidParamsRpcError extends RpcError{constructor(o){super(o,{code:InvalidParamsRpcError.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(` +`)})}}Object.defineProperty(InvalidParamsRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class InternalRpcError extends RpcError{constructor(o){super(o,{code:InternalRpcError.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(InternalRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class InvalidInputRpcError extends RpcError{constructor(o){super(o,{code:InvalidInputRpcError.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(` +`)})}}Object.defineProperty(InvalidInputRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class ResourceNotFoundRpcError extends RpcError{constructor(o){super(o,{code:ResourceNotFoundRpcError.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(ResourceNotFoundRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class ResourceUnavailableRpcError extends RpcError{constructor(o){super(o,{code:ResourceUnavailableRpcError.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(ResourceUnavailableRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class TransactionRejectedRpcError extends RpcError{constructor(o){super(o,{code:TransactionRejectedRpcError.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(TransactionRejectedRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class MethodNotSupportedRpcError extends RpcError{constructor(o,{method:tt}={}){super(o,{code:MethodNotSupportedRpcError.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${tt?` "${tt}"`:""} is not implemented.`})}}Object.defineProperty(MethodNotSupportedRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class LimitExceededRpcError extends RpcError{constructor(o){super(o,{code:LimitExceededRpcError.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(LimitExceededRpcError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class JsonRpcVersionUnsupportedError extends RpcError{constructor(o){super(o,{code:JsonRpcVersionUnsupportedError.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(JsonRpcVersionUnsupportedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class UserRejectedRequestError extends ProviderRpcError{constructor(o){super(o,{code:UserRejectedRequestError.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(UserRejectedRequestError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class UnauthorizedProviderError extends ProviderRpcError{constructor(o){super(o,{code:UnauthorizedProviderError.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(UnauthorizedProviderError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class UnsupportedProviderMethodError extends ProviderRpcError{constructor(o,{method:tt}={}){super(o,{code:UnsupportedProviderMethodError.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${tt?` " ${tt}"`:""}.`})}}Object.defineProperty(UnsupportedProviderMethodError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class ProviderDisconnectedError extends ProviderRpcError{constructor(o){super(o,{code:ProviderDisconnectedError.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(ProviderDisconnectedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class ChainDisconnectedError extends ProviderRpcError{constructor(o){super(o,{code:ChainDisconnectedError.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(ChainDisconnectedError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class SwitchChainError extends ProviderRpcError{constructor(o){super(o,{code:SwitchChainError.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(SwitchChainError,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class UnknownRpcError extends RpcError{constructor(o){super(o,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}function getNodeError(et,o){const tt=(et.details||"").toLowerCase(),rt=et instanceof BaseError$3?et.walk(nt=>(nt==null?void 0:nt.code)===ExecutionRevertedError.code):et;return rt instanceof BaseError$3?new ExecutionRevertedError({cause:et,message:rt.details}):ExecutionRevertedError.nodeMessage.test(tt)?new ExecutionRevertedError({cause:et,message:et.details}):FeeCapTooHighError.nodeMessage.test(tt)?new FeeCapTooHighError({cause:et,maxFeePerGas:o==null?void 0:o.maxFeePerGas}):FeeCapTooLowError.nodeMessage.test(tt)?new FeeCapTooLowError({cause:et,maxFeePerGas:o==null?void 0:o.maxFeePerGas}):NonceTooHighError.nodeMessage.test(tt)?new NonceTooHighError({cause:et,nonce:o==null?void 0:o.nonce}):NonceTooLowError.nodeMessage.test(tt)?new NonceTooLowError({cause:et,nonce:o==null?void 0:o.nonce}):NonceMaxValueError.nodeMessage.test(tt)?new NonceMaxValueError({cause:et,nonce:o==null?void 0:o.nonce}):InsufficientFundsError.nodeMessage.test(tt)?new InsufficientFundsError({cause:et}):IntrinsicGasTooHighError.nodeMessage.test(tt)?new IntrinsicGasTooHighError({cause:et,gas:o==null?void 0:o.gas}):IntrinsicGasTooLowError.nodeMessage.test(tt)?new IntrinsicGasTooLowError({cause:et,gas:o==null?void 0:o.gas}):TransactionTypeNotSupportedError.nodeMessage.test(tt)?new TransactionTypeNotSupportedError({cause:et}):TipAboveFeeCapError.nodeMessage.test(tt)?new TipAboveFeeCapError({cause:et,maxFeePerGas:o==null?void 0:o.maxFeePerGas,maxPriorityFeePerGas:o==null?void 0:o.maxPriorityFeePerGas}):new UnknownNodeError({cause:et})}function extract$1(et,{format:o}){if(!o)return{};const tt={};function rt(ot){const it=Object.keys(ot);for(const st of it)st in et&&(tt[st]=et[st]),ot[st]&&typeof ot[st]=="object"&&!Array.isArray(ot[st])&&rt(ot[st])}const nt=o(et||{});return rt(nt),tt}function defineFormatter(et,o){return({exclude:tt,format:rt})=>({exclude:tt,format:nt=>{const ot=o(nt);if(tt)for(const it of tt)delete ot[it];return{...ot,...rt(nt)}},type:et})}const rpcTransactionType={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function formatTransactionRequest(et){const o={};return typeof et.authorizationList<"u"&&(o.authorizationList=formatAuthorizationList$1(et.authorizationList)),typeof et.accessList<"u"&&(o.accessList=et.accessList),typeof et.blobVersionedHashes<"u"&&(o.blobVersionedHashes=et.blobVersionedHashes),typeof et.blobs<"u"&&(typeof et.blobs[0]!="string"?o.blobs=et.blobs.map(tt=>bytesToHex$3(tt)):o.blobs=et.blobs),typeof et.data<"u"&&(o.data=et.data),typeof et.from<"u"&&(o.from=et.from),typeof et.gas<"u"&&(o.gas=numberToHex(et.gas)),typeof et.gasPrice<"u"&&(o.gasPrice=numberToHex(et.gasPrice)),typeof et.maxFeePerBlobGas<"u"&&(o.maxFeePerBlobGas=numberToHex(et.maxFeePerBlobGas)),typeof et.maxFeePerGas<"u"&&(o.maxFeePerGas=numberToHex(et.maxFeePerGas)),typeof et.maxPriorityFeePerGas<"u"&&(o.maxPriorityFeePerGas=numberToHex(et.maxPriorityFeePerGas)),typeof et.nonce<"u"&&(o.nonce=numberToHex(et.nonce)),typeof et.to<"u"&&(o.to=et.to),typeof et.type<"u"&&(o.type=rpcTransactionType[et.type]),typeof et.value<"u"&&(o.value=numberToHex(et.value)),o}function formatAuthorizationList$1(et){return et.map(o=>({address:o.contractAddress,r:o.r,s:o.s,chainId:numberToHex(o.chainId),nonce:numberToHex(o.nonce),...typeof o.yParity<"u"?{yParity:numberToHex(o.yParity)}:{},...typeof o.v<"u"&&typeof o.yParity>"u"?{v:numberToHex(o.v)}:{}}))}function getAction$1(et,o,tt){const rt=et[o.name];if(typeof rt=="function")return rt;const nt=et[tt];return typeof nt=="function"?nt:ot=>o(et,ot)}const maxUint256=2n**256n-1n;function assertRequest(et){const{account:o,gasPrice:tt,maxFeePerGas:rt,maxPriorityFeePerGas:nt,to:ot}=et,it=o?parseAccount(o):void 0;if(it&&!isAddress(it.address))throw new InvalidAddressError({address:it.address});if(ot&&!isAddress(ot))throw new InvalidAddressError({address:ot});if(typeof tt<"u"&&(typeof rt<"u"||typeof nt<"u"))throw new FeeConflictError;if(rt&&rt>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:rt});if(nt&&rt&&nt>rt)throw new TipAboveFeeCapError({maxFeePerGas:rt,maxPriorityFeePerGas:nt})}const transactionType={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function formatTransaction(et){const o={...et,blockHash:et.blockHash?et.blockHash:null,blockNumber:et.blockNumber?BigInt(et.blockNumber):null,chainId:et.chainId?hexToNumber$2(et.chainId):void 0,gas:et.gas?BigInt(et.gas):void 0,gasPrice:et.gasPrice?BigInt(et.gasPrice):void 0,maxFeePerBlobGas:et.maxFeePerBlobGas?BigInt(et.maxFeePerBlobGas):void 0,maxFeePerGas:et.maxFeePerGas?BigInt(et.maxFeePerGas):void 0,maxPriorityFeePerGas:et.maxPriorityFeePerGas?BigInt(et.maxPriorityFeePerGas):void 0,nonce:et.nonce?hexToNumber$2(et.nonce):void 0,to:et.to?et.to:null,transactionIndex:et.transactionIndex?Number(et.transactionIndex):null,type:et.type?transactionType[et.type]:void 0,typeHex:et.type?et.type:void 0,value:et.value?BigInt(et.value):void 0,v:et.v?BigInt(et.v):void 0};return et.authorizationList&&(o.authorizationList=formatAuthorizationList(et.authorizationList)),o.yParity=(()=>{if(et.yParity)return Number(et.yParity);if(typeof o.v=="bigint"){if(o.v===0n||o.v===27n)return 0;if(o.v===1n||o.v===28n)return 1;if(o.v>=35n)return o.v%2n===0n?1:0}})(),o.type==="legacy"&&(delete o.accessList,delete o.maxFeePerBlobGas,delete o.maxFeePerGas,delete o.maxPriorityFeePerGas,delete o.yParity),o.type==="eip2930"&&(delete o.maxFeePerBlobGas,delete o.maxFeePerGas,delete o.maxPriorityFeePerGas),o.type==="eip1559"&&delete o.maxFeePerBlobGas,o}const defineTransaction=defineFormatter("transaction",formatTransaction);function formatAuthorizationList(et){return et.map(o=>({contractAddress:o.address,chainId:Number(o.chainId),nonce:Number(o.nonce),r:o.r,s:o.s,yParity:Number(o.yParity)}))}function formatBlock(et){var tt;const o=(tt=et.transactions)==null?void 0:tt.map(rt=>typeof rt=="string"?rt:formatTransaction(rt));return{...et,baseFeePerGas:et.baseFeePerGas?BigInt(et.baseFeePerGas):null,blobGasUsed:et.blobGasUsed?BigInt(et.blobGasUsed):void 0,difficulty:et.difficulty?BigInt(et.difficulty):void 0,excessBlobGas:et.excessBlobGas?BigInt(et.excessBlobGas):void 0,gasLimit:et.gasLimit?BigInt(et.gasLimit):void 0,gasUsed:et.gasUsed?BigInt(et.gasUsed):void 0,hash:et.hash?et.hash:null,logsBloom:et.logsBloom?et.logsBloom:null,nonce:et.nonce?et.nonce:null,number:et.number?BigInt(et.number):null,size:et.size?BigInt(et.size):void 0,timestamp:et.timestamp?BigInt(et.timestamp):void 0,transactions:o,totalDifficulty:et.totalDifficulty?BigInt(et.totalDifficulty):null}}const defineBlock=defineFormatter("block",formatBlock);class AccountStateConflictError extends BaseError$3{constructor({address:o}){super(`State for account "${o}" is set multiple times.`,{name:"AccountStateConflictError"})}}class StateAssignmentConflictError extends BaseError$3{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function prettyStateMapping(et){return et.reduce((o,{slot:tt,value:rt})=>`${o} ${tt}: ${rt} +`,"")}function prettyStateOverride(et){return et.reduce((o,{address:tt,...rt})=>{let nt=`${o} ${tt}: +`;return rt.nonce&&(nt+=` nonce: ${rt.nonce} +`),rt.balance&&(nt+=` balance: ${rt.balance} +`),rt.code&&(nt+=` code: ${rt.code} +`),rt.state&&(nt+=` state: +`,nt+=prettyStateMapping(rt.state)),rt.stateDiff&&(nt+=` stateDiff: +`,nt+=prettyStateMapping(rt.stateDiff)),nt},` State Override: +`).slice(0,-1)}function serializeStateMapping(et){if(!(!et||et.length===0))return et.reduce((o,{slot:tt,value:rt})=>{if(tt.length!==66)throw new InvalidBytesLengthError({size:tt.length,targetSize:66,type:"hex"});if(rt.length!==66)throw new InvalidBytesLengthError({size:rt.length,targetSize:66,type:"hex"});return o[tt]=rt,o},{})}function serializeAccountStateOverride(et){const{balance:o,nonce:tt,state:rt,stateDiff:nt,code:ot}=et,it={};if(ot!==void 0&&(it.code=ot),o!==void 0&&(it.balance=numberToHex(o)),tt!==void 0&&(it.nonce=numberToHex(tt)),rt!==void 0&&(it.state=serializeStateMapping(rt)),nt!==void 0){if(it.state)throw new StateAssignmentConflictError;it.stateDiff=serializeStateMapping(nt)}return it}function serializeStateOverride(et){if(!et)return;const o={};for(const{address:tt,...rt}of et){if(!isAddress(tt,{strict:!1}))throw new InvalidAddressError({address:tt});if(o[tt])throw new AccountStateConflictError({address:tt});o[tt]=serializeAccountStateOverride(rt)}return o}async function getBalance$1(et,{address:o,blockNumber:tt,blockTag:rt="latest"}){const nt=tt?numberToHex(tt):void 0,ot=await et.request({method:"eth_getBalance",params:[o,nt||rt]});return BigInt(ot)}function blobsToCommitments(et){const{kzg:o}=et,tt=et.to??(typeof et.blobs[0]=="string"?"hex":"bytes"),rt=typeof et.blobs[0]=="string"?et.blobs.map(ot=>hexToBytes$3(ot)):et.blobs,nt=[];for(const ot of rt)nt.push(Uint8Array.from(o.blobToKzgCommitment(ot)));return tt==="bytes"?nt:nt.map(ot=>bytesToHex$3(ot))}function blobsToProofs(et){const{kzg:o}=et,tt=et.to??(typeof et.blobs[0]=="string"?"hex":"bytes"),rt=typeof et.blobs[0]=="string"?et.blobs.map(it=>hexToBytes$3(it)):et.blobs,nt=typeof et.commitments[0]=="string"?et.commitments.map(it=>hexToBytes$3(it)):et.commitments,ot=[];for(let it=0;itbytesToHex$3(it))}function setBigUint64$1(et,o,tt,rt){if(typeof et.setBigUint64=="function")return et.setBigUint64(o,tt,rt);const nt=BigInt(32),ot=BigInt(4294967295),it=Number(tt>>nt&ot),st=Number(tt&ot),at=rt?4:0,ct=rt?0:4;et.setUint32(o+at,it,rt),et.setUint32(o+ct,st,rt)}const Chi=(et,o,tt)=>et&o^~et&tt,Maj=(et,o,tt)=>et&o^et&tt^o&tt;class HashMD extends Hash{constructor(o,tt,rt,nt){super(),this.blockLen=o,this.outputLen=tt,this.padOffset=rt,this.isLE=nt,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(o),this.view=createView$1(this.buffer)}update(o){exists$1(this);const{view:tt,buffer:rt,blockLen:nt}=this;o=toBytes$2(o);const ot=o.length;for(let it=0;itnt-it&&(this.process(rt,0),it=0);for(let dt=it;dtlt.length)throw new Error("_sha2: outputLen bigger than state");for(let dt=0;dt>>3,pt=rotr(mt,17)^rotr(mt,19)^mt>>>10;SHA256_W[dt]=pt+SHA256_W[dt-7]+ft+SHA256_W[dt-16]|0}let{A:rt,B:nt,C:ot,D:it,E:st,F:at,G:ct,H:lt}=this;for(let dt=0;dt<64;dt++){const ht=rotr(st,6)^rotr(st,11)^rotr(st,25),mt=lt+ht+Chi(st,at,ct)+SHA256_K[dt]+SHA256_W[dt]|0,pt=(rotr(rt,2)^rotr(rt,13)^rotr(rt,22))+Maj(rt,nt,ot)|0;lt=ct,ct=at,at=st,st=it+mt|0,it=ot,ot=nt,nt=rt,rt=mt+pt|0}rt=rt+this.A|0,nt=nt+this.B|0,ot=ot+this.C|0,it=it+this.D|0,st=st+this.E|0,at=at+this.F|0,ct=ct+this.G|0,lt=lt+this.H|0,this.set(rt,nt,ot,it,st,at,ct,lt)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const sha256$3=wrapConstructor(()=>new SHA256);function sha256$2(et,o){return sha256$3(isHex(et,{strict:!1})?toBytes$3(et):et)}function commitmentToVersionedHash(et){const{commitment:o,version:tt=1}=et,rt=et.to??(typeof o=="string"?"hex":"bytes"),nt=sha256$2(o);return nt.set([tt],0),rt==="bytes"?nt:bytesToHex$3(nt)}function commitmentsToVersionedHashes(et){const{commitments:o,version:tt}=et,rt=et.to??(typeof o[0]=="string"?"hex":"bytes"),nt=[];for(const ot of o)nt.push(commitmentToVersionedHash({commitment:ot,to:rt,version:tt}));return nt}const blobsPerTransaction=6,bytesPerFieldElement=32,fieldElementsPerBlob=4096,bytesPerBlob=bytesPerFieldElement*fieldElementsPerBlob,maxBytesPerTransaction=bytesPerBlob*blobsPerTransaction-1-1*fieldElementsPerBlob*blobsPerTransaction,versionedHashVersionKzg=1;class BlobSizeTooLargeError extends BaseError$3{constructor({maxSize:o,size:tt}){super("Blob size is too large.",{metaMessages:[`Max: ${o} bytes`,`Given: ${tt} bytes`],name:"BlobSizeTooLargeError"})}}class EmptyBlobError extends BaseError$3{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class InvalidVersionedHashSizeError extends BaseError$3{constructor({hash:o,size:tt}){super(`Versioned hash "${o}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${tt}`],name:"InvalidVersionedHashSizeError"})}}class InvalidVersionedHashVersionError extends BaseError$3{constructor({hash:o,version:tt}){super(`Versioned hash "${o}" version is invalid.`,{metaMessages:[`Expected: ${versionedHashVersionKzg}`,`Received: ${tt}`],name:"InvalidVersionedHashVersionError"})}}function toBlobs(et){const o=et.to??(typeof et.data=="string"?"hex":"bytes"),tt=typeof et.data=="string"?hexToBytes$3(et.data):et.data,rt=size$2(tt);if(!rt)throw new EmptyBlobError;if(rt>maxBytesPerTransaction)throw new BlobSizeTooLargeError({maxSize:maxBytesPerTransaction,size:rt});const nt=[];let ot=!0,it=0;for(;ot;){const st=createCursor(new Uint8Array(bytesPerBlob));let at=0;for(;atst.bytes):nt.map(st=>bytesToHex$3(st.bytes))}function toBlobSidecars(et){const{data:o,kzg:tt,to:rt}=et,nt=et.blobs??toBlobs({data:o,to:rt}),ot=et.commitments??blobsToCommitments({blobs:nt,kzg:tt,to:rt}),it=et.proofs??blobsToProofs({blobs:nt,commitments:ot,kzg:tt,to:rt}),st=[];for(let at=0;at1||tt[0]>1)throw new InvalidBytesBooleanError(tt);return!!tt[0]}function bytesToNumber$1(et,o={}){typeof o.size<"u"&&assertSize(et,{size:o.size});const tt=bytesToHex$3(et,o);return hexToNumber$2(tt,o)}function bytesToString(et,o={}){let tt=et;return typeof o.size<"u"&&(assertSize(tt,{size:o.size}),tt=trim$1(tt,{dir:"right"})),new TextDecoder().decode(tt)}function decodeAbiParameters(et,o){const tt=typeof o=="string"?hexToBytes$3(o):o,rt=createCursor(tt);if(size$2(tt)===0&&et.length>0)throw new AbiDecodingZeroDataError;if(size$2(o)&&size$2(o)<32)throw new AbiDecodingDataSizeTooSmallError({data:typeof o=="string"?o:bytesToHex$3(o),params:et,size:size$2(o)});let nt=0;const ot=[];for(let it=0;it48?bytesToBigInt(nt,{signed:tt}):bytesToNumber$1(nt,{signed:tt}),32]}function decodeTuple(et,o,{staticPosition:tt}){const rt=o.components.length===0||o.components.some(({name:it})=>!it),nt=rt?[]:{};let ot=0;if(hasDynamicChild(o)){const it=bytesToNumber$1(et.readBytes(sizeOfOffset)),st=tt+it;for(let at=0;atkeccak256$1(toBytes$3(et));function hashSignature(et){return hash(et)}const version$7="1.0.6";let BaseError$2=class ks extends Error{constructor(o,tt={}){var it;const rt=tt.cause instanceof ks?tt.cause.details:(it=tt.cause)!=null&&it.message?tt.cause.message:tt.details,nt=tt.cause instanceof ks&&tt.cause.docsPath||tt.docsPath,ot=[o||"An error occurred.","",...tt.metaMessages?[...tt.metaMessages,""]:[],...nt?[`Docs: https://abitype.dev${nt}`]:[],...rt?[`Details: ${rt}`]:[],`Version: abitype@${version$7}`].join(` +`);super(ot),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),tt.cause&&(this.cause=tt.cause),this.details=rt,this.docsPath=nt,this.metaMessages=tt.metaMessages,this.shortMessage=o}};function execTyped(et,o){const tt=et.exec(o);return tt==null?void 0:tt.groups}const bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,integerRegex=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,isTupleRegex=/^\(.+?\).*?$/,tupleRegex=/^tuple(?(\[(\d*)\])*)$/;function formatAbiParameter(et){let o=et.type;if(tupleRegex.test(et.type)&&"components"in et){o="(";const tt=et.components.length;for(let nt=0;nt[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;function isErrorSignature(et){return errorSignatureRegex.test(et)}function execErrorSignature(et){return execTyped(errorSignatureRegex,et)}const eventSignatureRegex=/^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;function isEventSignature(et){return eventSignatureRegex.test(et)}function execEventSignature(et){return execTyped(eventSignatureRegex,et)}const functionSignatureRegex=/^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/;function isFunctionSignature(et){return functionSignatureRegex.test(et)}function execFunctionSignature(et){return execTyped(functionSignatureRegex,et)}const structSignatureRegex=/^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/;function isStructSignature(et){return structSignatureRegex.test(et)}function execStructSignature(et){return execTyped(structSignatureRegex,et)}const constructorSignatureRegex=/^constructor\((?.*?)\)(?:\s(?payable{1}))?$/;function isConstructorSignature(et){return constructorSignatureRegex.test(et)}function execConstructorSignature(et){return execTyped(constructorSignatureRegex,et)}const fallbackSignatureRegex=/^fallback\(\) external(?:\s(?payable{1}))?$/;function isFallbackSignature(et){return fallbackSignatureRegex.test(et)}const receiveSignatureRegex=/^receive\(\) external payable$/;function isReceiveSignature(et){return receiveSignatureRegex.test(et)}const eventModifiers=new Set(["indexed"]),functionModifiers=new Set(["calldata","memory","storage"]);class UnknownTypeError extends BaseError$2{constructor({type:o}){super("Unknown type.",{metaMessages:[`Type "${o}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class UnknownSolidityTypeError extends BaseError$2{constructor({type:o}){super("Unknown type.",{metaMessages:[`Type "${o}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class InvalidParameterError extends BaseError$2{constructor({param:o}){super("Invalid ABI parameter.",{details:o}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class SolidityProtectedKeywordError extends BaseError$2{constructor({param:o,name:tt}){super("Invalid ABI parameter.",{details:o,metaMessages:[`"${tt}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}}class InvalidModifierError extends BaseError$2{constructor({param:o,type:tt,modifier:rt}){super("Invalid ABI parameter.",{details:o,metaMessages:[`Modifier "${rt}" not allowed${tt?` in "${tt}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class InvalidFunctionModifierError extends BaseError$2{constructor({param:o,type:tt,modifier:rt}){super("Invalid ABI parameter.",{details:o,metaMessages:[`Modifier "${rt}" not allowed${tt?` in "${tt}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${rt}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class InvalidAbiTypeParameterError extends BaseError$2{constructor({abiParameter:o}){super("Invalid ABI parameter.",{details:JSON.stringify(o,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}let InvalidSignatureError$1=class extends BaseError$2{constructor({signature:o,type:tt}){super(`Invalid ${tt} signature.`,{details:o}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};class UnknownSignatureError extends BaseError$2{constructor({signature:o}){super("Unknown signature.",{details:o}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class InvalidStructSignatureError extends BaseError$2{constructor({signature:o}){super("Invalid struct signature.",{details:o,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class CircularReferenceError extends BaseError$2{constructor({type:o}){super("Circular reference detected.",{metaMessages:[`Struct "${o}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class InvalidParenthesisError extends BaseError$2{constructor({current:o,depth:tt}){super("Unbalanced parentheses.",{metaMessages:[`"${o.trim()}" has too many ${tt>0?"opening":"closing"} parentheses.`],details:`Depth "${tt}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function getParameterCacheKey(et,o){return o?`${o}:${et}`:et}const parameterCache=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function parseSignature(et,o={}){if(isFunctionSignature(et)){const tt=execFunctionSignature(et);if(!tt)throw new InvalidSignatureError$1({signature:et,type:"function"});const rt=splitParameters(tt.parameters),nt=[],ot=rt.length;for(let st=0;st[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,abiParameterWithTupleRegex=/^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,dynamicIntegerRegex=/^u?int$/;function parseAbiParameter(et,o){var dt,ht;const tt=getParameterCacheKey(et,o==null?void 0:o.type);if(parameterCache.has(tt))return parameterCache.get(tt);const rt=isTupleRegex.test(et),nt=execTyped(rt?abiParameterWithTupleRegex:abiParameterWithoutTupleRegex,et);if(!nt)throw new InvalidParameterError({param:et});if(nt.name&&isSolidityKeyword(nt.name))throw new SolidityProtectedKeywordError({param:et,name:nt.name});const ot=nt.name?{name:nt.name}:{},it=nt.modifier==="indexed"?{indexed:!0}:{},st=(o==null?void 0:o.structs)??{};let at,ct={};if(rt){at="tuple";const mt=splitParameters(nt.type),ft=[],pt=mt.length;for(let gt=0;gt[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/;function resolveStructs(et,o,tt=new Set){const rt=[],nt=et.length;for(let ot=0;ot{const o=typeof et=="string"?et:formatAbiItem(et);return normalizeSignature$1(o)};function toSignatureHash(et){return hashSignature(toSignature(et))}const toEventSelector=toSignatureHash,toFunctionSelector=et=>slice(toSignatureHash(et),0,4);function getAbiItem(et){const{abi:o,args:tt=[],name:rt}=et,nt=isHex(rt,{strict:!1}),ot=o.filter(st=>nt?st.type==="function"?toFunctionSelector(st)===rt:st.type==="event"?toEventSelector(st)===rt:!1:"name"in st&&st.name===rt);if(ot.length===0)return;if(ot.length===1)return ot[0];let it;for(const st of ot){if(!("inputs"in st))continue;if(!tt||tt.length===0){if(!st.inputs||st.inputs.length===0)return st;continue}if(!st.inputs||st.inputs.length===0||st.inputs.length!==tt.length)continue;if(tt.every((ct,lt)=>{const dt="inputs"in st&&st.inputs[lt];return dt?isArgOfType(ct,dt):!1})){if(it&&"inputs"in it&&it.inputs){const ct=getAmbiguousTypes(st.inputs,it.inputs,tt);if(ct)throw new AbiItemAmbiguityError({abiItem:st,type:ct[0]},{abiItem:it,type:ct[1]})}it=st}}return it||ot[0]}function isArgOfType(et,o){const tt=typeof et,rt=o.type;switch(rt){case"address":return isAddress(et,{strict:!1});case"bool":return tt==="boolean";case"function":return tt==="string";case"string":return tt==="string";default:return rt==="tuple"&&"components"in o?Object.values(o.components).every((nt,ot)=>isArgOfType(Object.values(et)[ot],nt)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(rt)?tt==="number"||tt==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(rt)?tt==="string"||et instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(rt)?Array.isArray(et)&&et.every(nt=>isArgOfType(nt,{...o,type:rt.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function getAmbiguousTypes(et,o,tt){for(const rt in et){const nt=et[rt],ot=o[rt];if(nt.type==="tuple"&&ot.type==="tuple"&&"components"in nt&&"components"in ot)return getAmbiguousTypes(nt.components,ot.components,tt[rt]);const it=[nt.type,ot.type];if(it.includes("address")&&it.includes("bytes20")?!0:it.includes("address")&&it.includes("string")?isAddress(tt[rt],{strict:!1}):it.includes("address")&&it.includes("bytes")?isAddress(tt[rt],{strict:!1}):!1)return it}}const docsPath$1="/docs/contract/decodeFunctionResult";function decodeFunctionResult(et){const{abi:o,args:tt,functionName:rt,data:nt}=et;let ot=o[0];if(rt){const st=getAbiItem({abi:o,args:tt,name:rt});if(!st)throw new AbiFunctionNotFoundError(rt,{docsPath:docsPath$1});ot=st}if(ot.type!=="function")throw new AbiFunctionNotFoundError(void 0,{docsPath:docsPath$1});if(!ot.outputs)throw new AbiFunctionOutputsNotFoundError(ot.name,{docsPath:docsPath$1});const it=decodeAbiParameters(ot.outputs,nt);if(it&&it.length>1)return it;if(it&&it.length===1)return it[0]}const docsPath="/docs/contract/encodeFunctionData";function prepareEncodeFunctionData(et){const{abi:o,args:tt,functionName:rt}=et;let nt=o[0];if(rt){const ot=getAbiItem({abi:o,args:tt,name:rt});if(!ot)throw new AbiFunctionNotFoundError(rt,{docsPath});nt=ot}if(nt.type!=="function")throw new AbiFunctionNotFoundError(void 0,{docsPath});return{abi:[nt],functionName:toFunctionSelector(formatAbiItem$1(nt))}}function encodeFunctionData(et){const{args:o}=et,{abi:tt,functionName:rt}=(()=>{var st;return et.abi.length===1&&((st=et.functionName)!=null&&st.startsWith("0x"))?et:prepareEncodeFunctionData(et)})(),nt=tt[0],ot=rt,it="inputs"in nt&&nt.inputs?encodeAbiParameters(nt.inputs,o??[]):void 0;return concatHex([ot,it??"0x"])}function getChainContractAddress({blockNumber:et,chain:o,contract:tt}){var nt;const rt=(nt=o==null?void 0:o.contracts)==null?void 0:nt[tt];if(!rt)throw new ChainDoesNotSupportContract({chain:o,contract:{name:tt}});if(et&&rt.blockCreated&&rt.blockCreated>et)throw new ChainDoesNotSupportContract({blockNumber:et,chain:o,contract:{name:tt,blockCreated:rt.blockCreated}});return rt.address}const panicReasons={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},solidityError={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},solidityPanic={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};function decodeErrorResult(et){const{abi:o,data:tt}=et,rt=slice(tt,0,4);if(rt==="0x")throw new AbiDecodingZeroDataError;const ot=[...o||[],solidityError,solidityPanic].find(it=>it.type==="error"&&rt===toFunctionSelector(formatAbiItem$1(it)));if(!ot)throw new AbiErrorSignatureNotFoundError(rt,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:ot,args:"inputs"in ot&&ot.inputs&&ot.inputs.length>0?decodeAbiParameters(ot.inputs,slice(tt,4)):void 0,errorName:ot.name}}function formatAbiItemWithArgs({abiItem:et,args:o,includeFunctionName:tt=!0,includeName:rt=!1}){if("name"in et&&"inputs"in et&&et.inputs)return`${tt?et.name:""}(${et.inputs.map((nt,ot)=>`${rt&&nt.name?`${nt.name}: `:""}${typeof o[ot]=="object"?stringify$2(o[ot]):o[ot]}`).join(", ")})`}class CallExecutionError extends BaseError$3{constructor(o,{account:tt,docsPath:rt,chain:nt,data:ot,gas:it,gasPrice:st,maxFeePerGas:at,maxPriorityFeePerGas:ct,nonce:lt,to:dt,value:ht,stateOverride:mt}){var gt;const ft=tt?parseAccount(tt):void 0;let pt=prettyPrint({from:ft==null?void 0:ft.address,to:dt,value:typeof ht<"u"&&`${formatEther(ht)} ${((gt=nt==null?void 0:nt.nativeCurrency)==null?void 0:gt.symbol)||"ETH"}`,data:ot,gas:it,gasPrice:typeof st<"u"&&`${formatGwei(st)} gwei`,maxFeePerGas:typeof at<"u"&&`${formatGwei(at)} gwei`,maxPriorityFeePerGas:typeof ct<"u"&&`${formatGwei(ct)} gwei`,nonce:lt});mt&&(pt+=` +${prettyStateOverride(mt)}`),super(o.shortMessage,{cause:o,docsPath:rt,metaMessages:[...o.metaMessages?[...o.metaMessages," "]:[],"Raw Call Arguments:",pt].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=o}}class ContractFunctionExecutionError extends BaseError$3{constructor(o,{abi:tt,args:rt,contractAddress:nt,docsPath:ot,functionName:it,sender:st}){const at=getAbiItem({abi:tt,args:rt,name:it}),ct=at?formatAbiItemWithArgs({abiItem:at,args:rt,includeFunctionName:!1,includeName:!1}):void 0,lt=at?formatAbiItem$1(at,{includeName:!0}):void 0,dt=prettyPrint({address:nt&&getContractAddress(nt),function:lt,args:ct&&ct!=="()"&&`${[...Array((it==null?void 0:it.length)??0).keys()].map(()=>" ").join("")}${ct}`,sender:st});super(o.shortMessage||`An unknown error occurred while executing the contract function "${it}".`,{cause:o,docsPath:ot,metaMessages:[...o.metaMessages?[...o.metaMessages," "]:[],dt&&"Contract Call:",dt].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=tt,this.args=rt,this.cause=o,this.contractAddress=nt,this.functionName=it,this.sender=st}}class ContractFunctionRevertedError extends BaseError$3{constructor({abi:o,data:tt,functionName:rt,message:nt}){let ot,it,st,at;if(tt&&tt!=="0x")try{it=decodeErrorResult({abi:o,data:tt});const{abiItem:lt,errorName:dt,args:ht}=it;if(dt==="Error")at=ht[0];else if(dt==="Panic"){const[mt]=ht;at=panicReasons[mt]}else{const mt=lt?formatAbiItem$1(lt,{includeName:!0}):void 0,ft=lt&&ht?formatAbiItemWithArgs({abiItem:lt,args:ht,includeFunctionName:!1,includeName:!1}):void 0;st=[mt?`Error: ${mt}`:"",ft&&ft!=="()"?` ${[...Array((dt==null?void 0:dt.length)??0).keys()].map(()=>" ").join("")}${ft}`:""]}}catch(lt){ot=lt}else nt&&(at=nt);let ct;ot instanceof AbiErrorSignatureNotFoundError&&(ct=ot.signature,st=[`Unable to decode signature "${ct}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${ct}.`]),super(at&&at!=="execution reverted"||ct?[`The contract function "${rt}" reverted with the following ${ct?"signature":"reason"}:`,at||ct].join(` +`):`The contract function "${rt}" reverted.`,{cause:ot,metaMessages:st,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=it,this.reason=at,this.signature=ct}}class ContractFunctionZeroDataError extends BaseError$3{constructor({functionName:o}){super(`The contract function "${o}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${o}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class CounterfactualDeploymentFailedError extends BaseError$3{constructor({factory:o}){super(`Deployment for counterfactual contract call failed${o?` for factory "${o}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class RawContractError extends BaseError$3{constructor({data:o,message:tt}){super(tt||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=o}}function isNullUniversalResolverError(et,o){var rt,nt,ot,it,st,at;if(!(et instanceof BaseError$3))return!1;const tt=et.walk(ct=>ct instanceof ContractFunctionRevertedError);return tt instanceof ContractFunctionRevertedError?!!(((rt=tt.data)==null?void 0:rt.errorName)==="ResolverNotFound"||((nt=tt.data)==null?void 0:nt.errorName)==="ResolverWildcardNotSupported"||((ot=tt.data)==null?void 0:ot.errorName)==="ResolverNotContract"||((it=tt.data)==null?void 0:it.errorName)==="ResolverError"||((st=tt.data)==null?void 0:st.errorName)==="HttpError"||(at=tt.reason)!=null&&at.includes("Wildcard on non-extended resolvers is not supported")||o==="reverse"&&tt.reason===panicReasons[50]):!1}function encodedLabelToLabelhash(et){if(et.length!==66||et.indexOf("[")!==0||et.indexOf("]")!==65)return null;const o=`0x${et.slice(1,65)}`;return isHex(o)?o:null}function namehash(et){let o=new Uint8Array(32).fill(0);if(!et)return bytesToHex$3(o);const tt=et.split(".");for(let rt=tt.length-1;rt>=0;rt-=1){const nt=encodedLabelToLabelhash(tt[rt]),ot=nt?toBytes$3(nt):keccak256$1(stringToBytes(tt[rt]),"bytes");o=keccak256$1(concat$6([o,ot]),"bytes")}return bytesToHex$3(o)}function encodeLabelhash(et){return`[${et.slice(2)}]`}function labelhash(et){const o=new Uint8Array(32).fill(0);return et?encodedLabelToLabelhash(et)||keccak256$1(stringToBytes(et)):bytesToHex$3(o)}function packetToBytes(et){const o=et.replace(/^\.|\.$/gm,"");if(o.length===0)return new Uint8Array(1);const tt=new Uint8Array(stringToBytes(o).byteLength+2);let rt=0;const nt=o.split(".");for(let ot=0;ot255&&(it=stringToBytes(encodeLabelhash(labelhash(nt[ot])))),tt[rt]=it.length,tt.set(it,rt+1),rt+=it.length+1}return tt.byteLength!==rt+1?tt.slice(0,rt+1):tt}const EXECUTION_REVERTED_ERROR_CODE=3;function getContractError(et,{abi:o,address:tt,args:rt,docsPath:nt,functionName:ot,sender:it}){const{code:st,data:at,message:ct,shortMessage:lt}=et instanceof RawContractError?et:et instanceof BaseError$3?et.walk(ht=>"data"in ht)||et.walk():{},dt=et instanceof AbiDecodingZeroDataError?new ContractFunctionZeroDataError({functionName:ot}):[EXECUTION_REVERTED_ERROR_CODE,InternalRpcError.code].includes(st)&&(at||ct||lt)?new ContractFunctionRevertedError({abi:o,data:typeof at=="object"?at.data:at,functionName:ot,message:lt??ct}):et;return new ContractFunctionExecutionError(dt,{abi:o,args:rt,contractAddress:tt,docsPath:nt,functionName:ot,sender:it})}const aggregate3Signature="0x82ad56cb",deploylessCallViaBytecodeBytecode="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",deploylessCallViaFactoryBytecode="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe";function getCallError(et,{docsPath:o,...tt}){const rt=(()=>{const nt=getNodeError(et,tt);return nt instanceof UnknownNodeError?et:nt})();return new CallExecutionError(rt,{docsPath:o,...tt})}const schedulerCache=new Map;function createBatchScheduler({fn:et,id:o,shouldSplitBatch:tt,wait:rt=0,sort:nt}){const ot=async()=>{const lt=at();it();const dt=lt.map(({args:ht})=>ht);dt.length!==0&&et(dt).then(ht=>{var mt;nt&&Array.isArray(ht)&&ht.sort(nt);for(let ft=0;ft{var mt;for(let ft=0;ftschedulerCache.delete(o),st=()=>at().map(({args:lt})=>lt),at=()=>schedulerCache.get(o)||[],ct=lt=>schedulerCache.set(o,[...at(),lt]);return{flush:it,async schedule(lt){const dt={},ht=new Promise((pt,gt)=>{dt.resolve=pt,dt.reject=gt});return(tt==null?void 0:tt([...st(),lt]))&&ot(),at().length>0?(ct({args:lt,pendingPromise:dt}),ht):(ct({args:lt,pendingPromise:dt}),setTimeout(ot,rt),ht)}}}async function call(et,o){var Ot,Nt,Yt,Ft;const{account:tt=et.account,batch:rt=!!((Ot=et.batch)!=null&&Ot.multicall),blockNumber:nt,blockTag:ot="latest",accessList:it,blobs:st,code:at,data:ct,factory:lt,factoryData:dt,gas:ht,gasPrice:mt,maxFeePerBlobGas:ft,maxFeePerGas:pt,maxPriorityFeePerGas:gt,nonce:yt,to:bt,value:xt,stateOverride:vt,...Et}=o,Ct=tt?parseAccount(tt):void 0;if(at&&(lt||dt))throw new BaseError$3("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(at&&bt)throw new BaseError$3("Cannot provide both `code` & `to` as parameters.");const St=at&&ct,At=lt&&dt&&bt&&ct,kt=St||At,It=St?toDeploylessCallViaBytecodeData({code:at,data:ct}):At?toDeploylessCallViaFactoryData({data:ct,factory:lt,factoryData:dt,to:bt}):ct;try{assertRequest(o);const Qt=(nt?numberToHex(nt):void 0)||ot,Vt=serializeStateOverride(vt),Bt=(Ft=(Yt=(Nt=et.chain)==null?void 0:Nt.formatters)==null?void 0:Yt.transactionRequest)==null?void 0:Ft.format,jt=(Bt||formatTransactionRequest)({...extract$1(Et,{format:Bt}),from:Ct==null?void 0:Ct.address,accessList:it,blobs:st,data:It,gas:ht,gasPrice:mt,maxFeePerBlobGas:ft,maxFeePerGas:pt,maxPriorityFeePerGas:gt,nonce:yt,to:kt?void 0:bt,value:xt});if(rt&&shouldPerformMulticall({request:jt})&&!Vt)try{return await scheduleMulticall(et,{...jt,blockNumber:nt,blockTag:ot})}catch(Kt){if(!(Kt instanceof ClientChainNotConfiguredError)&&!(Kt instanceof ChainDoesNotSupportContract))throw Kt}const Xt=await et.request({method:"eth_call",params:Vt?[jt,Qt,Vt]:[jt,Qt]});return Xt==="0x"?{data:void 0}:{data:Xt}}catch(Ht){const Qt=getRevertErrorData(Ht),{offchainLookup:Vt,offchainLookupSignature:Bt}=await __vitePreload(async()=>{const{offchainLookup:Wt,offchainLookupSignature:jt}=await import("./ccip-DHJq9nI9.js");return{offchainLookup:Wt,offchainLookupSignature:jt}},[]);if(et.ccipRead!==!1&&(Qt==null?void 0:Qt.slice(0,10))===Bt&&bt)return{data:await Vt(et,{data:Qt,to:bt})};throw kt&&(Qt==null?void 0:Qt.slice(0,10))==="0x101bb98d"?new CounterfactualDeploymentFailedError({factory:lt}):getCallError(Ht,{...o,account:Ct,chain:et.chain})}}function shouldPerformMulticall({request:et}){const{data:o,to:tt,...rt}=et;return!(!o||o.startsWith(aggregate3Signature)||!tt||Object.values(rt).filter(nt=>typeof nt<"u").length>0)}async function scheduleMulticall(et,o){var pt;const{batchSize:tt=1024,wait:rt=0}=typeof((pt=et.batch)==null?void 0:pt.multicall)=="object"?et.batch.multicall:{},{blockNumber:nt,blockTag:ot="latest",data:it,multicallAddress:st,to:at}=o;let ct=st;if(!ct){if(!et.chain)throw new ClientChainNotConfiguredError;ct=getChainContractAddress({blockNumber:nt,chain:et.chain,contract:"multicall3"})}const dt=(nt?numberToHex(nt):void 0)||ot,{schedule:ht}=createBatchScheduler({id:`${et.uid}.${dt}`,wait:rt,shouldSplitBatch(gt){return gt.reduce((bt,{data:xt})=>bt+(xt.length-2),0)>tt*2},fn:async gt=>{const yt=gt.map(vt=>({allowFailure:!0,callData:vt.data,target:vt.to})),bt=encodeFunctionData({abi:multicall3Abi,args:[yt],functionName:"aggregate3"}),xt=await et.request({method:"eth_call",params:[{data:bt,to:ct},dt]});return decodeFunctionResult({abi:multicall3Abi,args:[yt],functionName:"aggregate3",data:xt||"0x"})}}),[{returnData:mt,success:ft}]=await ht({data:it,to:at});if(!ft)throw new RawContractError({data:mt});return mt==="0x"?{data:void 0}:{data:mt}}function toDeploylessCallViaBytecodeData(et){const{code:o,data:tt}=et;return encodeDeployData({abi:parseAbi(["constructor(bytes, bytes)"]),bytecode:deploylessCallViaBytecodeBytecode,args:[o,tt]})}function toDeploylessCallViaFactoryData(et){const{data:o,factory:tt,factoryData:rt,to:nt}=et;return encodeDeployData({abi:parseAbi(["constructor(address, bytes, address, bytes)"]),bytecode:deploylessCallViaFactoryBytecode,args:[nt,o,tt,rt]})}function getRevertErrorData(et){var tt;if(!(et instanceof BaseError$3))return;const o=et.walk();return typeof(o==null?void 0:o.data)=="object"?(tt=o.data)==null?void 0:tt.data:o.data}async function readContract$1(et,o){const{abi:tt,address:rt,args:nt,functionName:ot,...it}=o,st=encodeFunctionData({abi:tt,args:nt,functionName:ot});try{const{data:at}=await getAction$1(et,call,"call")({...it,data:st,to:rt});return decodeFunctionResult({abi:tt,args:nt,functionName:ot,data:at||"0x"})}catch(at){throw getContractError(at,{abi:tt,address:rt,args:nt,docsPath:"/docs/contract/readContract",functionName:ot})}}async function getEnsAddress$1(et,{blockNumber:o,blockTag:tt,coinType:rt,name:nt,gatewayUrls:ot,strict:it,universalResolverAddress:st}){let at=st;if(!at){if(!et.chain)throw new Error("client chain not configured. universalResolverAddress is required.");at=getChainContractAddress({blockNumber:o,chain:et.chain,contract:"ensUniversalResolver"})}try{const ct=encodeFunctionData({abi:addressResolverAbi,functionName:"addr",...rt!=null?{args:[namehash(nt),BigInt(rt)]}:{args:[namehash(nt)]}}),lt={address:at,abi:universalResolverResolveAbi,functionName:"resolve",args:[toHex(packetToBytes(nt)),ct],blockNumber:o,blockTag:tt},dt=getAction$1(et,readContract$1,"readContract"),ht=ot?await dt({...lt,args:[...lt.args,ot]}):await dt(lt);if(ht[0]==="0x")return null;const mt=decodeFunctionResult({abi:addressResolverAbi,args:rt!=null?[namehash(nt),BigInt(rt)]:void 0,functionName:"addr",data:ht[0]});return mt==="0x"||trim$1(mt)==="0x00"?null:mt}catch(ct){if(it)throw ct;if(isNullUniversalResolverError(ct,"resolve"))return null;throw ct}}class EnsAvatarInvalidMetadataError extends BaseError$3{constructor({data:o}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(o)}`],name:"EnsAvatarInvalidMetadataError"})}}class EnsAvatarInvalidNftUriError extends BaseError$3{constructor({reason:o}){super(`ENS NFT avatar URI is invalid. ${o}`,{name:"EnsAvatarInvalidNftUriError"})}}class EnsAvatarUriResolutionError extends BaseError$3{constructor({uri:o}){super(`Unable to resolve ENS avatar URI "${o}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class EnsAvatarUnsupportedNamespaceError extends BaseError$3{constructor({namespace:o}){super(`ENS NFT avatar namespace "${o}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const networkRegex=/(?https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/,ipfsHashRegex=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/,base64Regex$1=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,dataURIRegex=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function isImageUri(et){try{const o=await fetch(et,{method:"HEAD"});if(o.status===200){const tt=o.headers.get("content-type");return tt==null?void 0:tt.startsWith("image/")}return!1}catch(o){return typeof o=="object"&&typeof o.response<"u"||!globalThis.hasOwnProperty("Image")?!1:new Promise(tt=>{const rt=new Image;rt.onload=()=>{tt(!0)},rt.onerror=()=>{tt(!1)},rt.src=et})}}function getGateway(et,o){return et?et.endsWith("/")?et.slice(0,-1):et:o}function resolveAvatarUri({uri:et,gatewayUrls:o}){const tt=base64Regex$1.test(et);if(tt)return{uri:et,isOnChain:!0,isEncoded:tt};const rt=getGateway(o==null?void 0:o.ipfs,"https://ipfs.io"),nt=getGateway(o==null?void 0:o.arweave,"https://arweave.net"),ot=et.match(networkRegex),{protocol:it,subpath:st,target:at,subtarget:ct=""}=(ot==null?void 0:ot.groups)||{},lt=it==="ipns:/"||st==="ipns/",dt=it==="ipfs:/"||st==="ipfs/"||ipfsHashRegex.test(et);if(et.startsWith("http")&&!lt&&!dt){let mt=et;return o!=null&&o.arweave&&(mt=et.replace(/https:\/\/arweave.net/g,o==null?void 0:o.arweave)),{uri:mt,isOnChain:!1,isEncoded:!1}}if((lt||dt)&&at)return{uri:`${rt}/${lt?"ipns":"ipfs"}/${at}${ct}`,isOnChain:!1,isEncoded:!1};if(it==="ar:/"&&at)return{uri:`${nt}/${at}${ct||""}`,isOnChain:!1,isEncoded:!1};let ht=et.replace(dataURIRegex,"");if(ht.startsWith("nt.json());return await parseAvatarUri({gatewayUrls:et,uri:getJsonImage(tt)})}catch{throw new EnsAvatarUriResolutionError({uri:o})}}async function parseAvatarUri({gatewayUrls:et,uri:o}){const{uri:tt,isOnChain:rt}=resolveAvatarUri({uri:o,gatewayUrls:et});if(rt||await isImageUri(tt))return tt;throw new EnsAvatarUriResolutionError({uri:o})}function parseNftUri(et){let o=et;o.startsWith("did:nft:")&&(o=o.replace("did:nft:","").replace(/_/g,"/"));const[tt,rt,nt]=o.split("/"),[ot,it]=tt.split(":"),[st,at]=rt.split(":");if(!ot||ot.toLowerCase()!=="eip155")throw new EnsAvatarInvalidNftUriError({reason:"Only EIP-155 supported"});if(!it)throw new EnsAvatarInvalidNftUriError({reason:"Chain ID not found"});if(!at)throw new EnsAvatarInvalidNftUriError({reason:"Contract address not found"});if(!nt)throw new EnsAvatarInvalidNftUriError({reason:"Token ID not found"});if(!st)throw new EnsAvatarInvalidNftUriError({reason:"ERC namespace not found"});return{chainID:Number.parseInt(it),namespace:st.toLowerCase(),contractAddress:at,tokenID:nt}}async function getNftTokenUri(et,{nft:o}){if(o.namespace==="erc721")return readContract$1(et,{address:o.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(o.tokenID)]});if(o.namespace==="erc1155")return readContract$1(et,{address:o.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(o.tokenID)]});throw new EnsAvatarUnsupportedNamespaceError({namespace:o.namespace})}async function parseAvatarRecord(et,{gatewayUrls:o,record:tt}){return/eip155:/i.test(tt)?parseNftAvatarUri(et,{gatewayUrls:o,record:tt}):parseAvatarUri({uri:tt,gatewayUrls:o})}async function parseNftAvatarUri(et,{gatewayUrls:o,record:tt}){const rt=parseNftUri(tt),nt=await getNftTokenUri(et,{nft:rt}),{uri:ot,isOnChain:it,isEncoded:st}=resolveAvatarUri({uri:nt,gatewayUrls:o});if(it&&(ot.includes("data:application/json;base64,")||ot.startsWith("{"))){const ct=st?atob(ot.replace("data:application/json;base64,","")):ot,lt=JSON.parse(ct);return parseAvatarUri({uri:getJsonImage(lt),gatewayUrls:o})}let at=rt.tokenID;return rt.namespace==="erc1155"&&(at=at.replace("0x","").padStart(64,"0")),getMetadataAvatarUri({gatewayUrls:o,uri:ot.replace(/(?:0x)?{id}/,at)})}async function getEnsText(et,{blockNumber:o,blockTag:tt,name:rt,key:nt,gatewayUrls:ot,strict:it,universalResolverAddress:st}){let at=st;if(!at){if(!et.chain)throw new Error("client chain not configured. universalResolverAddress is required.");at=getChainContractAddress({blockNumber:o,chain:et.chain,contract:"ensUniversalResolver"})}try{const ct={address:at,abi:universalResolverResolveAbi,functionName:"resolve",args:[toHex(packetToBytes(rt)),encodeFunctionData({abi:textResolverAbi,functionName:"text",args:[namehash(rt),nt]})],blockNumber:o,blockTag:tt},lt=getAction$1(et,readContract$1,"readContract"),dt=ot?await lt({...ct,args:[...ct.args,ot]}):await lt(ct);if(dt[0]==="0x")return null;const ht=decodeFunctionResult({abi:textResolverAbi,functionName:"text",data:dt[0]});return ht===""?null:ht}catch(ct){if(it)throw ct;if(isNullUniversalResolverError(ct,"resolve"))return null;throw ct}}async function getEnsAvatar$1(et,{blockNumber:o,blockTag:tt,assetGatewayUrls:rt,name:nt,gatewayUrls:ot,strict:it,universalResolverAddress:st}){const at=await getAction$1(et,getEnsText,"getEnsText")({blockNumber:o,blockTag:tt,key:"avatar",name:nt,universalResolverAddress:st,gatewayUrls:ot,strict:it});if(!at)return null;try{return await parseAvatarRecord(et,{record:at,gatewayUrls:rt})}catch{return null}}async function getEnsName$1(et,{address:o,blockNumber:tt,blockTag:rt,gatewayUrls:nt,strict:ot,universalResolverAddress:it}){let st=it;if(!st){if(!et.chain)throw new Error("client chain not configured. universalResolverAddress is required.");st=getChainContractAddress({blockNumber:tt,chain:et.chain,contract:"ensUniversalResolver"})}const at=`${o.toLowerCase().substring(2)}.addr.reverse`;try{const ct={address:st,abi:universalResolverReverseAbi,functionName:"reverse",args:[toHex(packetToBytes(at))],blockNumber:tt,blockTag:rt},lt=getAction$1(et,readContract$1,"readContract"),[dt,ht]=nt?await lt({...ct,args:[...ct.args,nt]}):await lt(ct);return o.toLowerCase()!==ht.toLowerCase()?null:dt}catch(ct){if(ot)throw ct;if(isNullUniversalResolverError(ct,"reverse"))return null;throw ct}}const promiseCache$1=new Map,responseCache=new Map;function getCache(et){const o=(nt,ot)=>({clear:()=>ot.delete(nt),get:()=>ot.get(nt),set:it=>ot.set(nt,it)}),tt=o(et,promiseCache$1),rt=o(et,responseCache);return{clear:()=>{tt.clear(),rt.clear()},promise:tt,response:rt}}async function withCache(et,{cacheKey:o,cacheTime:tt=Number.POSITIVE_INFINITY}){const rt=getCache(o),nt=rt.response.get();if(nt&&tt>0&&new Date().getTime()-nt.created.getTime()`blockNumber.${et}`;async function getBlockNumber$1(et,{cacheTime:o=et.cacheTime}={}){const tt=await withCache(()=>et.request({method:"eth_blockNumber"}),{cacheKey:cacheKey(et.uid),cacheTime:o});return BigInt(tt)}function formatLog(et,{args:o,eventName:tt}={}){return{...et,blockHash:et.blockHash?et.blockHash:null,blockNumber:et.blockNumber?BigInt(et.blockNumber):null,logIndex:et.logIndex?Number(et.logIndex):null,transactionHash:et.transactionHash?et.transactionHash:null,transactionIndex:et.transactionIndex?Number(et.transactionIndex):null,...tt?{args:o,eventName:tt}:{}}}const receiptStatuses={"0x0":"reverted","0x1":"success"};function formatTransactionReceipt(et){const o={...et,blockNumber:et.blockNumber?BigInt(et.blockNumber):null,contractAddress:et.contractAddress?et.contractAddress:null,cumulativeGasUsed:et.cumulativeGasUsed?BigInt(et.cumulativeGasUsed):null,effectiveGasPrice:et.effectiveGasPrice?BigInt(et.effectiveGasPrice):null,gasUsed:et.gasUsed?BigInt(et.gasUsed):null,logs:et.logs?et.logs.map(tt=>formatLog(tt)):null,to:et.to?et.to:null,transactionIndex:et.transactionIndex?hexToNumber$2(et.transactionIndex):null,status:et.status?receiptStatuses[et.status]:null,type:et.type?transactionType[et.type]||et.type:null};return et.blobGasPrice&&(o.blobGasPrice=BigInt(et.blobGasPrice)),et.blobGasUsed&&(o.blobGasUsed=BigInt(et.blobGasUsed)),o}const defineTransactionReceipt=defineFormatter("transactionReceipt",formatTransactionReceipt);async function multicall$1(et,o){var gt;const{allowFailure:tt=!0,batchSize:rt,blockNumber:nt,blockTag:ot,multicallAddress:it,stateOverride:st}=o,at=o.contracts,ct=rt??(typeof((gt=et.batch)==null?void 0:gt.multicall)=="object"&&et.batch.multicall.batchSize||1024);let lt=it;if(!lt){if(!et.chain)throw new Error("client chain not configured. multicallAddress is required.");lt=getChainContractAddress({blockNumber:nt,chain:et.chain,contract:"multicall3"})}const dt=[[]];let ht=0,mt=0;for(let yt=0;yt0&&mt>ct&&dt[ht].length>0&&(ht++,mt=(Ct.length-2)/2,dt[ht]=[]),dt[ht]=[...dt[ht],{allowFailure:!0,callData:Ct,target:xt}]}catch(Ct){const St=getContractError(Ct,{abi:bt,address:xt,args:vt,docsPath:"/docs/contract/multicall",functionName:Et});if(!tt)throw St;dt[ht]=[...dt[ht],{allowFailure:!0,callData:"0x",target:xt}]}}const ft=await Promise.allSettled(dt.map(yt=>getAction$1(et,readContract$1,"readContract")({abi:multicall3Abi,address:lt,args:[yt],blockNumber:nt,blockTag:ot,functionName:"aggregate3",stateOverride:st}))),pt=[];for(let yt=0;ytlistenersCache.get(et)||[],ot=()=>{const lt=nt();listenersCache.set(et,lt.filter(dt=>dt.id!==rt))},it=()=>{const lt=cleanupCache.get(et);nt().length===1&<&<(),ot()},st=nt();if(listenersCache.set(et,[...st,{id:rt,fns:o}]),st&&st.length>0)return it;const at={};for(const lt in o)at[lt]=(...dt)=>{var mt,ft;const ht=nt();if(ht.length!==0)for(const pt of ht)(ft=(mt=pt.fns)[lt])==null||ft.call(mt,...dt)};const ct=tt(at);return typeof ct=="function"&&cleanupCache.set(et,ct),it}async function wait$1(et){return new Promise(o=>setTimeout(o,et))}function poll(et,{emitOnBegin:o,initialWaitTime:tt,interval:rt}){let nt=!0;const ot=()=>nt=!1;return(async()=>{let st;o&&(st=await et({unpoll:ot}));const at=await(tt==null?void 0:tt(st))??rt;await wait$1(at);const ct=async()=>{nt&&(await et({unpoll:ot}),await wait$1(rt),ct())};ct()})(),ot}function watchBlockNumber$1(et,{emitOnBegin:o=!1,emitMissed:tt=!1,onBlockNumber:rt,onError:nt,poll:ot,pollingInterval:it=et.pollingInterval}){const st=typeof ot<"u"?ot:!(et.transport.type==="webSocket"||et.transport.type==="fallback"&&et.transport.transports[0].config.type==="webSocket");let at;return st?(()=>{const dt=stringify$2(["watchBlockNumber",et.uid,o,tt,it]);return observe(dt,{onBlockNumber:rt,onError:nt},ht=>poll(async()=>{var mt;try{const ft=await getAction$1(et,getBlockNumber$1,"getBlockNumber")({cacheTime:0});if(at){if(ft===at)return;if(ft-at>1&&tt)for(let pt=at+1n;ptat)&&(ht.onBlockNumber(ft,at),at=ft)}catch(ft){(mt=ht.onError)==null||mt.call(ht,ft)}},{emitOnBegin:o,interval:it}))})():(()=>{const dt=stringify$2(["watchBlockNumber",et.uid,o,tt]);return observe(dt,{onBlockNumber:rt,onError:nt},ht=>{let mt=!0,ft=()=>mt=!1;return(async()=>{try{const pt=(()=>{if(et.transport.type==="fallback"){const yt=et.transport.transports.find(bt=>bt.config.type==="webSocket");return yt?yt.value:et.transport}return et.transport})(),{unsubscribe:gt}=await pt.subscribe({params:["newHeads"],onData(yt){var xt;if(!mt)return;const bt=hexToBigInt((xt=yt.result)==null?void 0:xt.number);ht.onBlockNumber(bt,at),at=bt},onError(yt){var bt;(bt=ht.onError)==null||bt.call(ht,yt)}});ft=gt,mt||ft()}catch(pt){nt==null||nt(pt)}})(),()=>ft()})})()}const promiseCache=new LruMap(8192);function withDedupe(et,{enabled:o=!0,id:tt}){if(!o||!tt)return et();if(promiseCache.get(tt))return promiseCache.get(tt);const rt=et().finally(()=>promiseCache.delete(tt));return promiseCache.set(tt,rt),rt}function withRetry(et,{delay:o=100,retryCount:tt=2,shouldRetry:rt=()=>!0}={}){return new Promise((nt,ot)=>{const it=async({count:st=0}={})=>{const at=async({error:ct})=>{const lt=typeof o=="function"?o({count:st,error:ct}):o;lt&&await wait$1(lt),it({count:st+1})};try{const ct=await et();nt(ct)}catch(ct){if(st{const{dedupe:nt=!1,retryDelay:ot=150,retryCount:it=3,uid:st}={...o,...rt},at=nt?keccak256$1(stringToHex(`${st}.${stringify$2(tt)}`)):void 0;return withDedupe(()=>withRetry(async()=>{try{return await et(tt)}catch(ct){const lt=ct;switch(lt.code){case ParseRpcError.code:throw new ParseRpcError(lt);case InvalidRequestRpcError.code:throw new InvalidRequestRpcError(lt);case MethodNotFoundRpcError.code:throw new MethodNotFoundRpcError(lt,{method:tt.method});case InvalidParamsRpcError.code:throw new InvalidParamsRpcError(lt);case InternalRpcError.code:throw new InternalRpcError(lt);case InvalidInputRpcError.code:throw new InvalidInputRpcError(lt);case ResourceNotFoundRpcError.code:throw new ResourceNotFoundRpcError(lt);case ResourceUnavailableRpcError.code:throw new ResourceUnavailableRpcError(lt);case TransactionRejectedRpcError.code:throw new TransactionRejectedRpcError(lt);case MethodNotSupportedRpcError.code:throw new MethodNotSupportedRpcError(lt,{method:tt.method});case LimitExceededRpcError.code:throw new LimitExceededRpcError(lt);case JsonRpcVersionUnsupportedError.code:throw new JsonRpcVersionUnsupportedError(lt);case UserRejectedRequestError.code:throw new UserRejectedRequestError(lt);case UnauthorizedProviderError.code:throw new UnauthorizedProviderError(lt);case UnsupportedProviderMethodError.code:throw new UnsupportedProviderMethodError(lt);case ProviderDisconnectedError.code:throw new ProviderDisconnectedError(lt);case ChainDisconnectedError.code:throw new ChainDisconnectedError(lt);case SwitchChainError.code:throw new SwitchChainError(lt);case 5e3:throw new UserRejectedRequestError(lt);default:throw ct instanceof BaseError$3?ct:new UnknownRpcError(lt)}}},{delay:({count:ct,error:lt})=>{var dt;if(lt&< instanceof HttpRequestError){const ht=(dt=lt==null?void 0:lt.headers)==null?void 0:dt.get("Retry-After");if(ht!=null&&ht.match(/\d/))return Number.parseInt(ht)*1e3}return~~(1<shouldRetry(ct)}),{enabled:nt,id:at})}}function shouldRetry(et){return"code"in et&&typeof et.code=="number"?et.code===-1||et.code===LimitExceededRpcError.code||et.code===InternalRpcError.code:et instanceof HttpRequestError&&et.status?et.status===403||et.status===408||et.status===413||et.status===429||et.status===500||et.status===502||et.status===503||et.status===504:!0}function defineChain(et){return{formatters:void 0,fees:void 0,serializers:void 0,...et}}function withTimeout(et,{errorInstance:o=new Error("timed out"),timeout:tt,signal:rt}){return new Promise((nt,ot)=>{(async()=>{let it;try{const st=new AbortController;tt>0&&(it=setTimeout(()=>{rt?st.abort():ot(o)},tt)),nt(await et({signal:(st==null?void 0:st.signal)||null}))}catch(st){(st==null?void 0:st.name)==="AbortError"&&ot(o),ot(st)}finally{clearTimeout(it)}})()})}function createIdStore(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const idCache=createIdStore();function getHttpRpcClient(et,o={}){return{async request(tt){var dt;const{body:rt,onRequest:nt=o.onRequest,onResponse:ot=o.onResponse,timeout:it=o.timeout??1e4}=tt,st={...o.fetchOptions??{},...tt.fetchOptions??{}},{headers:at,method:ct,signal:lt}=st;try{const ht=await withTimeout(async({signal:ft})=>{const pt={...st,body:Array.isArray(rt)?stringify$2(rt.map(xt=>({jsonrpc:"2.0",id:xt.id??idCache.take(),...xt}))):stringify$2({jsonrpc:"2.0",id:rt.id??idCache.take(),...rt}),headers:{"Content-Type":"application/json",...at},method:ct||"POST",signal:lt||(it>0?ft:null)},gt=new Request(et,pt),yt=await(nt==null?void 0:nt(gt,pt))??{...pt,url:et};return await fetch(yt.url??et,yt)},{errorInstance:new TimeoutError$4({body:rt,url:et}),timeout:it,signal:!0});ot&&await ot(ht);let mt;if((dt=ht.headers.get("Content-Type"))!=null&&dt.startsWith("application/json"))mt=await ht.json();else{mt=await ht.text();try{mt=JSON.parse(mt||"{}")}catch(ft){if(ht.ok)throw ft;mt={error:mt}}}if(!ht.ok)throw new HttpRequestError({body:rt,details:stringify$2(mt.error)||ht.statusText,headers:ht.headers,status:ht.status,url:et});return mt}catch(ht){throw ht instanceof HttpRequestError||ht instanceof TimeoutError$4?ht:new HttpRequestError({body:rt,cause:ht,url:et})}}}}function assertTransactionEIP7702(et){const{authorizationList:o}=et;if(o)for(const tt of o){const{contractAddress:rt,chainId:nt}=tt;if(!isAddress(rt))throw new InvalidAddressError({address:rt});if(nt<=0)throw new InvalidChainIdError({chainId:nt})}assertTransactionEIP1559(et)}function assertTransactionEIP4844(et){const{blobVersionedHashes:o}=et;if(o){if(o.length===0)throw new EmptyBlobError;for(const tt of o){const rt=size$2(tt),nt=hexToNumber$2(slice(tt,0,1));if(rt!==32)throw new InvalidVersionedHashSizeError({hash:tt,size:rt});if(nt!==versionedHashVersionKzg)throw new InvalidVersionedHashVersionError({hash:tt,version:nt})}}assertTransactionEIP1559(et)}function assertTransactionEIP1559(et){const{chainId:o,maxPriorityFeePerGas:tt,maxFeePerGas:rt,to:nt}=et;if(o<=0)throw new InvalidChainIdError({chainId:o});if(nt&&!isAddress(nt))throw new InvalidAddressError({address:nt});if(rt&&rt>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:rt});if(tt&&rt&&tt>rt)throw new TipAboveFeeCapError({maxFeePerGas:rt,maxPriorityFeePerGas:tt})}function assertTransactionEIP2930(et){const{chainId:o,maxPriorityFeePerGas:tt,gasPrice:rt,maxFeePerGas:nt,to:ot}=et;if(o<=0)throw new InvalidChainIdError({chainId:o});if(ot&&!isAddress(ot))throw new InvalidAddressError({address:ot});if(tt||nt)throw new BaseError$3("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(rt&&rt>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:rt})}function assertTransactionLegacy(et){const{chainId:o,maxPriorityFeePerGas:tt,gasPrice:rt,maxFeePerGas:nt,to:ot}=et;if(ot&&!isAddress(ot))throw new InvalidAddressError({address:ot});if(typeof o<"u"&&o<=0)throw new InvalidChainIdError({chainId:o});if(tt||nt)throw new BaseError$3("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(rt&&rt>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:rt})}function serializeAuthorizationList(et){if(!et||et.length===0)return[];const o=[];for(const tt of et){const{contractAddress:rt,chainId:nt,nonce:ot,...it}=tt;o.push([toHex(nt),rt,ot?toHex(ot):"0x",...toYParitySignatureArray({},it)])}return o}function serializeAccessList(et){if(!et||et.length===0)return[];const o=[];for(let tt=0;tt"u"||typeof mt>"u")){const xt=typeof et.blobs[0]=="string"?et.blobs:et.blobs.map(Ct=>bytesToHex$3(Ct)),vt=et.kzg,Et=blobsToCommitments({blobs:xt,kzg:vt});if(typeof ht>"u"&&(ht=commitmentsToVersionedHashes({commitments:Et})),typeof mt>"u"){const Ct=blobsToProofs({blobs:xt,commitments:Et,kzg:vt});mt=toBlobSidecars({blobs:xt,commitments:Et,proofs:Ct})}}const ft=serializeAccessList(lt),pt=[toHex(tt),nt?toHex(nt):"0x",ct?toHex(ct):"0x",at?toHex(at):"0x",rt?toHex(rt):"0x",ot??"0x",it?toHex(it):"0x",dt??"0x",ft,st?toHex(st):"0x",ht??[],...toYParitySignatureArray(et,o)],gt=[],yt=[],bt=[];if(mt)for(let xt=0;xt{if(o.v>=35n)return(o.v-35n)/2n>0?o.v:27n+(o.v===35n?0n:1n);if(tt>0)return BigInt(tt*2)+BigInt(35n+o.v-27n);const mt=27n+(o.v===27n?0n:1n);if(o.v!==mt)throw new InvalidLegacyVError({v:o.v});return mt})(),dt=trim$1(o.r),ht=trim$1(o.s);ct=[...ct,toHex(lt),dt==="0x00"?"0x":dt,ht==="0x00"?"0x":ht]}else tt>0&&(ct=[...ct,toHex(tt),"0x","0x"]);return toRlp(ct)}function toYParitySignatureArray(et,o){const tt=o??et,{v:rt,yParity:nt}=tt;if(typeof tt.r>"u")return[];if(typeof tt.s>"u")return[];if(typeof rt>"u"&&typeof nt>"u")return[];const ot=trim$1(tt.r),it=trim$1(tt.s);return[typeof nt=="number"?nt?toHex(1):"0x":rt===0n?"0x":rt===1n?toHex(1):rt===27n?"0x":toHex(1),ot==="0x00"?"0x":ot,it==="0x00"?"0x":it]}async function signMessage$1(et,{account:o=et.account,message:tt}){if(!o)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signMessage"});const rt=parseAccount(o);if(rt.signMessage)return rt.signMessage({message:tt});const nt=typeof tt=="string"?stringToHex(tt):tt.raw instanceof Uint8Array?toHex(tt.raw):tt.raw;return et.request({method:"personal_sign",params:[nt,rt.address]},{retryCount:0})}class HMAC extends Hash{constructor(o,tt){super(),this.finished=!1,this.destroyed=!1,hash$1(o);const rt=toBytes$2(tt);if(this.iHash=o.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;const nt=this.blockLen,ot=new Uint8Array(nt);ot.set(rt.length>nt?o.create().update(rt).digest():rt);for(let it=0;itnew HMAC(et,o).update(tt).digest();hmac.create=(et,o)=>new HMAC(et,o);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$6=BigInt(0),_1n$8=BigInt(1),_2n$5=BigInt(2);function isBytes$2(et){return et instanceof Uint8Array||et!=null&&typeof et=="object"&&et.constructor.name==="Uint8Array"}function abytes(et){if(!isBytes$2(et))throw new Error("Uint8Array expected")}function abool(et,o){if(typeof o!="boolean")throw new Error(`${et} must be valid boolean, got "${o}".`)}const hexes$1=Array.from({length:256},(et,o)=>o.toString(16).padStart(2,"0"));function bytesToHex$2(et){abytes(et);let o="";for(let tt=0;tt=asciis._0&&et<=asciis._9)return et-asciis._0;if(et>=asciis._A&&et<=asciis._F)return et-(asciis._A-10);if(et>=asciis._a&&et<=asciis._f)return et-(asciis._a-10)}function hexToBytes$2(et){if(typeof et!="string")throw new Error("hex string expected, got "+typeof et);const o=et.length,tt=o/2;if(o%2)throw new Error("padded hex string expected, got unpadded hex of length "+o);const rt=new Uint8Array(tt);for(let nt=0,ot=0;nttypeof et=="bigint"&&_0n$6<=et;function inRange(et,o,tt){return isPosBig(et)&&isPosBig(o)&&isPosBig(tt)&&o<=et&&et_0n$6;et>>=_1n$8,o+=1);return o}function bitGet(et,o){return et>>BigInt(o)&_1n$8}function bitSet(et,o,tt){return et|(tt?_1n$8:_0n$6)<(_2n$5<new Uint8Array(et),u8fr=et=>Uint8Array.from(et);function createHmacDrbg(et,o,tt){if(typeof et!="number"||et<2)throw new Error("hashLen must be a number");if(typeof o!="number"||o<2)throw new Error("qByteLen must be a number");if(typeof tt!="function")throw new Error("hmacFn must be a function");let rt=u8n(et),nt=u8n(et),ot=0;const it=()=>{rt.fill(1),nt.fill(0),ot=0},st=(...dt)=>tt(nt,rt,...dt),at=(dt=u8n())=>{nt=st(u8fr([0]),dt),rt=st(),dt.length!==0&&(nt=st(u8fr([1]),dt),rt=st())},ct=()=>{if(ot++>=1e3)throw new Error("drbg: tried 1000 values");let dt=0;const ht=[];for(;dt{it(),at(dt);let mt;for(;!(mt=ht(ct()));)at();return it(),mt}}const validatorFns={bigint:et=>typeof et=="bigint",function:et=>typeof et=="function",boolean:et=>typeof et=="boolean",string:et=>typeof et=="string",stringOrUint8Array:et=>typeof et=="string"||isBytes$2(et),isSafeInteger:et=>Number.isSafeInteger(et),array:et=>Array.isArray(et),field:(et,o)=>o.Fp.isValid(et),hash:et=>typeof et=="function"&&Number.isSafeInteger(et.outputLen)};function validateObject(et,o,tt={}){const rt=(nt,ot,it)=>{const st=validatorFns[ot];if(typeof st!="function")throw new Error(`Invalid validator "${ot}", expected function`);const at=et[nt];if(!(it&&at===void 0)&&!st(at,et))throw new Error(`Invalid param ${String(nt)}=${at} (${typeof at}), expected ${ot}`)};for(const[nt,ot]of Object.entries(o))rt(nt,ot,!1);for(const[nt,ot]of Object.entries(tt))rt(nt,ot,!0);return et}const notImplemented=()=>{throw new Error("not implemented")};function memoized(et){const o=new WeakMap;return(tt,...rt)=>{const nt=o.get(tt);if(nt!==void 0)return nt;const ot=et(tt,...rt);return o.set(tt,ot),ot}}const ut=Object.freeze(Object.defineProperty({__proto__:null,aInRange,abool,abytes,bitGet,bitLen,bitMask,bitSet,bytesToHex:bytesToHex$2,bytesToNumberBE,bytesToNumberLE,concatBytes:concatBytes$1,createHmacDrbg,ensureBytes:ensureBytes$1,equalBytes:equalBytes$1,hexToBytes:hexToBytes$2,hexToNumber:hexToNumber$1,inRange,isBytes:isBytes$2,memoized,notImplemented,numberToBytesBE,numberToBytesLE,numberToHexUnpadded:numberToHexUnpadded$1,numberToVarBytesBE,utf8ToBytes:utf8ToBytes$2,validateObject},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$5=BigInt(0),_1n$7=BigInt(1),_2n$4=BigInt(2),_3n$3=BigInt(3),_4n=BigInt(4),_5n$1=BigInt(5),_8n$3=BigInt(8);BigInt(9);BigInt(16);function mod$1(et,o){const tt=et%o;return tt>=_0n$5?tt:o+tt}function pow(et,o,tt){if(tt<=_0n$5||o<_0n$5)throw new Error("Expected power/modulo > 0");if(tt===_1n$7)return _0n$5;let rt=_1n$7;for(;o>_0n$5;)o&_1n$7&&(rt=rt*et%tt),et=et*et%tt,o>>=_1n$7;return rt}function pow2$1(et,o,tt){let rt=et;for(;o-- >_0n$5;)rt*=rt,rt%=tt;return rt}function invert$1(et,o){if(et===_0n$5||o<=_0n$5)throw new Error(`invert: expected positive integers, got n=${et} mod=${o}`);let tt=mod$1(et,o),rt=o,nt=_0n$5,ot=_1n$7;for(;tt!==_0n$5;){const st=rt/tt,at=rt%tt,ct=nt-ot*st;rt=tt,tt=at,nt=ot,ot=ct}if(rt!==_1n$7)throw new Error("invert: does not exist");return mod$1(nt,o)}function tonelliShanks(et){const o=(et-_1n$7)/_2n$4;let tt,rt,nt;for(tt=et-_1n$7,rt=0;tt%_2n$4===_0n$5;tt/=_2n$4,rt++);for(nt=_2n$4;nt(mod$1(et,o)&_1n$7)===_1n$7,FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(et){const o={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},tt=FIELD_FIELDS.reduce((rt,nt)=>(rt[nt]="function",rt),o);return validateObject(et,tt)}function FpPow(et,o,tt){if(tt<_0n$5)throw new Error("Expected power > 0");if(tt===_0n$5)return et.ONE;if(tt===_1n$7)return o;let rt=et.ONE,nt=o;for(;tt>_0n$5;)tt&_1n$7&&(rt=et.mul(rt,nt)),nt=et.sqr(nt),tt>>=_1n$7;return rt}function FpInvertBatch(et,o){const tt=new Array(o.length),rt=o.reduce((ot,it,st)=>et.is0(it)?ot:(tt[st]=ot,et.mul(ot,it)),et.ONE),nt=et.inv(rt);return o.reduceRight((ot,it,st)=>et.is0(it)?ot:(tt[st]=et.mul(ot,tt[st]),et.mul(ot,it)),nt),tt}function nLength(et,o){const tt=o!==void 0?o:et.toString(2).length,rt=Math.ceil(tt/8);return{nBitLength:tt,nByteLength:rt}}function Field$1(et,o,tt=!1,rt={}){if(et<=_0n$5)throw new Error(`Expected Field ORDER > 0, got ${et}`);const{nBitLength:nt,nByteLength:ot}=nLength(et,o);if(ot>2048)throw new Error("Field lengths over 2048 bytes are not supported");const it=FpSqrt(et),st=Object.freeze({ORDER:et,BITS:nt,BYTES:ot,MASK:bitMask(nt),ZERO:_0n$5,ONE:_1n$7,create:at=>mod$1(at,et),isValid:at=>{if(typeof at!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof at}`);return _0n$5<=at&&atat===_0n$5,isOdd:at=>(at&_1n$7)===_1n$7,neg:at=>mod$1(-at,et),eql:(at,ct)=>at===ct,sqr:at=>mod$1(at*at,et),add:(at,ct)=>mod$1(at+ct,et),sub:(at,ct)=>mod$1(at-ct,et),mul:(at,ct)=>mod$1(at*ct,et),pow:(at,ct)=>FpPow(st,at,ct),div:(at,ct)=>mod$1(at*invert$1(ct,et),et),sqrN:at=>at*at,addN:(at,ct)=>at+ct,subN:(at,ct)=>at-ct,mulN:(at,ct)=>at*ct,inv:at=>invert$1(at,et),sqrt:rt.sqrt||(at=>it(st,at)),invertBatch:at=>FpInvertBatch(st,at),cmov:(at,ct,lt)=>lt?ct:at,toBytes:at=>tt?numberToBytesLE(at,ot):numberToBytesBE(at,ot),fromBytes:at=>{if(at.length!==ot)throw new Error(`Fp.fromBytes: expected ${ot}, got ${at.length}`);return tt?bytesToNumberLE(at):bytesToNumberBE(at)}});return Object.freeze(st)}function getFieldBytesLength(et){if(typeof et!="bigint")throw new Error("field order must be bigint");const o=et.toString(2).length;return Math.ceil(o/8)}function getMinHashLength(et){const o=getFieldBytesLength(et);return o+Math.ceil(o/2)}function mapHashToField(et,o,tt=!1){const rt=et.length,nt=getFieldBytesLength(o),ot=getMinHashLength(o);if(rt<16||rt1024)throw new Error(`expected ${ot}-1024 bytes of input, got ${rt}`);const it=tt?bytesToNumberBE(et):bytesToNumberLE(et),st=mod$1(it,o-_1n$7)+_1n$7;return tt?numberToBytesLE(st,nt):numberToBytesBE(st,nt)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$6=BigInt(1),pointPrecomputes$1=new WeakMap,pointWindowSizes=new WeakMap;function wNAF(et,o){const tt=(ot,it)=>{const st=it.negate();return ot?st:it},rt=ot=>{if(!Number.isSafeInteger(ot)||ot<=0||ot>o)throw new Error(`Wrong window size=${ot}, should be [1..${o}]`)},nt=ot=>{rt(ot);const it=Math.ceil(o/ot)+1,st=2**(ot-1);return{windows:it,windowSize:st}};return{constTimeNegate:tt,unsafeLadder(ot,it){let st=et.ZERO,at=ot;for(;it>_0n$4;)it&_1n$6&&(st=st.add(at)),at=at.double(),it>>=_1n$6;return st},precomputeWindow(ot,it){const{windows:st,windowSize:at}=nt(it),ct=[];let lt=ot,dt=lt;for(let ht=0;ht>=ft,yt>ct&&(yt-=mt,st+=_1n$6);const bt=gt,xt=gt+Math.abs(yt)-1,vt=pt%2!==0,Et=yt<0;yt===0?dt=dt.add(tt(vt,it[bt])):lt=lt.add(tt(Et,it[xt]))}return{p:lt,f:dt}},wNAFCached(ot,it,st){const at=pointWindowSizes.get(ot)||1;let ct=pointPrecomputes$1.get(ot);return ct||(ct=this.precomputeWindow(ot,at),at!==1&&pointPrecomputes$1.set(ot,st(ct))),this.wNAF(at,ct,it)},setWindowSize(ot,it){rt(it),pointWindowSizes.set(ot,it),pointPrecomputes$1.delete(ot)}}}function pippenger(et,o,tt,rt){if(!Array.isArray(tt)||!Array.isArray(rt)||rt.length!==tt.length)throw new Error("arrays of points and scalars must have equal length");rt.forEach((lt,dt)=>{if(!o.isValid(lt))throw new Error(`wrong scalar at index ${dt}`)}),tt.forEach((lt,dt)=>{if(!(lt instanceof et))throw new Error(`wrong point at index ${dt}`)});const nt=bitLen(BigInt(tt.length)),ot=nt>12?nt-3:nt>4?nt-2:nt?2:1,it=(1<=0;lt-=ot){st.fill(et.ZERO);for(let ht=0;ht>BigInt(lt)&BigInt(it));st[ft]=st[ft].add(tt[ht])}let dt=et.ZERO;for(let ht=st.length-1,mt=et.ZERO;ht>0;ht--)mt=mt.add(st[ht]),dt=dt.add(mt);if(ct=ct.add(dt),lt!==0)for(let ht=0;ht{const{Err:tt}=DER;if(et<0||et>256)throw new tt("tlv.encode: wrong tag");if(o.length&1)throw new tt("tlv.encode: unpadded data");const rt=o.length/2,nt=numberToHexUnpadded$1(rt);if(nt.length/2&128)throw new tt("tlv.encode: long form length too big");const ot=rt>127?numberToHexUnpadded$1(nt.length/2|128):"";return`${numberToHexUnpadded$1(et)}${ot}${nt}${o}`},decode(et,o){const{Err:tt}=DER;let rt=0;if(et<0||et>256)throw new tt("tlv.encode: wrong tag");if(o.length<2||o[rt++]!==et)throw new tt("tlv.decode: wrong tlv");const nt=o[rt++],ot=!!(nt&128);let it=0;if(!ot)it=nt;else{const at=nt&127;if(!at)throw new tt("tlv.decode(long): indefinite length not supported");if(at>4)throw new tt("tlv.decode(long): byte length is too big");const ct=o.subarray(rt,rt+at);if(ct.length!==at)throw new tt("tlv.decode: length bytes not complete");if(ct[0]===0)throw new tt("tlv.decode(long): zero leftmost byte");for(const lt of ct)it=it<<8|lt;if(rt+=at,it<128)throw new tt("tlv.decode(long): not minimal encoding")}const st=o.subarray(rt,rt+it);if(st.length!==it)throw new tt("tlv.decode: wrong value length");return{v:st,l:o.subarray(rt+it)}}},_int:{encode(et){const{Err:o}=DER;if(et<_0n$3)throw new o("integer: negative integers are not allowed");let tt=numberToHexUnpadded$1(et);if(Number.parseInt(tt[0],16)&8&&(tt="00"+tt),tt.length&1)throw new o("unexpected assertion");return tt},decode(et){const{Err:o}=DER;if(et[0]&128)throw new o("Invalid signature integer: negative");if(et[0]===0&&!(et[1]&128))throw new o("Invalid signature integer: unnecessary leading zero");return b2n(et)}},toSig(et){const{Err:o,_int:tt,_tlv:rt}=DER,nt=typeof et=="string"?h2b(et):et;abytes(nt);const{v:ot,l:it}=rt.decode(48,nt);if(it.length)throw new o("Invalid signature: left bytes after parsing");const{v:st,l:at}=rt.decode(2,ot),{v:ct,l:lt}=rt.decode(2,at);if(lt.length)throw new o("Invalid signature: left bytes after parsing");return{r:tt.decode(st),s:tt.decode(ct)}},hexFromSig(et){const{_tlv:o,_int:tt}=DER,rt=`${o.encode(2,tt.encode(et.r))}${o.encode(2,tt.encode(et.s))}`;return o.encode(48,rt)}},_0n$3=BigInt(0),_1n$5=BigInt(1);BigInt(2);const _3n$2=BigInt(3);BigInt(4);function weierstrassPoints(et){const o=validatePointOpts(et),{Fp:tt}=o,rt=Field$1(o.n,o.nBitLength),nt=o.toBytes||((pt,gt,yt)=>{const bt=gt.toAffine();return concatBytes$1(Uint8Array.from([4]),tt.toBytes(bt.x),tt.toBytes(bt.y))}),ot=o.fromBytes||(pt=>{const gt=pt.subarray(1),yt=tt.fromBytes(gt.subarray(0,tt.BYTES)),bt=tt.fromBytes(gt.subarray(tt.BYTES,2*tt.BYTES));return{x:yt,y:bt}});function it(pt){const{a:gt,b:yt}=o,bt=tt.sqr(pt),xt=tt.mul(bt,pt);return tt.add(tt.add(xt,tt.mul(pt,gt)),yt)}if(!tt.eql(tt.sqr(o.Gy),it(o.Gx)))throw new Error("bad generator point: equation left != right");function st(pt){return inRange(pt,_1n$5,o.n)}function at(pt){const{allowedPrivateKeyLengths:gt,nByteLength:yt,wrapPrivateKey:bt,n:xt}=o;if(gt&&typeof pt!="bigint"){if(isBytes$2(pt)&&(pt=bytesToHex$2(pt)),typeof pt!="string"||!gt.includes(pt.length))throw new Error("Invalid key");pt=pt.padStart(yt*2,"0")}let vt;try{vt=typeof pt=="bigint"?pt:bytesToNumberBE(ensureBytes$1("private key",pt,yt))}catch{throw new Error(`private key must be ${yt} bytes, hex or bigint, not ${typeof pt}`)}return bt&&(vt=mod$1(vt,xt)),aInRange("private key",vt,_1n$5,xt),vt}function ct(pt){if(!(pt instanceof ht))throw new Error("ProjectivePoint expected")}const lt=memoized((pt,gt)=>{const{px:yt,py:bt,pz:xt}=pt;if(tt.eql(xt,tt.ONE))return{x:yt,y:bt};const vt=pt.is0();gt==null&&(gt=vt?tt.ONE:tt.inv(xt));const Et=tt.mul(yt,gt),Ct=tt.mul(bt,gt),St=tt.mul(xt,gt);if(vt)return{x:tt.ZERO,y:tt.ZERO};if(!tt.eql(St,tt.ONE))throw new Error("invZ was invalid");return{x:Et,y:Ct}}),dt=memoized(pt=>{if(pt.is0()){if(o.allowInfinityPoint&&!tt.is0(pt.py))return;throw new Error("bad point: ZERO")}const{x:gt,y:yt}=pt.toAffine();if(!tt.isValid(gt)||!tt.isValid(yt))throw new Error("bad point: x or y not FE");const bt=tt.sqr(yt),xt=it(gt);if(!tt.eql(bt,xt))throw new Error("bad point: equation left != right");if(!pt.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class ht{constructor(gt,yt,bt){if(this.px=gt,this.py=yt,this.pz=bt,gt==null||!tt.isValid(gt))throw new Error("x required");if(yt==null||!tt.isValid(yt))throw new Error("y required");if(bt==null||!tt.isValid(bt))throw new Error("z required");Object.freeze(this)}static fromAffine(gt){const{x:yt,y:bt}=gt||{};if(!gt||!tt.isValid(yt)||!tt.isValid(bt))throw new Error("invalid affine point");if(gt instanceof ht)throw new Error("projective point not allowed");const xt=vt=>tt.eql(vt,tt.ZERO);return xt(yt)&&xt(bt)?ht.ZERO:new ht(yt,bt,tt.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(gt){const yt=tt.invertBatch(gt.map(bt=>bt.pz));return gt.map((bt,xt)=>bt.toAffine(yt[xt])).map(ht.fromAffine)}static fromHex(gt){const yt=ht.fromAffine(ot(ensureBytes$1("pointHex",gt)));return yt.assertValidity(),yt}static fromPrivateKey(gt){return ht.BASE.multiply(at(gt))}static msm(gt,yt){return pippenger(ht,rt,gt,yt)}_setWindowSize(gt){ft.setWindowSize(this,gt)}assertValidity(){dt(this)}hasEvenY(){const{y:gt}=this.toAffine();if(tt.isOdd)return!tt.isOdd(gt);throw new Error("Field doesn't support isOdd")}equals(gt){ct(gt);const{px:yt,py:bt,pz:xt}=this,{px:vt,py:Et,pz:Ct}=gt,St=tt.eql(tt.mul(yt,Ct),tt.mul(vt,xt)),At=tt.eql(tt.mul(bt,Ct),tt.mul(Et,xt));return St&&At}negate(){return new ht(this.px,tt.neg(this.py),this.pz)}double(){const{a:gt,b:yt}=o,bt=tt.mul(yt,_3n$2),{px:xt,py:vt,pz:Et}=this;let Ct=tt.ZERO,St=tt.ZERO,At=tt.ZERO,kt=tt.mul(xt,xt),It=tt.mul(vt,vt),Ot=tt.mul(Et,Et),Nt=tt.mul(xt,vt);return Nt=tt.add(Nt,Nt),At=tt.mul(xt,Et),At=tt.add(At,At),Ct=tt.mul(gt,At),St=tt.mul(bt,Ot),St=tt.add(Ct,St),Ct=tt.sub(It,St),St=tt.add(It,St),St=tt.mul(Ct,St),Ct=tt.mul(Nt,Ct),At=tt.mul(bt,At),Ot=tt.mul(gt,Ot),Nt=tt.sub(kt,Ot),Nt=tt.mul(gt,Nt),Nt=tt.add(Nt,At),At=tt.add(kt,kt),kt=tt.add(At,kt),kt=tt.add(kt,Ot),kt=tt.mul(kt,Nt),St=tt.add(St,kt),Ot=tt.mul(vt,Et),Ot=tt.add(Ot,Ot),kt=tt.mul(Ot,Nt),Ct=tt.sub(Ct,kt),At=tt.mul(Ot,It),At=tt.add(At,At),At=tt.add(At,At),new ht(Ct,St,At)}add(gt){ct(gt);const{px:yt,py:bt,pz:xt}=this,{px:vt,py:Et,pz:Ct}=gt;let St=tt.ZERO,At=tt.ZERO,kt=tt.ZERO;const It=o.a,Ot=tt.mul(o.b,_3n$2);let Nt=tt.mul(yt,vt),Yt=tt.mul(bt,Et),Ft=tt.mul(xt,Ct),Ht=tt.add(yt,bt),Qt=tt.add(vt,Et);Ht=tt.mul(Ht,Qt),Qt=tt.add(Nt,Yt),Ht=tt.sub(Ht,Qt),Qt=tt.add(yt,xt);let Vt=tt.add(vt,Ct);return Qt=tt.mul(Qt,Vt),Vt=tt.add(Nt,Ft),Qt=tt.sub(Qt,Vt),Vt=tt.add(bt,xt),St=tt.add(Et,Ct),Vt=tt.mul(Vt,St),St=tt.add(Yt,Ft),Vt=tt.sub(Vt,St),kt=tt.mul(It,Qt),St=tt.mul(Ot,Ft),kt=tt.add(St,kt),St=tt.sub(Yt,kt),kt=tt.add(Yt,kt),At=tt.mul(St,kt),Yt=tt.add(Nt,Nt),Yt=tt.add(Yt,Nt),Ft=tt.mul(It,Ft),Qt=tt.mul(Ot,Qt),Yt=tt.add(Yt,Ft),Ft=tt.sub(Nt,Ft),Ft=tt.mul(It,Ft),Qt=tt.add(Qt,Ft),Nt=tt.mul(Yt,Qt),At=tt.add(At,Nt),Nt=tt.mul(Vt,Qt),St=tt.mul(Ht,St),St=tt.sub(St,Nt),Nt=tt.mul(Ht,Yt),kt=tt.mul(Vt,kt),kt=tt.add(kt,Nt),new ht(St,At,kt)}subtract(gt){return this.add(gt.negate())}is0(){return this.equals(ht.ZERO)}wNAF(gt){return ft.wNAFCached(this,gt,ht.normalizeZ)}multiplyUnsafe(gt){aInRange("scalar",gt,_0n$3,o.n);const yt=ht.ZERO;if(gt===_0n$3)return yt;if(gt===_1n$5)return this;const{endo:bt}=o;if(!bt)return ft.unsafeLadder(this,gt);let{k1neg:xt,k1:vt,k2neg:Et,k2:Ct}=bt.splitScalar(gt),St=yt,At=yt,kt=this;for(;vt>_0n$3||Ct>_0n$3;)vt&_1n$5&&(St=St.add(kt)),Ct&_1n$5&&(At=At.add(kt)),kt=kt.double(),vt>>=_1n$5,Ct>>=_1n$5;return xt&&(St=St.negate()),Et&&(At=At.negate()),At=new ht(tt.mul(At.px,bt.beta),At.py,At.pz),St.add(At)}multiply(gt){const{endo:yt,n:bt}=o;aInRange("scalar",gt,_1n$5,bt);let xt,vt;if(yt){const{k1neg:Et,k1:Ct,k2neg:St,k2:At}=yt.splitScalar(gt);let{p:kt,f:It}=this.wNAF(Ct),{p:Ot,f:Nt}=this.wNAF(At);kt=ft.constTimeNegate(Et,kt),Ot=ft.constTimeNegate(St,Ot),Ot=new ht(tt.mul(Ot.px,yt.beta),Ot.py,Ot.pz),xt=kt.add(Ot),vt=It.add(Nt)}else{const{p:Et,f:Ct}=this.wNAF(gt);xt=Et,vt=Ct}return ht.normalizeZ([xt,vt])[0]}multiplyAndAddUnsafe(gt,yt,bt){const xt=ht.BASE,vt=(Ct,St)=>St===_0n$3||St===_1n$5||!Ct.equals(xt)?Ct.multiplyUnsafe(St):Ct.multiply(St),Et=vt(this,yt).add(vt(gt,bt));return Et.is0()?void 0:Et}toAffine(gt){return lt(this,gt)}isTorsionFree(){const{h:gt,isTorsionFree:yt}=o;if(gt===_1n$5)return!0;if(yt)return yt(ht,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:gt,clearCofactor:yt}=o;return gt===_1n$5?this:yt?yt(ht,this):this.multiplyUnsafe(o.h)}toRawBytes(gt=!0){return abool("isCompressed",gt),this.assertValidity(),nt(ht,this,gt)}toHex(gt=!0){return abool("isCompressed",gt),bytesToHex$2(this.toRawBytes(gt))}}ht.BASE=new ht(o.Gx,o.Gy,tt.ONE),ht.ZERO=new ht(tt.ZERO,tt.ONE,tt.ZERO);const mt=o.nBitLength,ft=wNAF(ht,o.endo?Math.ceil(mt/2):mt);return{CURVE:o,ProjectivePoint:ht,normPrivateKeyToScalar:at,weierstrassEquation:it,isWithinCurveOrder:st}}function validateOpts$2(et){const o=validateBasic(et);return validateObject(o,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...o})}function weierstrass$1(et){const o=validateOpts$2(et),{Fp:tt,n:rt}=o,nt=tt.BYTES+1,ot=2*tt.BYTES+1;function it(Ft){return mod$1(Ft,rt)}function st(Ft){return invert$1(Ft,rt)}const{ProjectivePoint:at,normPrivateKeyToScalar:ct,weierstrassEquation:lt,isWithinCurveOrder:dt}=weierstrassPoints({...o,toBytes(Ft,Ht,Qt){const Vt=Ht.toAffine(),Bt=tt.toBytes(Vt.x),Wt=concatBytes$1;return abool("isCompressed",Qt),Qt?Wt(Uint8Array.from([Ht.hasEvenY()?2:3]),Bt):Wt(Uint8Array.from([4]),Bt,tt.toBytes(Vt.y))},fromBytes(Ft){const Ht=Ft.length,Qt=Ft[0],Vt=Ft.subarray(1);if(Ht===nt&&(Qt===2||Qt===3)){const Bt=bytesToNumberBE(Vt);if(!inRange(Bt,_1n$5,tt.ORDER))throw new Error("Point is not on curve");const Wt=lt(Bt);let jt;try{jt=tt.sqrt(Wt)}catch(Pt){const Gt=Pt instanceof Error?": "+Pt.message:"";throw new Error("Point is not on curve"+Gt)}const Xt=(jt&_1n$5)===_1n$5;return(Qt&1)===1!==Xt&&(jt=tt.neg(jt)),{x:Bt,y:jt}}else if(Ht===ot&&Qt===4){const Bt=tt.fromBytes(Vt.subarray(0,tt.BYTES)),Wt=tt.fromBytes(Vt.subarray(tt.BYTES,2*tt.BYTES));return{x:Bt,y:Wt}}else throw new Error(`Point of length ${Ht} was invalid. Expected ${nt} compressed bytes or ${ot} uncompressed bytes`)}}),ht=Ft=>bytesToHex$2(numberToBytesBE(Ft,o.nByteLength));function mt(Ft){const Ht=rt>>_1n$5;return Ft>Ht}function ft(Ft){return mt(Ft)?it(-Ft):Ft}const pt=(Ft,Ht,Qt)=>bytesToNumberBE(Ft.slice(Ht,Qt));class gt{constructor(Ht,Qt,Vt){this.r=Ht,this.s=Qt,this.recovery=Vt,this.assertValidity()}static fromCompact(Ht){const Qt=o.nByteLength;return Ht=ensureBytes$1("compactSignature",Ht,Qt*2),new gt(pt(Ht,0,Qt),pt(Ht,Qt,2*Qt))}static fromDER(Ht){const{r:Qt,s:Vt}=DER.toSig(ensureBytes$1("DER",Ht));return new gt(Qt,Vt)}assertValidity(){aInRange("r",this.r,_1n$5,rt),aInRange("s",this.s,_1n$5,rt)}addRecoveryBit(Ht){return new gt(this.r,this.s,Ht)}recoverPublicKey(Ht){const{r:Qt,s:Vt,recovery:Bt}=this,Wt=Ct(ensureBytes$1("msgHash",Ht));if(Bt==null||![0,1,2,3].includes(Bt))throw new Error("recovery id invalid");const jt=Bt===2||Bt===3?Qt+o.n:Qt;if(jt>=tt.ORDER)throw new Error("recovery id 2 or 3 invalid");const Xt=Bt&1?"03":"02",Kt=at.fromHex(Xt+ht(jt)),Pt=st(jt),Gt=it(-Wt*Pt),tr=it(Vt*Pt),zt=at.BASE.multiplyAndAddUnsafe(Kt,Gt,tr);if(!zt)throw new Error("point at infinify");return zt.assertValidity(),zt}hasHighS(){return mt(this.s)}normalizeS(){return this.hasHighS()?new gt(this.r,it(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes$2(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes$2(this.toCompactHex())}toCompactHex(){return ht(this.r)+ht(this.s)}}const yt={isValidPrivateKey(Ft){try{return ct(Ft),!0}catch{return!1}},normPrivateKeyToScalar:ct,randomPrivateKey:()=>{const Ft=getMinHashLength(o.n);return mapHashToField(o.randomBytes(Ft),o.n)},precompute(Ft=8,Ht=at.BASE){return Ht._setWindowSize(Ft),Ht.multiply(BigInt(3)),Ht}};function bt(Ft,Ht=!0){return at.fromPrivateKey(Ft).toRawBytes(Ht)}function xt(Ft){const Ht=isBytes$2(Ft),Qt=typeof Ft=="string",Vt=(Ht||Qt)&&Ft.length;return Ht?Vt===nt||Vt===ot:Qt?Vt===2*nt||Vt===2*ot:Ft instanceof at}function vt(Ft,Ht,Qt=!0){if(xt(Ft))throw new Error("first arg must be private key");if(!xt(Ht))throw new Error("second arg must be public key");return at.fromHex(Ht).multiply(ct(Ft)).toRawBytes(Qt)}const Et=o.bits2int||function(Ft){const Ht=bytesToNumberBE(Ft),Qt=Ft.length*8-o.nBitLength;return Qt>0?Ht>>BigInt(Qt):Ht},Ct=o.bits2int_modN||function(Ft){return it(Et(Ft))},St=bitMask(o.nBitLength);function At(Ft){return aInRange(`num < 2^${o.nBitLength}`,Ft,_0n$3,St),numberToBytesBE(Ft,o.nByteLength)}function kt(Ft,Ht,Qt=It){if(["recovered","canonical"].some(rr=>rr in Qt))throw new Error("sign() legacy options not supported");const{hash:Vt,randomBytes:Bt}=o;let{lowS:Wt,prehash:jt,extraEntropy:Xt}=Qt;Wt==null&&(Wt=!0),Ft=ensureBytes$1("msgHash",Ft),validateSigVerOpts(Qt),jt&&(Ft=ensureBytes$1("prehashed msgHash",Vt(Ft)));const Kt=Ct(Ft),Pt=ct(Ht),Gt=[At(Pt),At(Kt)];if(Xt!=null&&Xt!==!1){const rr=Xt===!0?Bt(tt.BYTES):Xt;Gt.push(ensureBytes$1("extraEntropy",rr))}const tr=concatBytes$1(...Gt),zt=Kt;function lr(rr){const Jt=Et(rr);if(!dt(Jt))return;const Rt=st(Jt),Mt=at.BASE.multiply(Jt).toAffine(),Ut=it(Mt.x);if(Ut===_0n$3)return;const Zt=it(Rt*it(zt+Ut*Pt));if(Zt===_0n$3)return;let nr=(Mt.x===Ut?0:2)|Number(Mt.y&_1n$5),ar=Zt;return Wt&&mt(Zt)&&(ar=ft(Zt),nr^=1),new gt(Ut,ar,nr)}return{seed:tr,k2sig:lr}}const It={lowS:o.lowS,prehash:!1},Ot={lowS:o.lowS,prehash:!1};function Nt(Ft,Ht,Qt=It){const{seed:Vt,k2sig:Bt}=kt(Ft,Ht,Qt),Wt=o;return createHmacDrbg(Wt.hash.outputLen,Wt.nByteLength,Wt.hmac)(Vt,Bt)}at.BASE._setWindowSize(8);function Yt(Ft,Ht,Qt,Vt=Ot){var Mt;const Bt=Ft;if(Ht=ensureBytes$1("msgHash",Ht),Qt=ensureBytes$1("publicKey",Qt),"strict"in Vt)throw new Error("options.strict was renamed to lowS");validateSigVerOpts(Vt);const{lowS:Wt,prehash:jt}=Vt;let Xt,Kt;try{if(typeof Bt=="string"||isBytes$2(Bt))try{Xt=gt.fromDER(Bt)}catch(Ut){if(!(Ut instanceof DER.Err))throw Ut;Xt=gt.fromCompact(Bt)}else if(typeof Bt=="object"&&typeof Bt.r=="bigint"&&typeof Bt.s=="bigint"){const{r:Ut,s:Zt}=Bt;Xt=new gt(Ut,Zt)}else throw new Error("PARSE");Kt=at.fromHex(Qt)}catch(Ut){if(Ut.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(Wt&&Xt.hasHighS())return!1;jt&&(Ht=o.hash(Ht));const{r:Pt,s:Gt}=Xt,tr=Ct(Ht),zt=st(Gt),lr=it(tr*zt),rr=it(Pt*zt),Jt=(Mt=at.BASE.multiplyAndAddUnsafe(Kt,lr,rr))==null?void 0:Mt.toAffine();return Jt?it(Jt.x)===Pt:!1}return{CURVE:o,getPublicKey:bt,getSharedSecret:vt,sign:Nt,verify:Yt,ProjectivePoint:at,Signature:gt,utils:yt}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash(et){return{hash:et,hmac:(o,...tt)=>hmac(et,o,concatBytes$2(...tt)),randomBytes:randomBytes$1}}function createCurve(et,o){const tt=rt=>weierstrass$1({...et,...getHash(rt)});return Object.freeze({...tt(o),create:tt})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n$4=BigInt(1),_2n$3=BigInt(2),divNearest$1=(et,o)=>(et+o/_2n$3)/o;function sqrtMod$1(et){const o=secp256k1P,tt=BigInt(3),rt=BigInt(6),nt=BigInt(11),ot=BigInt(22),it=BigInt(23),st=BigInt(44),at=BigInt(88),ct=et*et*et%o,lt=ct*ct*et%o,dt=pow2$1(lt,tt,o)*lt%o,ht=pow2$1(dt,tt,o)*lt%o,mt=pow2$1(ht,_2n$3,o)*ct%o,ft=pow2$1(mt,nt,o)*mt%o,pt=pow2$1(ft,ot,o)*ft%o,gt=pow2$1(pt,st,o)*pt%o,yt=pow2$1(gt,at,o)*gt%o,bt=pow2$1(yt,st,o)*pt%o,xt=pow2$1(bt,tt,o)*lt%o,vt=pow2$1(xt,it,o)*ft%o,Et=pow2$1(vt,rt,o)*ct%o,Ct=pow2$1(Et,_2n$3,o);if(!Fp$1.eql(Fp$1.sqr(Ct),et))throw new Error("Cannot find square root");return Ct}const Fp$1=Field$1(secp256k1P,void 0,void 0,{sqrt:sqrtMod$1}),secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp:Fp$1,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:et=>{const o=secp256k1N,tt=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),rt=-_1n$4*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),nt=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),ot=tt,it=BigInt("0x100000000000000000000000000000000"),st=divNearest$1(ot*et,o),at=divNearest$1(-rt*et,o);let ct=mod$1(et-st*tt-at*nt,o),lt=mod$1(-st*rt-at*ot,o);const dt=ct>it,ht=lt>it;if(dt&&(ct=o-ct),ht&&(lt=o-lt),ct>it||lt>it)throw new Error("splitScalar: Endomorphism failed, k="+et);return{k1neg:dt,k1:ct,k2neg:ht,k2:lt}}}},sha256$3);BigInt(0);secp256k1.ProjectivePoint;function getAction(et,o,tt){const rt=et[o.name];if(typeof rt=="function")return rt;const nt=et[tt];return typeof nt=="function"?nt:ot=>o(et,ot)}const version$6="2.13.8",getVersion$1=()=>`@wagmi/core@${version$6}`;var __classPrivateFieldGet$2=function(et,o,tt,rt){if(tt==="a"&&!rt)throw new TypeError("Private accessor was defined without a getter");if(typeof o=="function"?et!==o||!rt:!o.has(et))throw new TypeError("Cannot read private member from an object whose class did not declare it");return tt==="m"?rt:tt==="a"?rt.call(et):rt?rt.value:o.get(et)},_BaseError_instances,_BaseError_walk;let BaseError$1=class _s extends Error{get docsBaseUrl(){return"https://wagmi.sh/core"}get version(){return getVersion$1()}constructor(o,tt={}){var ot;super(),_BaseError_instances.add(this),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WagmiCoreError"});const rt=tt.cause instanceof _s?tt.cause.details:(ot=tt.cause)!=null&&ot.message?tt.cause.message:tt.details,nt=tt.cause instanceof _s&&tt.cause.docsPath||tt.docsPath;this.message=[o||"An error occurred.","",...tt.metaMessages?[...tt.metaMessages,""]:[],...nt?[`Docs: ${this.docsBaseUrl}${nt}.html${tt.docsSlug?`#${tt.docsSlug}`:""}`]:[],...rt?[`Details: ${rt}`]:[],`Version: ${this.version}`].join(` +`),tt.cause&&(this.cause=tt.cause),this.details=rt,this.docsPath=nt,this.metaMessages=tt.metaMessages,this.shortMessage=o}walk(o){return __classPrivateFieldGet$2(this,_BaseError_instances,"m",_BaseError_walk).call(this,this,o)}};_BaseError_instances=new WeakSet,_BaseError_walk=function et(o,tt){return tt!=null&&tt(o)?o:o.cause?__classPrivateFieldGet$2(this,_BaseError_instances,"m",et).call(this,o.cause,tt):o};class ChainNotConfiguredError extends BaseError$1{constructor(){super("Chain not configured."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ChainNotConfiguredError"})}}class ConnectorAlreadyConnectedError extends BaseError$1{constructor(){super("Connector already connected."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorAlreadyConnectedError"})}}class ConnectorNotConnectedError extends BaseError$1{constructor(){super("Connector not connected."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorNotConnectedError"})}}class ConnectorAccountNotFoundError extends BaseError$1{constructor({address:o,connector:tt}){super(`Account "${o}" not found for connector "${tt.name}".`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorAccountNotFoundError"})}}class ConnectorChainMismatchError extends BaseError$1{constructor({connectionChainId:o,connectorChainId:tt}){super(`The current chain of the connector (id: ${tt}) does not match the connection's chain (id: ${o}).`,{metaMessages:[`Current Chain ID: ${tt}`,`Expected Chain ID: ${o}`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorChainMismatchError"})}}class ConnectorUnavailableReconnectingError extends BaseError$1{constructor({connector:o}){super(`Connector "${o.name}" unavailable while reconnecting.`,{details:["During the reconnection step, the only connector methods guaranteed to be available are: `id`, `name`, `type`, `uuid`.","All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored.","This error commonly occurs for connectors that asynchronously inject after reconnection has already started."].join(" ")}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorUnavailableReconnectingError"})}}async function connect$1(et,o){var rt;let tt;if(typeof o.connector=="function"?tt=et._internal.connectors.setup(o.connector):tt=o.connector,tt.uid===et.state.current)throw new ConnectorAlreadyConnectedError;try{et.setState(it=>({...it,status:"connecting"})),tt.emitter.emit("message",{type:"connecting"});const nt=await tt.connect({chainId:o.chainId}),ot=nt.accounts;return tt.emitter.off("connect",et._internal.events.connect),tt.emitter.on("change",et._internal.events.change),tt.emitter.on("disconnect",et._internal.events.disconnect),await((rt=et.storage)==null?void 0:rt.setItem("recentConnectorId",tt.id)),et.setState(it=>({...it,connections:new Map(it.connections).set(tt.uid,{accounts:ot,chainId:nt.chainId,connector:tt}),current:tt.uid,status:"connected"})),{accounts:ot,chainId:nt.chainId}}catch(nt){throw et.setState(ot=>({...ot,status:ot.current?"connected":"disconnected"})),nt}}const size$1=256;let index$3=size$1,buffer$2;function uid$1(et=11){if(!buffer$2||index$3+et>size$1*2){buffer$2="",index$3=0;for(let o=0;o{const bt=yt(gt);for(const vt in ft)delete bt[vt];const xt={...gt,...bt};return Object.assign(xt,{extend:pt(xt)})}}return Object.assign(ft,{extend:pt(ft)})}function createTransport({key:et,name:o,request:tt,retryCount:rt=3,retryDelay:nt=150,timeout:ot,type:it},st){const at=uid$1();return{config:{key:et,name:o,request:tt,retryCount:rt,retryDelay:nt,timeout:ot,type:it},request:buildRequest(tt,{retryCount:rt,retryDelay:nt,uid:at}),value:st}}function custom$1(et,o={}){const{key:tt="custom",name:rt="Custom Provider",retryDelay:nt}=o;return({retryCount:ot})=>createTransport({key:tt,name:rt,request:et.request.bind(et),retryCount:o.retryCount??ot,retryDelay:nt,type:"custom"})}class UrlRequiredError extends BaseError$3{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function http(et,o={}){const{batch:tt,fetchOptions:rt,key:nt="http",name:ot="HTTP JSON-RPC",onFetchRequest:it,onFetchResponse:st,retryDelay:at}=o;return({chain:ct,retryCount:lt,timeout:dt})=>{const{batchSize:ht=1e3,wait:mt=0}=typeof tt=="object"?tt:{},ft=o.retryCount??lt,pt=dt??o.timeout??1e4,gt=ct==null?void 0:ct.rpcUrls.default.http[0];if(!gt)throw new UrlRequiredError;const yt=getHttpRpcClient(gt,{fetchOptions:rt,onRequest:it,onResponse:st,timeout:pt});return createTransport({key:nt,name:ot,async request({method:bt,params:xt}){const vt={method:bt,params:xt},{schedule:Et}=createBatchScheduler({id:gt,wait:mt,shouldSplitBatch(kt){return kt.length>ht},fn:kt=>yt.request({body:kt}),sort:(kt,It)=>kt.id-It.id}),Ct=async kt=>tt?Et(kt):[await yt.request({body:kt})],[{error:St,result:At}]=await Ct(vt);if(St)throw new RpcRequestError({body:vt,error:St,url:gt});return At},retryCount:ft,retryDelay:at,timeout:pt,type:"http"},{fetchOptions:rt,url:gt})}}async function getConnectorClient(et,o={}){let tt;if(o.connector){const{connector:ct}=o;if(et.state.status==="reconnecting"&&!ct.getAccounts&&!ct.getChainId)throw new ConnectorUnavailableReconnectingError({connector:ct});const[lt,dt]=await Promise.all([ct.getAccounts(),ct.getChainId()]);tt={accounts:lt,chainId:dt,connector:ct}}else tt=et.state.connections.get(et.state.current);if(!tt)throw new ConnectorNotConnectedError;const rt=o.chainId??tt.chainId,nt=await tt.connector.getChainId();if(nt!==tt.chainId)throw new ConnectorChainMismatchError({connectionChainId:tt.chainId,connectorChainId:nt});const ot=tt.connector;if(ot.getClient)return ot.getClient({chainId:rt});const it=parseAccount(o.account??tt.accounts[0]);if(it.address=getAddress(it.address),o.account&&!tt.accounts.some(ct=>ct.toLowerCase()===it.address.toLowerCase()))throw new ConnectorAccountNotFoundError({address:it.address,connector:ot});const st=et.chains.find(ct=>ct.id===rt),at=await tt.connector.getProvider({chainId:rt});return createClient({account:it,chain:st,name:"Connector Client",transport:ct=>custom$1(at)({...ct,retryCount:0})})}async function disconnect(et,o={}){var nt,ot;let tt;if(o.connector)tt=o.connector;else{const{connections:it,current:st}=et.state,at=it.get(st);tt=at==null?void 0:at.connector}const rt=et.state.connections;tt&&(await tt.disconnect(),tt.emitter.off("change",et._internal.events.change),tt.emitter.off("disconnect",et._internal.events.disconnect),tt.emitter.on("connect",et._internal.events.connect),rt.delete(tt.uid)),et.setState(it=>{if(rt.size===0)return{...it,connections:new Map,current:null,status:"disconnected"};const st=rt.values().next().value;return{...it,connections:new Map(rt),current:st.connector.uid}});{const it=et.state.current;if(!it)return;const st=(nt=et.state.connections.get(it))==null?void 0:nt.connector;if(!st)return;await((ot=et.storage)==null?void 0:ot.setItem("recentConnectorId",st.id))}}function getUnit(et){return typeof et=="number"?et:et==="wei"?0:Math.abs(weiUnits[et])}function getAccount(et){const o=et.state.current,tt=et.state.connections.get(o),rt=tt==null?void 0:tt.accounts,nt=rt==null?void 0:rt[0],ot=et.chains.find(st=>st.id===(tt==null?void 0:tt.chainId)),it=et.state.status;switch(it){case"connected":return{address:nt,addresses:rt,chain:ot,chainId:tt==null?void 0:tt.chainId,connector:tt==null?void 0:tt.connector,isConnected:!0,isConnecting:!1,isDisconnected:!1,isReconnecting:!1,status:it};case"reconnecting":return{address:nt,addresses:rt,chain:ot,chainId:tt==null?void 0:tt.chainId,connector:tt==null?void 0:tt.connector,isConnected:!!nt,isConnecting:!1,isDisconnected:!1,isReconnecting:!0,status:it};case"connecting":return{address:nt,addresses:rt,chain:ot,chainId:tt==null?void 0:tt.chainId,connector:tt==null?void 0:tt.connector,isConnected:!1,isConnecting:!0,isDisconnected:!1,isReconnecting:!1,status:it};case"disconnected":return{address:void 0,addresses:void 0,chain:void 0,chainId:void 0,connector:void 0,isConnected:!1,isConnecting:!1,isDisconnected:!0,isReconnecting:!1,status:it}}}async function multicall(et,o){const{allowFailure:tt=!0,chainId:rt,contracts:nt,...ot}=o,it=et.getClient({chainId:rt});return getAction(it,multicall$1,"multicall")({allowFailure:tt,contracts:nt,...ot})}function readContract(et,o){const{chainId:tt,...rt}=o,nt=et.getClient({chainId:tt});return getAction(nt,readContract$1,"readContract")(rt)}async function readContracts(et,o){var st;const{allowFailure:tt=!0,blockNumber:rt,blockTag:nt,...ot}=o,it=o.contracts;try{const at={};for(const[ht,mt]of it.entries()){const ft=mt.chainId??et.state.chainId;at[ft]||(at[ft]=[]),(st=at[ft])==null||st.push({contract:mt,index:ht})}const ct=()=>Object.entries(at).map(([ht,mt])=>multicall(et,{...ot,allowFailure:tt,blockNumber:rt,blockTag:nt,chainId:Number.parseInt(ht),contracts:mt.map(({contract:ft})=>ft)})),lt=(await Promise.all(ct())).flat(),dt=Object.values(at).flatMap(ht=>ht.map(({index:mt})=>mt));return lt.reduce((ht,mt,ft)=>(ht&&(ht[dt[ft]]=mt),ht),[])}catch(at){if(at instanceof ContractFunctionExecutionError)throw at;const ct=()=>it.map(lt=>readContract(et,{...lt,blockNumber:rt,blockTag:nt}));return tt?(await Promise.allSettled(ct())).map(lt=>lt.status==="fulfilled"?{result:lt.value,status:"success"}:{error:lt.reason,result:void 0,status:"failure"}):await Promise.all(ct())}}async function getBalance(et,o){const{address:tt,blockNumber:rt,blockTag:nt,chainId:ot,token:it,unit:st="ether"}=o;if(it)try{return getTokenBalance(et,{balanceAddress:tt,chainId:ot,symbolType:"string",tokenAddress:it})}catch(ht){if(ht instanceof ContractFunctionExecutionError){const mt=await getTokenBalance(et,{balanceAddress:tt,chainId:ot,symbolType:"bytes32",tokenAddress:it}),ft=hexToString(trim$1(mt.symbol,{dir:"right"}));return{...mt,symbol:ft}}throw ht}const at=et.getClient({chainId:ot}),lt=await getAction(at,getBalance$1,"getBalance")(rt?{address:tt,blockNumber:rt}:{address:tt,blockTag:nt}),dt=et.chains.find(ht=>ht.id===ot)??at.chain;return{decimals:dt.nativeCurrency.decimals,formatted:formatUnits(lt,getUnit(st)),symbol:dt.nativeCurrency.symbol,value:lt}}async function getTokenBalance(et,o){const{balanceAddress:tt,chainId:rt,symbolType:nt,tokenAddress:ot,unit:it}=o,st={abi:[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:nt}]}],address:ot},[at,ct,lt]=await readContracts(et,{allowFailure:!1,contracts:[{...st,functionName:"balanceOf",args:[tt],chainId:rt},{...st,functionName:"decimals",chainId:rt},{...st,functionName:"symbol",chainId:rt}]}),dt=formatUnits(at??"0",getUnit(it??ct));return{decimals:ct,formatted:dt,symbol:lt,value:at}}function getBlockNumber(et,o={}){const{chainId:tt,...rt}=o,nt=et.getClient({chainId:tt});return getAction(nt,getBlockNumber$1,"getBlockNumber")(rt)}function getChainId(et){return et.state.chainId}function deepEqual(et,o){if(et===o)return!0;if(et&&o&&typeof et=="object"&&typeof o=="object"){if(et.constructor!==o.constructor)return!1;let tt,rt;if(Array.isArray(et)&&Array.isArray(o)){if(tt=et.length,tt!==o.length)return!1;for(rt=tt;rt--!==0;)if(!deepEqual(et[rt],o[rt]))return!1;return!0}if(et.valueOf!==Object.prototype.valueOf)return et.valueOf()===o.valueOf();if(et.toString!==Object.prototype.toString)return et.toString()===o.toString();const nt=Object.keys(et);if(tt=nt.length,tt!==Object.keys(o).length)return!1;for(rt=tt;rt--!==0;)if(!Object.prototype.hasOwnProperty.call(o,nt[rt]))return!1;for(rt=tt;rt--!==0;){const ot=nt[rt];if(ot&&!deepEqual(et[ot],o[ot]))return!1}return!0}return et!==et&&o!==o}let previousChains=[];function getChains(et){const o=et.chains;return deepEqual(previousChains,o)?previousChains:(previousChains=o,o)}let previousConnections=[];function getConnections(et){const o=[...et.state.connections.values()];return et.state.status==="reconnecting"||deepEqual(previousConnections,o)?previousConnections:(previousConnections=o,o)}let previousConnectors=[];function getConnectors(et){const o=et.connectors;return deepEqual(previousConnectors,o)?previousConnectors:(previousConnectors=o,o)}function getEnsAddress(et,o){const{chainId:tt,...rt}=o,nt=et.getClient({chainId:tt});return getAction(nt,getEnsAddress$1,"getEnsAddress")(rt)}function getEnsAvatar(et,o){const{chainId:tt,...rt}=o,nt=et.getClient({chainId:tt});return getAction(nt,getEnsAvatar$1,"getEnsAvatar")(rt)}function getEnsName(et,o){const{chainId:tt,...rt}=o,nt=et.getClient({chainId:tt});return getAction(nt,getEnsName$1,"getEnsName")(rt)}let isReconnecting=!1;async function reconnect(et,o={}){var ct,lt;if(isReconnecting)return[];isReconnecting=!0,et.setState(dt=>({...dt,status:dt.current?"reconnecting":"connecting"}));const tt=[];if((ct=o.connectors)!=null&&ct.length)for(const dt of o.connectors){let ht;typeof dt=="function"?ht=et._internal.connectors.setup(dt):ht=dt,tt.push(ht)}else tt.push(...et.connectors);let rt;try{rt=await((lt=et.storage)==null?void 0:lt.getItem("recentConnectorId"))}catch{}const nt={};for(const[,dt]of et.state.connections)nt[dt.connector.id]=1;rt&&(nt[rt]=0);const ot=Object.keys(nt).length>0?[...tt].sort((dt,ht)=>(nt[dt.id]??10)-(nt[ht.id]??10)):tt;let it=!1;const st=[],at=[];for(const dt of ot){const ht=await dt.getProvider().catch(()=>{});if(!ht||at.some(pt=>pt===ht)||!await dt.isAuthorized())continue;const ft=await dt.connect({isReconnecting:!0}).catch(()=>null);ft&&(dt.emitter.off("connect",et._internal.events.connect),dt.emitter.on("change",et._internal.events.change),dt.emitter.on("disconnect",et._internal.events.disconnect),et.setState(pt=>{const gt=new Map(it?pt.connections:new Map).set(dt.uid,{accounts:ft.accounts,chainId:ft.chainId,connector:dt});return{...pt,current:it?pt.current:dt.uid,connections:gt}}),st.push({accounts:ft.accounts,chainId:ft.chainId,connector:dt}),at.push(ht),it=!0)}return(et.state.status==="reconnecting"||et.state.status==="connecting")&&(it?et.setState(dt=>({...dt,status:"connected"})):et.setState(dt=>({...dt,connections:new Map,current:null,status:"disconnected"}))),isReconnecting=!1,st}async function signMessage(et,o){const{account:tt,connector:rt,...nt}=o;let ot;return typeof tt=="object"&&tt.type==="local"?ot=et.getClient():ot=await getConnectorClient(et,{account:tt,connector:rt}),getAction(ot,signMessage$1,"signMessage")({...nt,...tt?{account:tt}:{}})}class ProviderNotFoundError extends BaseError$1{constructor(){super("Provider not found."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ProviderNotFoundError"})}}class SwitchChainNotSupportedError extends BaseError$1{constructor({connector:o}){super(`"${o.name}" does not support programmatic chain switching.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SwitchChainNotSupportedError"})}}async function switchChain(et,o){var it;const{addEthereumChainParameter:tt,chainId:rt}=o,nt=et.state.connections.get(((it=o.connector)==null?void 0:it.uid)??et.state.current);if(nt){const st=nt.connector;if(!st.switchChain)throw new SwitchChainNotSupportedError({connector:st});return await st.switchChain({addEthereumChainParameter:tt,chainId:rt})}const ot=et.chains.find(st=>st.id===rt);if(!ot)throw new ChainNotConfiguredError;return et.setState(st=>({...st,chainId:rt})),ot}function watchAccount(et,o){const{onChange:tt}=o;return et.subscribe(()=>getAccount(et),tt,{equalityFn(rt,nt){const{connector:ot,...it}=rt,{connector:st,...at}=nt;return deepEqual(it,at)&&(ot==null?void 0:ot.id)===(st==null?void 0:st.id)&&(ot==null?void 0:ot.uid)===(st==null?void 0:st.uid)}})}function watchBlockNumber(et,o){const{syncConnectedChain:tt=et._internal.syncConnectedChain,...rt}=o;let nt;const ot=at=>{nt&&nt();const ct=et.getClient({chainId:at});return nt=getAction(ct,watchBlockNumber$1,"watchBlockNumber")(rt),nt},it=ot(o.chainId);let st;return tt&&!o.chainId&&(st=et.subscribe(({chainId:at})=>at,async at=>ot(at))),()=>{it==null||it(),st==null||st()}}function watchChainId(et,o){const{onChange:tt}=o;return et.subscribe(rt=>rt.chainId,tt)}function watchConnections(et,o){const{onChange:tt}=o;return et.subscribe(()=>getConnections(et),tt,{equalityFn:deepEqual})}function watchConnectors(et,o){const{onChange:tt}=o;return et._internal.connectors.subscribe((rt,nt)=>{tt(Object.values(rt),nt)})}function createConnector(et){return et}const supportsSimulationIdRegex=/(rabby|trustwallet)/,targetMap={coinbaseWallet:{id:"coinbaseWallet",name:"Coinbase Wallet",provider(et){return et!=null&&et.coinbaseWalletExtension?et.coinbaseWalletExtension:findProvider(et,"isCoinbaseWallet")}},metaMask:{id:"metaMask",name:"MetaMask",provider(et){return findProvider(et,o=>{if(!o.isMetaMask||o.isBraveWallet&&!o._events&&!o._state)return!1;const tt=["isApexWallet","isAvalanche","isBitKeep","isBlockWallet","isKuCoinWallet","isMathWallet","isOkxWallet","isOKExWallet","isOneInchIOSWallet","isOneInchAndroidWallet","isOpera","isPortal","isRabby","isTokenPocket","isTokenary","isZerion"];for(const rt of tt)if(o[rt])return!1;return!0})}},phantom:{id:"phantom",name:"Phantom",provider(et){var o,tt;return(o=et==null?void 0:et.phantom)!=null&&o.ethereum?(tt=et.phantom)==null?void 0:tt.ethereum:findProvider(et,"isPhantom")}}};injected.type="injected";function injected(et={}){const{shimDisconnect:o=!0,unstable_shimAsyncInject:tt}=et;function rt(){const at=et.target;if(typeof at=="function"){const ct=at();if(ct)return ct}return typeof at=="object"?at:typeof at=="string"?{...targetMap[at]??{id:at,name:`${at[0].toUpperCase()}${at.slice(1)}`,provider:`is${at[0].toUpperCase()}${at.slice(1)}`}}:{id:"injected",name:"Injected",provider(ct){return ct==null?void 0:ct.ethereum}}}let nt,ot,it,st;return at=>({get icon(){return rt().icon},get id(){return rt().id},get name(){return rt().name},get supportsSimulation(){return supportsSimulationIdRegex.test(this.id.toLowerCase())},type:injected.type,async setup(){const ct=await this.getProvider();ct!=null&&ct.on&&et.target&&(it||(it=this.onConnect.bind(this),ct.on("connect",it)),nt||(nt=this.onAccountsChanged.bind(this),ct.on("accountsChanged",nt)))},async connect({chainId:ct,isReconnecting:lt}={}){var mt,ft,pt,gt,yt,bt;const dt=await this.getProvider();if(!dt)throw new ProviderNotFoundError;let ht=[];if(lt)ht=await this.getAccounts().catch(()=>[]);else if(o)try{ht=(gt=(pt=(ft=(mt=(await dt.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}))[0])==null?void 0:mt.caveats)==null?void 0:ft[0])==null?void 0:pt.value)==null?void 0:gt.map(vt=>getAddress(vt)),ht.length>0&&(ht=await this.getAccounts())}catch(xt){const vt=xt;if(vt.code===UserRejectedRequestError.code)throw new UserRejectedRequestError(vt);if(vt.code===ResourceUnavailableRpcError.code)throw vt}try{!(ht!=null&&ht.length)&&!lt&&(ht=(await dt.request({method:"eth_requestAccounts"})).map(Et=>getAddress(Et))),it&&(dt.removeListener("connect",it),it=void 0),nt||(nt=this.onAccountsChanged.bind(this),dt.on("accountsChanged",nt)),ot||(ot=this.onChainChanged.bind(this),dt.on("chainChanged",ot)),st||(st=this.onDisconnect.bind(this),dt.on("disconnect",st));let xt=await this.getChainId();if(ct&&xt!==ct){const vt=await this.switchChain({chainId:ct}).catch(Et=>{if(Et.code===UserRejectedRequestError.code)throw Et;return{id:xt}});xt=(vt==null?void 0:vt.id)??xt}return o&&await((yt=at.storage)==null?void 0:yt.removeItem(`${this.id}.disconnected`)),et.target||await((bt=at.storage)==null?void 0:bt.setItem("injected.connected",!0)),{accounts:ht,chainId:xt}}catch(xt){const vt=xt;throw vt.code===UserRejectedRequestError.code?new UserRejectedRequestError(vt):vt.code===ResourceUnavailableRpcError.code?new ResourceUnavailableRpcError(vt):vt}},async disconnect(){var lt,dt;const ct=await this.getProvider();if(!ct)throw new ProviderNotFoundError;ot&&(ct.removeListener("chainChanged",ot),ot=void 0),st&&(ct.removeListener("disconnect",st),st=void 0),it||(it=this.onConnect.bind(this),ct.on("connect",it));try{await withTimeout(()=>ct.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]}),{timeout:100})}catch{}o&&await((lt=at.storage)==null?void 0:lt.setItem(`${this.id}.disconnected`,!0)),et.target||await((dt=at.storage)==null?void 0:dt.removeItem("injected.connected"))},async getAccounts(){const ct=await this.getProvider();if(!ct)throw new ProviderNotFoundError;return(await ct.request({method:"eth_accounts"})).map(dt=>getAddress(dt))},async getChainId(){const ct=await this.getProvider();if(!ct)throw new ProviderNotFoundError;const lt=await ct.request({method:"eth_chainId"});return Number(lt)},async getProvider(){if(typeof window>"u")return;let ct;const lt=rt();return typeof lt.provider=="function"?ct=lt.provider(window):typeof lt.provider=="string"?ct=findProvider(window,lt.provider):ct=lt.provider,ct&&!ct.removeListener&&("off"in ct&&typeof ct.off=="function"?ct.removeListener=ct.off:ct.removeListener=()=>{}),ct},async isAuthorized(){var ct,lt;try{if(o&&await((ct=at.storage)==null?void 0:ct.getItem(`${this.id}.disconnected`))||!et.target&&!await((lt=at.storage)==null?void 0:lt.getItem("injected.connected")))return!1;if(!await this.getProvider()){if(tt!==void 0&&tt!==!1){const ft=async()=>(typeof window<"u"&&window.removeEventListener("ethereum#initialized",ft),!!await this.getProvider()),pt=typeof tt=="number"?tt:1e3;if(await Promise.race([...typeof window<"u"?[new Promise(yt=>window.addEventListener("ethereum#initialized",()=>yt(ft()),{once:!0}))]:[],new Promise(yt=>setTimeout(()=>yt(ft()),pt))]))return!0}throw new ProviderNotFoundError}return!!(await withRetry(()=>this.getAccounts())).length}catch{return!1}},async switchChain({addEthereumChainParameter:ct,chainId:lt}){var mt,ft,pt,gt;const dt=await this.getProvider();if(!dt)throw new ProviderNotFoundError;const ht=at.chains.find(yt=>yt.id===lt);if(!ht)throw new SwitchChainError(new ChainNotConfiguredError);try{return await Promise.all([dt.request({method:"wallet_switchEthereumChain",params:[{chainId:numberToHex(lt)}]}).then(async()=>{await this.getChainId()===lt&&at.emitter.emit("change",{chainId:lt})}),new Promise(yt=>{const bt=xt=>{"chainId"in xt&&xt.chainId===lt&&(at.emitter.off("change",bt),yt())};at.emitter.on("change",bt)})]),ht}catch(yt){const bt=yt;if(bt.code===4902||((ft=(mt=bt==null?void 0:bt.data)==null?void 0:mt.originalError)==null?void 0:ft.code)===4902)try{const{default:xt,...vt}=ht.blockExplorers??{};let Et;ct!=null&&ct.blockExplorerUrls?Et=ct.blockExplorerUrls:xt&&(Et=[xt.url,...Object.values(vt).map(kt=>kt.url)]);let Ct;(pt=ct==null?void 0:ct.rpcUrls)!=null&&pt.length?Ct=ct.rpcUrls:Ct=[((gt=ht.rpcUrls.default)==null?void 0:gt.http[0])??""];const St={blockExplorerUrls:Et,chainId:numberToHex(lt),chainName:(ct==null?void 0:ct.chainName)??ht.name,iconUrls:ct==null?void 0:ct.iconUrls,nativeCurrency:(ct==null?void 0:ct.nativeCurrency)??ht.nativeCurrency,rpcUrls:Ct};if(await dt.request({method:"wallet_addEthereumChain",params:[St]}),await this.getChainId()!==lt)throw new UserRejectedRequestError(new Error("User rejected switch after adding network."));return ht}catch(xt){throw new UserRejectedRequestError(xt)}throw bt.code===UserRejectedRequestError.code?new UserRejectedRequestError(bt):new SwitchChainError(bt)}},async onAccountsChanged(ct){var lt;if(ct.length===0)this.onDisconnect();else if(at.emitter.listenerCount("connect")){const dt=(await this.getChainId()).toString();this.onConnect({chainId:dt}),o&&await((lt=at.storage)==null?void 0:lt.removeItem(`${this.id}.disconnected`))}else at.emitter.emit("change",{accounts:ct.map(dt=>getAddress(dt))})},onChainChanged(ct){const lt=Number(ct);at.emitter.emit("change",{chainId:lt})},async onConnect(ct){const lt=await this.getAccounts();if(lt.length===0)return;const dt=Number(ct.chainId);at.emitter.emit("connect",{accounts:lt,chainId:dt});const ht=await this.getProvider();ht&&(it&&(ht.removeListener("connect",it),it=void 0),nt||(nt=this.onAccountsChanged.bind(this),ht.on("accountsChanged",nt)),ot||(ot=this.onChainChanged.bind(this),ht.on("chainChanged",ot)),st||(st=this.onDisconnect.bind(this),ht.on("disconnect",st)))},async onDisconnect(ct){const lt=await this.getProvider();ct&&ct.code===1013&<&&(await this.getAccounts()).length||(at.emitter.emit("disconnect"),lt&&(ot&&(lt.removeListener("chainChanged",ot),ot=void 0),st&&(lt.removeListener("disconnect",st),st=void 0),it||(it=this.onConnect.bind(this),lt.on("connect",it))))}})}function findProvider(et,o){function tt(nt){return typeof o=="function"?o(nt):typeof o=="string"?nt[o]:!0}const rt=et.ethereum;if(rt!=null&&rt.providers)return rt.providers.find(nt=>tt(nt));if(rt&&tt(rt))return rt}function requestProviders(et){if(typeof window>"u")return;const o=tt=>et(tt.detail);return window.addEventListener("eip6963:announceProvider",o),window.dispatchEvent(new CustomEvent("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",o)}function createStore$1(){const et=new Set;let o=[];const tt=()=>requestProviders(nt=>{o.some(({info:ot})=>ot.uuid===nt.info.uuid)||(o=[...o,nt],et.forEach(ot=>ot(o,{added:[nt]})))});let rt=tt();return{_listeners(){return et},clear(){et.forEach(nt=>nt([],{removed:[...o]})),o=[]},destroy(){this.clear(),et.clear(),rt==null||rt()},findProvider({rdns:nt}){return o.find(ot=>ot.info.rdns===nt)},getProviders(){return o},reset(){this.clear(),rt==null||rt(),rt=tt()},subscribe(nt,{emitImmediately:ot}={}){return et.add(nt),ot&&nt(o,{added:o}),()=>et.delete(nt)}}}const __vite_import_meta_env__$2={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},subscribeWithSelectorImpl=et=>(o,tt,rt)=>{const nt=rt.subscribe;return rt.subscribe=(it,st,at)=>{let ct=it;if(st){const lt=(at==null?void 0:at.equalityFn)||Object.is;let dt=it(rt.getState());ct=ht=>{const mt=it(ht);if(!lt(dt,mt)){const ft=dt;st(dt=mt,ft)}},at!=null&&at.fireImmediately&&st(dt,dt)}return nt(ct)},et(o,tt,rt)},subscribeWithSelector=subscribeWithSelectorImpl;function createJSONStorage(et,o){let tt;try{tt=et()}catch{return}return{getItem:nt=>{var ot;const it=at=>at===null?null:JSON.parse(at,void 0),st=(ot=tt.getItem(nt))!=null?ot:null;return st instanceof Promise?st.then(it):it(st)},setItem:(nt,ot)=>tt.setItem(nt,JSON.stringify(ot,void 0)),removeItem:nt=>tt.removeItem(nt)}}const toThenable=et=>o=>{try{const tt=et(o);return tt instanceof Promise?tt:{then(rt){return toThenable(rt)(tt)},catch(rt){return this}}}catch(tt){return{then(rt){return this},catch(rt){return toThenable(rt)(tt)}}}},oldImpl=(et,o)=>(tt,rt,nt)=>{let ot={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:gt=>gt,version:0,merge:(gt,yt)=>({...yt,...gt}),...o},it=!1;const st=new Set,at=new Set;let ct;try{ct=ot.getStorage()}catch{}if(!ct)return et((...gt)=>{console.warn(`[zustand persist middleware] Unable to update item '${ot.name}', the given storage is currently unavailable.`),tt(...gt)},rt,nt);const lt=toThenable(ot.serialize),dt=()=>{const gt=ot.partialize({...rt()});let yt;const bt=lt({state:gt,version:ot.version}).then(xt=>ct.setItem(ot.name,xt)).catch(xt=>{yt=xt});if(yt)throw yt;return bt},ht=nt.setState;nt.setState=(gt,yt)=>{ht(gt,yt),dt()};const mt=et((...gt)=>{tt(...gt),dt()},rt,nt);let ft;const pt=()=>{var gt;if(!ct)return;it=!1,st.forEach(bt=>bt(rt()));const yt=((gt=ot.onRehydrateStorage)==null?void 0:gt.call(ot,rt()))||void 0;return toThenable(ct.getItem.bind(ct))(ot.name).then(bt=>{if(bt)return ot.deserialize(bt)}).then(bt=>{if(bt)if(typeof bt.version=="number"&&bt.version!==ot.version){if(ot.migrate)return ot.migrate(bt.state,bt.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return bt.state}).then(bt=>{var xt;return ft=ot.merge(bt,(xt=rt())!=null?xt:mt),tt(ft,!0),dt()}).then(()=>{yt==null||yt(ft,void 0),it=!0,at.forEach(bt=>bt(ft))}).catch(bt=>{yt==null||yt(void 0,bt)})};return nt.persist={setOptions:gt=>{ot={...ot,...gt},gt.getStorage&&(ct=gt.getStorage())},clearStorage:()=>{ct==null||ct.removeItem(ot.name)},getOptions:()=>ot,rehydrate:()=>pt(),hasHydrated:()=>it,onHydrate:gt=>(st.add(gt),()=>{st.delete(gt)}),onFinishHydration:gt=>(at.add(gt),()=>{at.delete(gt)})},pt(),ft||mt},newImpl=(et,o)=>(tt,rt,nt)=>{let ot={storage:createJSONStorage(()=>localStorage),partialize:pt=>pt,version:0,merge:(pt,gt)=>({...gt,...pt}),...o},it=!1;const st=new Set,at=new Set;let ct=ot.storage;if(!ct)return et((...pt)=>{console.warn(`[zustand persist middleware] Unable to update item '${ot.name}', the given storage is currently unavailable.`),tt(...pt)},rt,nt);const lt=()=>{const pt=ot.partialize({...rt()});return ct.setItem(ot.name,{state:pt,version:ot.version})},dt=nt.setState;nt.setState=(pt,gt)=>{dt(pt,gt),lt()};const ht=et((...pt)=>{tt(...pt),lt()},rt,nt);let mt;const ft=()=>{var pt,gt;if(!ct)return;it=!1,st.forEach(bt=>{var xt;return bt((xt=rt())!=null?xt:ht)});const yt=((gt=ot.onRehydrateStorage)==null?void 0:gt.call(ot,(pt=rt())!=null?pt:ht))||void 0;return toThenable(ct.getItem.bind(ct))(ot.name).then(bt=>{if(bt)if(typeof bt.version=="number"&&bt.version!==ot.version){if(ot.migrate)return ot.migrate(bt.state,bt.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return bt.state}).then(bt=>{var xt;return mt=ot.merge(bt,(xt=rt())!=null?xt:ht),tt(mt,!0),lt()}).then(()=>{yt==null||yt(mt,void 0),mt=rt(),it=!0,at.forEach(bt=>bt(mt))}).catch(bt=>{yt==null||yt(void 0,bt)})};return nt.persist={setOptions:pt=>{ot={...ot,...pt},pt.storage&&(ct=pt.storage)},clearStorage:()=>{ct==null||ct.removeItem(ot.name)},getOptions:()=>ot,rehydrate:()=>ft(),hasHydrated:()=>it,onHydrate:pt=>(st.add(pt),()=>{st.delete(pt)}),onFinishHydration:pt=>(at.add(pt),()=>{at.delete(pt)})},ot.skipHydration||ft(),mt||ht},persistImpl=(et,o)=>"getStorage"in o||"serialize"in o||"deserialize"in o?((__vite_import_meta_env__$2?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),oldImpl(et,o)):newImpl(et,o),persist=persistImpl,__vite_import_meta_env__$1={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},createStoreImpl=et=>{let o;const tt=new Set,rt=(at,ct)=>{const lt=typeof at=="function"?at(o):at;if(!Object.is(lt,o)){const dt=o;o=ct??typeof lt!="object"?lt:Object.assign({},o,lt),tt.forEach(ht=>ht(o,dt))}},nt=()=>o,st={setState:rt,getState:nt,subscribe:at=>(tt.add(at),()=>tt.delete(at)),destroy:()=>{(__vite_import_meta_env__$1?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),tt.clear()}};return o=et(rt,nt,st),st},createStore=et=>et?createStoreImpl(et):createStoreImpl;var eventemitter3={exports:{}};(function(et){var o=Object.prototype.hasOwnProperty,tt="~";function rt(){}Object.create&&(rt.prototype=Object.create(null),new rt().__proto__||(tt=!1));function nt(at,ct,lt){this.fn=at,this.context=ct,this.once=lt||!1}function ot(at,ct,lt,dt,ht){if(typeof lt!="function")throw new TypeError("The listener must be a function");var mt=new nt(lt,dt||at,ht),ft=tt?tt+ct:ct;return at._events[ft]?at._events[ft].fn?at._events[ft]=[at._events[ft],mt]:at._events[ft].push(mt):(at._events[ft]=mt,at._eventsCount++),at}function it(at,ct){--at._eventsCount===0?at._events=new rt:delete at._events[ct]}function st(){this._events=new rt,this._eventsCount=0}st.prototype.eventNames=function(){var ct=[],lt,dt;if(this._eventsCount===0)return ct;for(dt in lt=this._events)o.call(lt,dt)&&ct.push(tt?dt.slice(1):dt);return Object.getOwnPropertySymbols?ct.concat(Object.getOwnPropertySymbols(lt)):ct},st.prototype.listeners=function(ct){var lt=tt?tt+ct:ct,dt=this._events[lt];if(!dt)return[];if(dt.fn)return[dt.fn];for(var ht=0,mt=dt.length,ft=new Array(mt);ht{let nt=rt;return(nt==null?void 0:nt.__type)==="bigint"&&(nt=BigInt(nt.value)),(nt==null?void 0:nt.__type)==="Map"&&(nt=new Map(nt.value)),(o==null?void 0:o(tt,nt))??nt})}function getReferenceKey(et,o){return et.slice(0,o).join(".")||"."}function getCutoff(et,o){const{length:tt}=et;for(let rt=0;rt{let it=ot;return typeof it=="bigint"&&(it={__type:"bigint",value:ot.toString()}),it instanceof Map&&(it={__type:"Map",value:Array.from(ot.entries())}),(o==null?void 0:o(nt,it))??it},rt),tt??void 0)}function createStorage(et){const{deserialize:o=deserialize$1,key:tt="wagmi",serialize:rt=serialize$1,storage:nt=noopStorage}=et;function ot(it){return it instanceof Promise?it.then(st=>st).catch(()=>null):it}return{...nt,key:tt,async getItem(it,st){const at=nt.getItem(`${tt}.${it}`),ct=await ot(at);return ct?o(ct)??null:st??null},async setItem(it,st){const at=`${tt}.${it}`;st===null?await ot(nt.removeItem(at)):await ot(nt.setItem(at,rt(st)))},async removeItem(it){await ot(nt.removeItem(`${tt}.${it}`))}}}const noopStorage={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},size=256;let index$2=size,buffer$1;function uid(et=11){if(!buffer$1||index$2+et>size*2){buffer$1="",index$2=0;for(let o=0;oot.chains),at=createStore(()=>[...ot.connectors??[],...nt?[]:(it==null?void 0:it.getProviders().map(lt))??[]].map(ct));function ct(Et){var At;const Ct=createEmitter(uid()),St={...Et({emitter:Ct,chains:st.getState(),storage:tt,transports:ot.transports}),emitter:Ct,uid:Ct.uid};return Ct.on("connect",xt),(At=St.setup)==null||At.call(St),St}function lt(Et){const{info:Ct}=Et,St=Et.provider;return injected({target:{...Ct,id:Ct.rdns,provider:St}})}const dt=new Map;function ht(Et={}){const Ct=Et.chainId??gt.getState().chainId,St=st.getState().find(kt=>kt.id===Ct);if(Et.chainId&&!St)throw new ChainNotConfiguredError;{const kt=dt.get(gt.getState().chainId);if(kt&&!St)return kt;if(!St)throw new ChainNotConfiguredError}{const kt=dt.get(Ct);if(kt)return kt}let At;if(ot.client)At=ot.client({chain:St});else{const kt=St.id,It=st.getState().map(Yt=>Yt.id),Ot={},Nt=Object.entries(ot);for(const[Yt,Ft]of Nt)if(!(Yt==="chains"||Yt==="client"||Yt==="connectors"||Yt==="transports"))if(typeof Ft=="object")if(kt in Ft)Ot[Yt]=Ft[kt];else{if(It.some(Qt=>Qt in Ft))continue;Ot[Yt]=Ft}else Ot[Yt]=Ft;At=createClient({...Ot,chain:St,batch:Ot.batch??{multicall:!0},transport:Yt=>ot.transports[kt]({...Yt,connectors:at})})}return dt.set(Ct,At),At}function mt(){return{chainId:st.getState()[0].id,connections:new Map,current:null,status:"disconnected"}}let ft;const pt="0.0.0-canary-";version$6.startsWith(pt)?ft=Number.parseInt(version$6.replace(pt,"")):ft=Number.parseInt(version$6.split(".")[0]??"0");const gt=createStore(subscribeWithSelector(tt?persist(mt,{migrate(Et,Ct){if(Ct===ft)return Et;const St=mt(),At=yt(Et,St.chainId);return{...St,chainId:At}},name:"store",partialize(Et){return{connections:{__type:"Map",value:Array.from(Et.connections.entries()).map(([Ct,St])=>{const{id:At,name:kt,type:It,uid:Ot}=St.connector;return[Ct,{...St,connector:{id:At,name:kt,type:It,uid:Ot}}]})},chainId:Et.chainId,current:Et.current}},merge(Et,Ct){typeof Et=="object"&&Et&&"status"in Et&&delete Et.status;const St=yt(Et,Ct.chainId);return{...Ct,...Et,chainId:St}},skipHydration:nt,storage:tt,version:ft}):mt));function yt(Et,Ct){return Et&&typeof Et=="object"&&"chainId"in Et&&typeof Et.chainId=="number"&&st.getState().some(St=>St.id===Et.chainId)?Et.chainId:Ct}rt&>.subscribe(({connections:Et,current:Ct})=>{var St;return Ct?(St=Et.get(Ct))==null?void 0:St.chainId:void 0},Et=>{if(st.getState().some(St=>St.id===Et))return gt.setState(St=>({...St,chainId:Et??St.chainId}))}),it==null||it.subscribe(Et=>{const Ct=new Map;for(const At of at.getState())Ct.set(At.id,!0);const St=[];for(const At of Et){const kt=ct(lt(At));Ct.has(kt.id)||St.push(kt)}tt&&!gt.persist.hasHydrated()||at.setState(At=>[...At,...St],!0)});function bt(Et){gt.setState(Ct=>{const St=Ct.connections.get(Et.uid);return St?{...Ct,connections:new Map(Ct.connections).set(Et.uid,{accounts:Et.accounts??St.accounts,chainId:Et.chainId??St.chainId,connector:St.connector})}:Ct})}function xt(Et){gt.getState().status==="connecting"||gt.getState().status==="reconnecting"||gt.setState(Ct=>{const St=at.getState().find(At=>At.uid===Et.uid);return St?(St.emitter.listenerCount("connect")&&St.emitter.off("connect",bt),St.emitter.listenerCount("change")||St.emitter.on("change",bt),St.emitter.listenerCount("disconnect")||St.emitter.on("disconnect",vt),{...Ct,connections:new Map(Ct.connections).set(Et.uid,{accounts:Et.accounts,chainId:Et.chainId,connector:St}),current:Et.uid,status:"connected"}):Ct})}function vt(Et){gt.setState(Ct=>{const St=Ct.connections.get(Et.uid);if(St){const kt=St.connector;kt.emitter.listenerCount("change")&&St.connector.emitter.off("change",bt),kt.emitter.listenerCount("disconnect")&&St.connector.emitter.off("disconnect",vt),kt.emitter.listenerCount("connect")||St.connector.emitter.on("connect",xt)}if(Ct.connections.delete(Et.uid),Ct.connections.size===0)return{...Ct,connections:new Map,current:null,status:"disconnected"};const At=Ct.connections.values().next().value;return{...Ct,connections:new Map(Ct.connections),current:At.connector.uid}})}return{get chains(){return st.getState()},get connectors(){return at.getState()},storage:tt,getClient:ht,get state(){return gt.getState()},setState(Et){let Ct;typeof Et=="function"?Ct=Et(gt.getState()):Ct=Et;const St=mt();typeof Ct!="object"&&(Ct=St),Object.keys(St).some(kt=>!(kt in Ct))&&(Ct=St),gt.setState(Ct,!0)},subscribe(Et,Ct,St){return gt.subscribe(Et,Ct,St?{...St,fireImmediately:St.emitImmediately}:void 0)},_internal:{mipd:it,store:gt,ssr:!!nt,syncConnectedChain:rt,transports:ot.transports,chains:{setState(Et){const Ct=typeof Et=="function"?Et(st.getState()):Et;if(Ct.length!==0)return st.setState(Ct,!0)},subscribe(Et){return st.subscribe(Et)}},connectors:{providerDetailToConnector:lt,setup:ct,setState(Et){return at.setState(typeof Et=="function"?Et(at.getState()):Et,!0)},subscribe(Et){return at.subscribe(Et)}},events:{change:bt,connect:xt,disconnect:vt}}}}function hydrate(et,o){const{initialState:tt,reconnectOnMount:rt}=o;return tt&&!et._internal.store.persist.hasHydrated()&&et.setState({...tt,chainId:et.chains.some(nt=>nt.id===tt.chainId)?tt.chainId:et.chains[0].id,connections:rt?tt.connections:new Map,status:rt?"reconnecting":"disconnected"}),{async onMount(){var nt;if(et._internal.ssr){await et._internal.store.persist.rehydrate();const ot=(nt=et._internal.mipd)==null?void 0:nt.getProviders().map(et._internal.connectors.providerDetailToConnector).map(et._internal.connectors.setup);et._internal.connectors.setState(it=>[...it,...ot??[]])}rt?reconnect(et):et.storage&&et.setState(ot=>({...ot,connections:new Map}))}}}function extractRpcUrls(et){var ot,it,st;const{chain:o}=et,tt=o.rpcUrls.default.http[0];if(!et.transports)return[tt];const rt=(it=(ot=et.transports)==null?void 0:ot[o.id])==null?void 0:it.call(ot,{chain:o});return(((st=rt==null?void 0:rt.value)==null?void 0:st.transports)||[rt]).map(({value:at})=>(at==null?void 0:at.url)||tt)}function Hydrate(et){const{children:o,config:tt,initialState:rt,reconnectOnMount:nt=!0}=et,{onMount:ot}=hydrate(tt,{initialState:rt,reconnectOnMount:nt});tt._internal.ssr||ot();const it=reactExports.useRef(!0);return reactExports.useEffect(()=>{if(it.current&&tt._internal.ssr)return ot(),()=>{it.current=!1}},[]),o}const WagmiContext=reactExports.createContext(void 0);function WagmiProvider(et){const{children:o,config:tt}=et,rt={value:tt};return reactExports.createElement(Hydrate,et,reactExports.createElement(WagmiContext.Provider,rt,o))}const version$5="2.12.19",getVersion=()=>`wagmi@${version$5}`;class BaseError extends BaseError$1{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WagmiError"})}get docsBaseUrl(){return"https://wagmi.sh/react"}get version(){return getVersion()}}class WagmiProviderNotFoundError extends BaseError{constructor(){super("`useConfig` must be used within `WagmiProvider`.",{docsPath:"/api/WagmiProvider"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WagmiProviderNotFoundError"})}}function useConfig(et={}){const o=et.config??reactExports.useContext(WagmiContext);if(!o)throw new WagmiProviderNotFoundError;return o}function watchChains(et,o){const{onChange:tt}=o;return et._internal.chains.subscribe((rt,nt)=>{tt(rt,nt)})}var withSelector={exports:{}},withSelector_production_min={},shim={exports:{}},useSyncExternalStoreShim_production_min={};/** + * @license React + * use-sync-external-store-shim.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var e$2=reactExports;function h$4(et,o){return et===o&&(et!==0||1/et===1/o)||et!==et&&o!==o}var k$3=typeof Object.is=="function"?Object.is:h$4,l$2=e$2.useState,m$4=e$2.useEffect,n$3=e$2.useLayoutEffect,p$3=e$2.useDebugValue;function q$4(et,o){var tt=o(),rt=l$2({inst:{value:tt,getSnapshot:o}}),nt=rt[0].inst,ot=rt[1];return n$3(function(){nt.value=tt,nt.getSnapshot=o,r$4(nt)&&ot({inst:nt})},[et,tt,o]),m$4(function(){return r$4(nt)&&ot({inst:nt}),et(function(){r$4(nt)&&ot({inst:nt})})},[et]),p$3(tt),tt}function r$4(et){var o=et.getSnapshot;et=et.value;try{var tt=o();return!k$3(et,tt)}catch{return!0}}function t$3(et,o){return o()}var u$2=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?t$3:q$4;useSyncExternalStoreShim_production_min.useSyncExternalStore=e$2.useSyncExternalStore!==void 0?e$2.useSyncExternalStore:u$2;shim.exports=useSyncExternalStoreShim_production_min;var shimExports=shim.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var h$3=reactExports,n$2=shimExports;function p$2(et,o){return et===o&&(et!==0||1/et===1/o)||et!==et&&o!==o}var q$3=typeof Object.is=="function"?Object.is:p$2,r$3=n$2.useSyncExternalStore,t$2=h$3.useRef,u$1=h$3.useEffect,v$3=h$3.useMemo,w$3=h$3.useDebugValue;withSelector_production_min.useSyncExternalStoreWithSelector=function(et,o,tt,rt,nt){var ot=t$2(null);if(ot.current===null){var it={hasValue:!1,value:null};ot.current=it}else it=ot.current;ot=v$3(function(){function at(mt){if(!ct){if(ct=!0,lt=mt,mt=rt(mt),nt!==void 0&&it.hasValue){var ft=it.value;if(nt(ft,mt))return dt=ft}return dt=mt}if(ft=dt,q$3(lt,mt))return ft;var pt=rt(mt);return nt!==void 0&&nt(ft,pt)?ft:(lt=mt,dt=pt)}var ct=!1,lt,dt,ht=tt===void 0?null:tt;return[function(){return at(o())},ht===null?void 0:function(){return at(ht())}]},[o,tt,rt,nt]);var st=r$3(et,ot[0],ot[1]);return u$1(function(){it.hasValue=!0,it.value=st},[st]),w$3(st),st};withSelector.exports=withSelector_production_min;var withSelectorExports=withSelector.exports;const isPlainObject$4=et=>typeof et=="object"&&!Array.isArray(et);function useSyncExternalStoreWithTracked(et,o,tt=o,rt=deepEqual){const nt=reactExports.useRef([]),ot=withSelectorExports.useSyncExternalStoreWithSelector(et,o,tt,it=>it,(it,st)=>{if(isPlainObject$4(it)&&isPlainObject$4(st)&&nt.current.length){for(const at of nt.current)if(!rt(it[at],st[at]))return!1;return!0}return rt(it,st)});return reactExports.useMemo(()=>{if(isPlainObject$4(ot)){const it={...ot};let st={};for(const[at,ct]of Object.entries(it))st={...st,[at]:{configurable:!1,enumerable:!0,get:()=>(nt.current.includes(at)||nt.current.push(at),ct)}};return Object.defineProperties(it,st),it}return ot},[ot])}function useAccount(et={}){const o=useConfig(et);return useSyncExternalStoreWithTracked(tt=>watchAccount(o,{onChange:tt}),()=>getAccount(o))}function useAccountEffect(et={}){const{onConnect:o,onDisconnect:tt}=et,rt=useConfig(et);reactExports.useEffect(()=>watchAccount(rt,{onChange(nt,ot){if((ot.status==="reconnecting"||ot.status==="connecting"&&ot.address===void 0)&&nt.status==="connected"){const{address:it,addresses:st,chain:at,chainId:ct,connector:lt}=nt,dt=ot.status==="reconnecting"||ot.status===void 0;o==null||o({address:it,addresses:st,chain:at,chainId:ct,connector:lt,isReconnected:dt})}else ot.status==="connected"&&nt.status==="disconnected"&&(tt==null||tt())}}),[rt,o,tt])}var Subscribable=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(et){return this.listeners.add(et),this.onSubscribe(),()=>{this.listeners.delete(et),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},isServer=typeof window>"u"||"Deno"in globalThis;function noop$4(){}function functionalUpdate(et,o){return typeof et=="function"?et(o):et}function isValidTimeout(et){return typeof et=="number"&&et>=0&&et!==1/0}function timeUntilStale(et,o){return Math.max(et+(o||0)-Date.now(),0)}function resolveStaleTime(et,o){return typeof et=="function"?et(o):et}function resolveEnabled(et,o){return typeof et=="function"?et(o):et}function matchQuery(et,o){const{type:tt="all",exact:rt,fetchStatus:nt,predicate:ot,queryKey:it,stale:st}=et;if(it){if(rt){if(o.queryHash!==hashQueryKeyByOptions(it,o.options))return!1}else if(!partialMatchKey(o.queryKey,it))return!1}if(tt!=="all"){const at=o.isActive();if(tt==="active"&&!at||tt==="inactive"&&at)return!1}return!(typeof st=="boolean"&&o.isStale()!==st||nt&&nt!==o.state.fetchStatus||ot&&!ot(o))}function matchMutation(et,o){const{exact:tt,status:rt,predicate:nt,mutationKey:ot}=et;if(ot){if(!o.options.mutationKey)return!1;if(tt){if(hashKey(o.options.mutationKey)!==hashKey(ot))return!1}else if(!partialMatchKey(o.options.mutationKey,ot))return!1}return!(rt&&o.state.status!==rt||nt&&!nt(o))}function hashQueryKeyByOptions(et,o){return((o==null?void 0:o.queryKeyHashFn)||hashKey)(et)}function hashKey(et){return JSON.stringify(et,(o,tt)=>isPlainObject$3(tt)?Object.keys(tt).sort().reduce((rt,nt)=>(rt[nt]=tt[nt],rt),{}):tt)}function partialMatchKey(et,o){return et===o?!0:typeof et!=typeof o?!1:et&&o&&typeof et=="object"&&typeof o=="object"?!Object.keys(o).some(tt=>!partialMatchKey(et[tt],o[tt])):!1}function replaceEqualDeep(et,o){if(et===o)return et;const tt=isPlainArray(et)&&isPlainArray(o);if(tt||isPlainObject$3(et)&&isPlainObject$3(o)){const rt=tt?et:Object.keys(et),nt=rt.length,ot=tt?o:Object.keys(o),it=ot.length,st=tt?[]:{};let at=0;for(let ct=0;ct{setTimeout(o,et)})}function replaceData(et,o,tt){return typeof tt.structuralSharing=="function"?tt.structuralSharing(et,o):tt.structuralSharing!==!1?replaceEqualDeep(et,o):o}function addToEnd(et,o,tt=0){const rt=[...et,o];return tt&&rt.length>tt?rt.slice(1):rt}function addToStart(et,o,tt=0){const rt=[o,...et];return tt&&rt.length>tt?rt.slice(0,-1):rt}var skipToken=Symbol();function ensureQueryFn(et,o){return!et.queryFn&&(o!=null&&o.initialPromise)?()=>o.initialPromise:!et.queryFn||et.queryFn===skipToken?()=>Promise.reject(new Error(`Missing queryFn: '${et.queryHash}'`)):et.queryFn}var kn,hn,Mn,Us,FocusManager=(Us=class extends Subscribable{constructor(){super();hr(this,kn);hr(this,hn);hr(this,Mn);ur(this,Mn,o=>{if(!isServer&&window.addEventListener){const tt=()=>o();return window.addEventListener("visibilitychange",tt,!1),()=>{window.removeEventListener("visibilitychange",tt)}}})}onSubscribe(){Lt(this,hn)||this.setEventListener(Lt(this,Mn))}onUnsubscribe(){var o;this.hasListeners()||((o=Lt(this,hn))==null||o.call(this),ur(this,hn,void 0))}setEventListener(o){var tt;ur(this,Mn,o),(tt=Lt(this,hn))==null||tt.call(this),ur(this,hn,o(rt=>{typeof rt=="boolean"?this.setFocused(rt):this.onFocus()}))}setFocused(o){Lt(this,kn)!==o&&(ur(this,kn,o),this.onFocus())}onFocus(){const o=this.isFocused();this.listeners.forEach(tt=>{tt(o)})}isFocused(){var o;return typeof Lt(this,kn)=="boolean"?Lt(this,kn):((o=globalThis.document)==null?void 0:o.visibilityState)!=="hidden"}},kn=new WeakMap,hn=new WeakMap,Mn=new WeakMap,Us),focusManager=new FocusManager,Bn,fn,Fn,zs,OnlineManager=(zs=class extends Subscribable{constructor(){super();hr(this,Bn,!0);hr(this,fn);hr(this,Fn);ur(this,Fn,o=>{if(!isServer&&window.addEventListener){const tt=()=>o(!0),rt=()=>o(!1);return window.addEventListener("online",tt,!1),window.addEventListener("offline",rt,!1),()=>{window.removeEventListener("online",tt),window.removeEventListener("offline",rt)}}})}onSubscribe(){Lt(this,fn)||this.setEventListener(Lt(this,Fn))}onUnsubscribe(){var o;this.hasListeners()||((o=Lt(this,fn))==null||o.call(this),ur(this,fn,void 0))}setEventListener(o){var tt;ur(this,Fn,o),(tt=Lt(this,fn))==null||tt.call(this),ur(this,fn,o(this.setOnline.bind(this)))}setOnline(o){Lt(this,Bn)!==o&&(ur(this,Bn,o),this.listeners.forEach(rt=>{rt(o)}))}isOnline(){return Lt(this,Bn)}},Bn=new WeakMap,fn=new WeakMap,Fn=new WeakMap,zs),onlineManager=new OnlineManager;function pendingThenable(){let et,o;const tt=new Promise((nt,ot)=>{et=nt,o=ot});tt.status="pending",tt.catch(()=>{});function rt(nt){Object.assign(tt,nt),delete tt.resolve,delete tt.reject}return tt.resolve=nt=>{rt({status:"fulfilled",value:nt}),et(nt)},tt.reject=nt=>{rt({status:"rejected",reason:nt}),o(nt)},tt}function defaultRetryDelay(et){return Math.min(1e3*2**et,3e4)}function canFetch(et){return(et??"online")==="online"?onlineManager.isOnline():!0}var CancelledError=class extends Error{constructor(et){super("CancelledError"),this.revert=et==null?void 0:et.revert,this.silent=et==null?void 0:et.silent}};function isCancelledError(et){return et instanceof CancelledError}function createRetryer(et){let o=!1,tt=0,rt=!1,nt;const ot=pendingThenable(),it=pt=>{var gt;rt||(ht(new CancelledError(pt)),(gt=et.abort)==null||gt.call(et))},st=()=>{o=!0},at=()=>{o=!1},ct=()=>focusManager.isFocused()&&(et.networkMode==="always"||onlineManager.isOnline())&&et.canRun(),lt=()=>canFetch(et.networkMode)&&et.canRun(),dt=pt=>{var gt;rt||(rt=!0,(gt=et.onSuccess)==null||gt.call(et,pt),nt==null||nt(),ot.resolve(pt))},ht=pt=>{var gt;rt||(rt=!0,(gt=et.onError)==null||gt.call(et,pt),nt==null||nt(),ot.reject(pt))},mt=()=>new Promise(pt=>{var gt;nt=yt=>{(rt||ct())&&pt(yt)},(gt=et.onPause)==null||gt.call(et)}).then(()=>{var pt;nt=void 0,rt||(pt=et.onContinue)==null||pt.call(et)}),ft=()=>{if(rt)return;let pt;const gt=tt===0?et.initialPromise:void 0;try{pt=gt??et.fn()}catch(yt){pt=Promise.reject(yt)}Promise.resolve(pt).then(dt).catch(yt=>{var Ct;if(rt)return;const bt=et.retry??(isServer?0:3),xt=et.retryDelay??defaultRetryDelay,vt=typeof xt=="function"?xt(tt,yt):xt,Et=bt===!0||typeof bt=="number"&&ttct()?void 0:mt()).then(()=>{o?ht(yt):ft()})})};return{promise:ot,cancel:it,continue:()=>(nt==null||nt(),ot),cancelRetry:st,continueRetry:at,canStart:lt,start:()=>(lt()?ft():mt().then(ft),ot)}}function createNotifyManager(){let et=[],o=0,tt=st=>{st()},rt=st=>{st()},nt=st=>setTimeout(st,0);const ot=st=>{o?et.push(st):nt(()=>{tt(st)})},it=()=>{const st=et;et=[],st.length&&nt(()=>{rt(()=>{st.forEach(at=>{tt(at)})})})};return{batch:st=>{let at;o++;try{at=st()}finally{o--,o||it()}return at},batchCalls:st=>(...at)=>{ot(()=>{st(...at)})},schedule:ot,setNotifyFunction:st=>{tt=st},setBatchNotifyFunction:st=>{rt=st},setScheduler:st=>{nt=st}}}var notifyManager=createNotifyManager(),_n,Vs,Removable=(Vs=class{constructor(){hr(this,_n)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),isValidTimeout(this.gcTime)&&ur(this,_n,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(et){this.gcTime=Math.max(this.gcTime||0,et??(isServer?1/0:5*60*1e3))}clearGcTimeout(){Lt(this,_n)&&(clearTimeout(Lt(this,_n)),ur(this,_n,void 0))}},_n=new WeakMap,Vs),Un,zn,Vr,Or,io,Rn,Gr,nn,Hs,Query=(Hs=class extends Removable{constructor(o){super();hr(this,Gr);hr(this,Un);hr(this,zn);hr(this,Vr);hr(this,Or);hr(this,io);hr(this,Rn);ur(this,Rn,!1),ur(this,io,o.defaultOptions),this.setOptions(o.options),this.observers=[],ur(this,Vr,o.cache),this.queryKey=o.queryKey,this.queryHash=o.queryHash,ur(this,Un,getDefaultState$1(this.options)),this.state=o.state??Lt(this,Un),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var o;return(o=Lt(this,Or))==null?void 0:o.promise}setOptions(o){this.options={...Lt(this,io),...o},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Lt(this,Vr).remove(this)}setData(o,tt){const rt=replaceData(this.state.data,o,this.options);return fr(this,Gr,nn).call(this,{data:rt,type:"success",dataUpdatedAt:tt==null?void 0:tt.updatedAt,manual:tt==null?void 0:tt.manual}),rt}setState(o,tt){fr(this,Gr,nn).call(this,{type:"setState",state:o,setStateOptions:tt})}cancel(o){var rt,nt;const tt=(rt=Lt(this,Or))==null?void 0:rt.promise;return(nt=Lt(this,Or))==null||nt.cancel(o),tt?tt.then(noop$4).catch(noop$4):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Lt(this,Un))}isActive(){return this.observers.some(o=>resolveEnabled(o.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===skipToken||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(o=>o.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(o=0){return this.state.isInvalidated||this.state.data===void 0||!timeUntilStale(this.state.dataUpdatedAt,o)}onFocus(){var tt;const o=this.observers.find(rt=>rt.shouldFetchOnWindowFocus());o==null||o.refetch({cancelRefetch:!1}),(tt=Lt(this,Or))==null||tt.continue()}onOnline(){var tt;const o=this.observers.find(rt=>rt.shouldFetchOnReconnect());o==null||o.refetch({cancelRefetch:!1}),(tt=Lt(this,Or))==null||tt.continue()}addObserver(o){this.observers.includes(o)||(this.observers.push(o),this.clearGcTimeout(),Lt(this,Vr).notify({type:"observerAdded",query:this,observer:o}))}removeObserver(o){this.observers.includes(o)&&(this.observers=this.observers.filter(tt=>tt!==o),this.observers.length||(Lt(this,Or)&&(Lt(this,Rn)?Lt(this,Or).cancel({revert:!0}):Lt(this,Or).cancelRetry()),this.scheduleGc()),Lt(this,Vr).notify({type:"observerRemoved",query:this,observer:o}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||fr(this,Gr,nn).call(this,{type:"invalidate"})}fetch(o,tt){var at,ct,lt;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(tt!=null&&tt.cancelRefetch))this.cancel({silent:!0});else if(Lt(this,Or))return Lt(this,Or).continueRetry(),Lt(this,Or).promise}if(o&&this.setOptions(o),!this.options.queryFn){const dt=this.observers.find(ht=>ht.options.queryFn);dt&&this.setOptions(dt.options)}const rt=new AbortController,nt=dt=>{Object.defineProperty(dt,"signal",{enumerable:!0,get:()=>(ur(this,Rn,!0),rt.signal)})},ot=()=>{const dt=ensureQueryFn(this.options,tt),ht={queryKey:this.queryKey,meta:this.meta};return nt(ht),ur(this,Rn,!1),this.options.persister?this.options.persister(dt,ht,this):dt(ht)},it={fetchOptions:tt,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:ot};nt(it),(at=this.options.behavior)==null||at.onFetch(it,this),ur(this,zn,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((ct=it.fetchOptions)==null?void 0:ct.meta))&&fr(this,Gr,nn).call(this,{type:"fetch",meta:(lt=it.fetchOptions)==null?void 0:lt.meta});const st=dt=>{var ht,mt,ft,pt;isCancelledError(dt)&&dt.silent||fr(this,Gr,nn).call(this,{type:"error",error:dt}),isCancelledError(dt)||((mt=(ht=Lt(this,Vr).config).onError)==null||mt.call(ht,dt,this),(pt=(ft=Lt(this,Vr).config).onSettled)==null||pt.call(ft,this.state.data,dt,this)),this.scheduleGc()};return ur(this,Or,createRetryer({initialPromise:tt==null?void 0:tt.initialPromise,fn:it.fetchFn,abort:rt.abort.bind(rt),onSuccess:dt=>{var ht,mt,ft,pt;if(dt===void 0){st(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(dt)}catch(gt){st(gt);return}(mt=(ht=Lt(this,Vr).config).onSuccess)==null||mt.call(ht,dt,this),(pt=(ft=Lt(this,Vr).config).onSettled)==null||pt.call(ft,dt,this.state.error,this),this.scheduleGc()},onError:st,onFail:(dt,ht)=>{fr(this,Gr,nn).call(this,{type:"failed",failureCount:dt,error:ht})},onPause:()=>{fr(this,Gr,nn).call(this,{type:"pause"})},onContinue:()=>{fr(this,Gr,nn).call(this,{type:"continue"})},retry:it.options.retry,retryDelay:it.options.retryDelay,networkMode:it.options.networkMode,canRun:()=>!0})),Lt(this,Or).start()}},Un=new WeakMap,zn=new WeakMap,Vr=new WeakMap,Or=new WeakMap,io=new WeakMap,Rn=new WeakMap,Gr=new WeakSet,nn=function(o){const tt=rt=>{switch(o.type){case"failed":return{...rt,fetchFailureCount:o.failureCount,fetchFailureReason:o.error};case"pause":return{...rt,fetchStatus:"paused"};case"continue":return{...rt,fetchStatus:"fetching"};case"fetch":return{...rt,...fetchState(rt.data,this.options),fetchMeta:o.meta??null};case"success":return{...rt,data:o.data,dataUpdateCount:rt.dataUpdateCount+1,dataUpdatedAt:o.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!o.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const nt=o.error;return isCancelledError(nt)&&nt.revert&&Lt(this,zn)?{...Lt(this,zn),fetchStatus:"idle"}:{...rt,error:nt,errorUpdateCount:rt.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:rt.fetchFailureCount+1,fetchFailureReason:nt,fetchStatus:"idle",status:"error"};case"invalidate":return{...rt,isInvalidated:!0};case"setState":return{...rt,...o.state}}};this.state=tt(this.state),notifyManager.batch(()=>{this.observers.forEach(rt=>{rt.onQueryUpdate()}),Lt(this,Vr).notify({query:this,type:"updated",action:o})})},Hs);function fetchState(et,o){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:canFetch(o.networkMode)?"fetching":"paused",...et===void 0&&{error:null,status:"pending"}}}function getDefaultState$1(et){const o=typeof et.initialData=="function"?et.initialData():et.initialData,tt=o!==void 0,rt=tt?typeof et.initialDataUpdatedAt=="function"?et.initialDataUpdatedAt():et.initialDataUpdatedAt:0;return{data:o,dataUpdateCount:0,dataUpdatedAt:tt?rt??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:tt?"success":"pending",fetchStatus:"idle"}}var Zr,Ws,QueryCache=(Ws=class extends Subscribable{constructor(o={}){super();hr(this,Zr);this.config=o,ur(this,Zr,new Map)}build(o,tt,rt){const nt=tt.queryKey,ot=tt.queryHash??hashQueryKeyByOptions(nt,tt);let it=this.get(ot);return it||(it=new Query({cache:this,queryKey:nt,queryHash:ot,options:o.defaultQueryOptions(tt),state:rt,defaultOptions:o.getQueryDefaults(nt)}),this.add(it)),it}add(o){Lt(this,Zr).has(o.queryHash)||(Lt(this,Zr).set(o.queryHash,o),this.notify({type:"added",query:o}))}remove(o){const tt=Lt(this,Zr).get(o.queryHash);tt&&(o.destroy(),tt===o&&Lt(this,Zr).delete(o.queryHash),this.notify({type:"removed",query:o}))}clear(){notifyManager.batch(()=>{this.getAll().forEach(o=>{this.remove(o)})})}get(o){return Lt(this,Zr).get(o)}getAll(){return[...Lt(this,Zr).values()]}find(o){const tt={exact:!0,...o};return this.getAll().find(rt=>matchQuery(tt,rt))}findAll(o={}){const tt=this.getAll();return Object.keys(o).length>0?tt.filter(rt=>matchQuery(o,rt)):tt}notify(o){notifyManager.batch(()=>{this.listeners.forEach(tt=>{tt(o)})})}onFocus(){notifyManager.batch(()=>{this.getAll().forEach(o=>{o.onFocus()})})}onOnline(){notifyManager.batch(()=>{this.getAll().forEach(o=>{o.onOnline()})})}},Zr=new WeakMap,Ws),qr,Lr,Tn,Kr,un,Gs,Mutation=(Gs=class extends Removable{constructor(o){super();hr(this,Kr);hr(this,qr);hr(this,Lr);hr(this,Tn);this.mutationId=o.mutationId,ur(this,Lr,o.mutationCache),ur(this,qr,[]),this.state=o.state||getDefaultState(),this.setOptions(o.options),this.scheduleGc()}setOptions(o){this.options=o,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(o){Lt(this,qr).includes(o)||(Lt(this,qr).push(o),this.clearGcTimeout(),Lt(this,Lr).notify({type:"observerAdded",mutation:this,observer:o}))}removeObserver(o){ur(this,qr,Lt(this,qr).filter(tt=>tt!==o)),this.scheduleGc(),Lt(this,Lr).notify({type:"observerRemoved",mutation:this,observer:o})}optionalRemove(){Lt(this,qr).length||(this.state.status==="pending"?this.scheduleGc():Lt(this,Lr).remove(this))}continue(){var o;return((o=Lt(this,Tn))==null?void 0:o.continue())??this.execute(this.state.variables)}async execute(o){var nt,ot,it,st,at,ct,lt,dt,ht,mt,ft,pt,gt,yt,bt,xt,vt,Et,Ct,St;ur(this,Tn,createRetryer({fn:()=>this.options.mutationFn?this.options.mutationFn(o):Promise.reject(new Error("No mutationFn found")),onFail:(At,kt)=>{fr(this,Kr,un).call(this,{type:"failed",failureCount:At,error:kt})},onPause:()=>{fr(this,Kr,un).call(this,{type:"pause"})},onContinue:()=>{fr(this,Kr,un).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Lt(this,Lr).canRun(this)}));const tt=this.state.status==="pending",rt=!Lt(this,Tn).canStart();try{if(!tt){fr(this,Kr,un).call(this,{type:"pending",variables:o,isPaused:rt}),await((ot=(nt=Lt(this,Lr).config).onMutate)==null?void 0:ot.call(nt,o,this));const kt=await((st=(it=this.options).onMutate)==null?void 0:st.call(it,o));kt!==this.state.context&&fr(this,Kr,un).call(this,{type:"pending",context:kt,variables:o,isPaused:rt})}const At=await Lt(this,Tn).start();return await((ct=(at=Lt(this,Lr).config).onSuccess)==null?void 0:ct.call(at,At,o,this.state.context,this)),await((dt=(lt=this.options).onSuccess)==null?void 0:dt.call(lt,At,o,this.state.context)),await((mt=(ht=Lt(this,Lr).config).onSettled)==null?void 0:mt.call(ht,At,null,this.state.variables,this.state.context,this)),await((pt=(ft=this.options).onSettled)==null?void 0:pt.call(ft,At,null,o,this.state.context)),fr(this,Kr,un).call(this,{type:"success",data:At}),At}catch(At){try{throw await((yt=(gt=Lt(this,Lr).config).onError)==null?void 0:yt.call(gt,At,o,this.state.context,this)),await((xt=(bt=this.options).onError)==null?void 0:xt.call(bt,At,o,this.state.context)),await((Et=(vt=Lt(this,Lr).config).onSettled)==null?void 0:Et.call(vt,void 0,At,this.state.variables,this.state.context,this)),await((St=(Ct=this.options).onSettled)==null?void 0:St.call(Ct,void 0,At,o,this.state.context)),At}finally{fr(this,Kr,un).call(this,{type:"error",error:At})}}finally{Lt(this,Lr).runNext(this)}}},qr=new WeakMap,Lr=new WeakMap,Tn=new WeakMap,Kr=new WeakSet,un=function(o){const tt=rt=>{switch(o.type){case"failed":return{...rt,failureCount:o.failureCount,failureReason:o.error};case"pause":return{...rt,isPaused:!0};case"continue":return{...rt,isPaused:!1};case"pending":return{...rt,context:o.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:o.isPaused,status:"pending",variables:o.variables,submittedAt:Date.now()};case"success":return{...rt,data:o.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...rt,data:void 0,error:o.error,failureCount:rt.failureCount+1,failureReason:o.error,isPaused:!1,status:"error"}}};this.state=tt(this.state),notifyManager.batch(()=>{Lt(this,qr).forEach(rt=>{rt.onMutationUpdate(o)}),Lt(this,Lr).notify({mutation:this,type:"updated",action:o})})},Gs);function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var zr,so,Zs,MutationCache=(Zs=class extends Subscribable{constructor(o={}){super();hr(this,zr);hr(this,so);this.config=o,ur(this,zr,new Map),ur(this,so,Date.now())}build(o,tt,rt){const nt=new Mutation({mutationCache:this,mutationId:++Cn(this,so)._,options:o.defaultMutationOptions(tt),state:rt});return this.add(nt),nt}add(o){const tt=scopeFor(o),rt=Lt(this,zr).get(tt)??[];rt.push(o),Lt(this,zr).set(tt,rt),this.notify({type:"added",mutation:o})}remove(o){var rt;const tt=scopeFor(o);if(Lt(this,zr).has(tt)){const nt=(rt=Lt(this,zr).get(tt))==null?void 0:rt.filter(ot=>ot!==o);nt&&(nt.length===0?Lt(this,zr).delete(tt):Lt(this,zr).set(tt,nt))}this.notify({type:"removed",mutation:o})}canRun(o){var rt;const tt=(rt=Lt(this,zr).get(scopeFor(o)))==null?void 0:rt.find(nt=>nt.state.status==="pending");return!tt||tt===o}runNext(o){var rt;const tt=(rt=Lt(this,zr).get(scopeFor(o)))==null?void 0:rt.find(nt=>nt!==o&&nt.state.isPaused);return(tt==null?void 0:tt.continue())??Promise.resolve()}clear(){notifyManager.batch(()=>{this.getAll().forEach(o=>{this.remove(o)})})}getAll(){return[...Lt(this,zr).values()].flat()}find(o){const tt={exact:!0,...o};return this.getAll().find(rt=>matchMutation(tt,rt))}findAll(o={}){return this.getAll().filter(tt=>matchMutation(o,tt))}notify(o){notifyManager.batch(()=>{this.listeners.forEach(tt=>{tt(o)})})}resumePausedMutations(){const o=this.getAll().filter(tt=>tt.state.isPaused);return notifyManager.batch(()=>Promise.all(o.map(tt=>tt.continue().catch(noop$4))))}},zr=new WeakMap,so=new WeakMap,Zs);function scopeFor(et){var o;return((o=et.options.scope)==null?void 0:o.id)??String(et.mutationId)}function infiniteQueryBehavior(et){return{onFetch:(o,tt)=>{var lt,dt,ht,mt,ft;const rt=o.options,nt=(ht=(dt=(lt=o.fetchOptions)==null?void 0:lt.meta)==null?void 0:dt.fetchMore)==null?void 0:ht.direction,ot=((mt=o.state.data)==null?void 0:mt.pages)||[],it=((ft=o.state.data)==null?void 0:ft.pageParams)||[];let st={pages:[],pageParams:[]},at=0;const ct=async()=>{let pt=!1;const gt=xt=>{Object.defineProperty(xt,"signal",{enumerable:!0,get:()=>(o.signal.aborted?pt=!0:o.signal.addEventListener("abort",()=>{pt=!0}),o.signal)})},yt=ensureQueryFn(o.options,o.fetchOptions),bt=async(xt,vt,Et)=>{if(pt)return Promise.reject();if(vt==null&&xt.pages.length)return Promise.resolve(xt);const Ct={queryKey:o.queryKey,pageParam:vt,direction:Et?"backward":"forward",meta:o.options.meta};gt(Ct);const St=await yt(Ct),{maxPages:At}=o.options,kt=Et?addToStart:addToEnd;return{pages:kt(xt.pages,St,At),pageParams:kt(xt.pageParams,vt,At)}};if(nt&&ot.length){const xt=nt==="backward",vt=xt?getPreviousPageParam:getNextPageParam,Et={pages:ot,pageParams:it},Ct=vt(rt,Et);st=await bt(Et,Ct,xt)}else{const xt=et??ot.length;do{const vt=at===0?it[0]??rt.initialPageParam:getNextPageParam(rt,st);if(at>0&&vt==null)break;st=await bt(st,vt),at++}while(at{var pt,gt;return(gt=(pt=o.options).persister)==null?void 0:gt.call(pt,ct,{queryKey:o.queryKey,meta:o.options.meta,signal:o.signal},tt)}:o.fetchFn=ct}}}function getNextPageParam(et,{pages:o,pageParams:tt}){const rt=o.length-1;return o.length>0?et.getNextPageParam(o[rt],o,tt[rt],tt):void 0}function getPreviousPageParam(et,{pages:o,pageParams:tt}){var rt;return o.length>0?(rt=et.getPreviousPageParam)==null?void 0:rt.call(et,o[0],o,tt[0],tt):void 0}var Ir,pn,mn,Vn,Hn,gn,Wn,Gn,qs,QueryClient=(qs=class{constructor(et={}){hr(this,Ir);hr(this,pn);hr(this,mn);hr(this,Vn);hr(this,Hn);hr(this,gn);hr(this,Wn);hr(this,Gn);ur(this,Ir,et.queryCache||new QueryCache),ur(this,pn,et.mutationCache||new MutationCache),ur(this,mn,et.defaultOptions||{}),ur(this,Vn,new Map),ur(this,Hn,new Map),ur(this,gn,0)}mount(){Cn(this,gn)._++,Lt(this,gn)===1&&(ur(this,Wn,focusManager.subscribe(async et=>{et&&(await this.resumePausedMutations(),Lt(this,Ir).onFocus())})),ur(this,Gn,onlineManager.subscribe(async et=>{et&&(await this.resumePausedMutations(),Lt(this,Ir).onOnline())})))}unmount(){var et,o;Cn(this,gn)._--,Lt(this,gn)===0&&((et=Lt(this,Wn))==null||et.call(this),ur(this,Wn,void 0),(o=Lt(this,Gn))==null||o.call(this),ur(this,Gn,void 0))}isFetching(et){return Lt(this,Ir).findAll({...et,fetchStatus:"fetching"}).length}isMutating(et){return Lt(this,pn).findAll({...et,status:"pending"}).length}getQueryData(et){var tt;const o=this.defaultQueryOptions({queryKey:et});return(tt=Lt(this,Ir).get(o.queryHash))==null?void 0:tt.state.data}ensureQueryData(et){const o=this.getQueryData(et.queryKey);if(o===void 0)return this.fetchQuery(et);{const tt=this.defaultQueryOptions(et),rt=Lt(this,Ir).build(this,tt);return et.revalidateIfStale&&rt.isStaleByTime(resolveStaleTime(tt.staleTime,rt))&&this.prefetchQuery(tt),Promise.resolve(o)}}getQueriesData(et){return Lt(this,Ir).findAll(et).map(({queryKey:o,state:tt})=>{const rt=tt.data;return[o,rt]})}setQueryData(et,o,tt){const rt=this.defaultQueryOptions({queryKey:et}),nt=Lt(this,Ir).get(rt.queryHash),ot=nt==null?void 0:nt.state.data,it=functionalUpdate(o,ot);if(it!==void 0)return Lt(this,Ir).build(this,rt).setData(it,{...tt,manual:!0})}setQueriesData(et,o,tt){return notifyManager.batch(()=>Lt(this,Ir).findAll(et).map(({queryKey:rt})=>[rt,this.setQueryData(rt,o,tt)]))}getQueryState(et){var tt;const o=this.defaultQueryOptions({queryKey:et});return(tt=Lt(this,Ir).get(o.queryHash))==null?void 0:tt.state}removeQueries(et){const o=Lt(this,Ir);notifyManager.batch(()=>{o.findAll(et).forEach(tt=>{o.remove(tt)})})}resetQueries(et,o){const tt=Lt(this,Ir),rt={type:"active",...et};return notifyManager.batch(()=>(tt.findAll(et).forEach(nt=>{nt.reset()}),this.refetchQueries(rt,o)))}cancelQueries(et={},o={}){const tt={revert:!0,...o},rt=notifyManager.batch(()=>Lt(this,Ir).findAll(et).map(nt=>nt.cancel(tt)));return Promise.all(rt).then(noop$4).catch(noop$4)}invalidateQueries(et={},o={}){return notifyManager.batch(()=>{if(Lt(this,Ir).findAll(et).forEach(rt=>{rt.invalidate()}),et.refetchType==="none")return Promise.resolve();const tt={...et,type:et.refetchType??et.type??"active"};return this.refetchQueries(tt,o)})}refetchQueries(et={},o){const tt={...o,cancelRefetch:(o==null?void 0:o.cancelRefetch)??!0},rt=notifyManager.batch(()=>Lt(this,Ir).findAll(et).filter(nt=>!nt.isDisabled()).map(nt=>{let ot=nt.fetch(void 0,tt);return tt.throwOnError||(ot=ot.catch(noop$4)),nt.state.fetchStatus==="paused"?Promise.resolve():ot}));return Promise.all(rt).then(noop$4)}fetchQuery(et){const o=this.defaultQueryOptions(et);o.retry===void 0&&(o.retry=!1);const tt=Lt(this,Ir).build(this,o);return tt.isStaleByTime(resolveStaleTime(o.staleTime,tt))?tt.fetch(o):Promise.resolve(tt.state.data)}prefetchQuery(et){return this.fetchQuery(et).then(noop$4).catch(noop$4)}fetchInfiniteQuery(et){return et.behavior=infiniteQueryBehavior(et.pages),this.fetchQuery(et)}prefetchInfiniteQuery(et){return this.fetchInfiniteQuery(et).then(noop$4).catch(noop$4)}ensureInfiniteQueryData(et){return et.behavior=infiniteQueryBehavior(et.pages),this.ensureQueryData(et)}resumePausedMutations(){return onlineManager.isOnline()?Lt(this,pn).resumePausedMutations():Promise.resolve()}getQueryCache(){return Lt(this,Ir)}getMutationCache(){return Lt(this,pn)}getDefaultOptions(){return Lt(this,mn)}setDefaultOptions(et){ur(this,mn,et)}setQueryDefaults(et,o){Lt(this,Vn).set(hashKey(et),{queryKey:et,defaultOptions:o})}getQueryDefaults(et){const o=[...Lt(this,Vn).values()];let tt={};return o.forEach(rt=>{partialMatchKey(et,rt.queryKey)&&(tt={...tt,...rt.defaultOptions})}),tt}setMutationDefaults(et,o){Lt(this,Hn).set(hashKey(et),{mutationKey:et,defaultOptions:o})}getMutationDefaults(et){const o=[...Lt(this,Hn).values()];let tt={};return o.forEach(rt=>{partialMatchKey(et,rt.mutationKey)&&(tt={...tt,...rt.defaultOptions})}),tt}defaultQueryOptions(et){if(et._defaulted)return et;const o={...Lt(this,mn).queries,...this.getQueryDefaults(et.queryKey),...et,_defaulted:!0};return o.queryHash||(o.queryHash=hashQueryKeyByOptions(o.queryKey,o)),o.refetchOnReconnect===void 0&&(o.refetchOnReconnect=o.networkMode!=="always"),o.throwOnError===void 0&&(o.throwOnError=!!o.suspense),!o.networkMode&&o.persister&&(o.networkMode="offlineFirst"),o.enabled!==!0&&o.queryFn===skipToken&&(o.enabled=!1),o}defaultMutationOptions(et){return et!=null&&et._defaulted?et:{...Lt(this,mn).mutations,...(et==null?void 0:et.mutationKey)&&this.getMutationDefaults(et.mutationKey),...et,_defaulted:!0}}clear(){Lt(this,Ir).clear(),Lt(this,pn).clear()}},Ir=new WeakMap,pn=new WeakMap,mn=new WeakMap,Vn=new WeakMap,Hn=new WeakMap,gn=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,qs),Br,Cr,ao,Mr,In,Zn,yn,Qr,co,qn,Kn,Pn,jn,bn,Qn,kr,oo,Rs,Ts,Is,Ps,js,Ns,Ds,ru,Ks,QueryObserver=(Ks=class extends Subscribable{constructor(o,tt){super();hr(this,kr);hr(this,Br);hr(this,Cr);hr(this,ao);hr(this,Mr);hr(this,In);hr(this,Zn);hr(this,yn);hr(this,Qr);hr(this,co);hr(this,qn);hr(this,Kn);hr(this,Pn);hr(this,jn);hr(this,bn);hr(this,Qn,new Set);this.options=tt,ur(this,Br,o),ur(this,Qr,null),ur(this,yn,pendingThenable()),this.options.experimental_prefetchInRender||Lt(this,yn).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(tt)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Lt(this,Cr).addObserver(this),shouldFetchOnMount(Lt(this,Cr),this.options)?fr(this,kr,oo).call(this):this.updateResult(),fr(this,kr,Ps).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return shouldFetchOn(Lt(this,Cr),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return shouldFetchOn(Lt(this,Cr),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,fr(this,kr,js).call(this),fr(this,kr,Ns).call(this),Lt(this,Cr).removeObserver(this)}setOptions(o,tt){const rt=this.options,nt=Lt(this,Cr);if(this.options=Lt(this,Br).defaultQueryOptions(o),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof resolveEnabled(this.options.enabled,Lt(this,Cr))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");fr(this,kr,Ds).call(this),Lt(this,Cr).setOptions(this.options),rt._defaulted&&!shallowEqualObjects(this.options,rt)&&Lt(this,Br).getQueryCache().notify({type:"observerOptionsUpdated",query:Lt(this,Cr),observer:this});const ot=this.hasListeners();ot&&shouldFetchOptionally(Lt(this,Cr),nt,this.options,rt)&&fr(this,kr,oo).call(this),this.updateResult(tt),ot&&(Lt(this,Cr)!==nt||resolveEnabled(this.options.enabled,Lt(this,Cr))!==resolveEnabled(rt.enabled,Lt(this,Cr))||resolveStaleTime(this.options.staleTime,Lt(this,Cr))!==resolveStaleTime(rt.staleTime,Lt(this,Cr)))&&fr(this,kr,Rs).call(this);const it=fr(this,kr,Ts).call(this);ot&&(Lt(this,Cr)!==nt||resolveEnabled(this.options.enabled,Lt(this,Cr))!==resolveEnabled(rt.enabled,Lt(this,Cr))||it!==Lt(this,bn))&&fr(this,kr,Is).call(this,it)}getOptimisticResult(o){const tt=Lt(this,Br).getQueryCache().build(Lt(this,Br),o),rt=this.createResult(tt,o);return shouldAssignObserverCurrentProperties(this,rt)&&(ur(this,Mr,rt),ur(this,Zn,this.options),ur(this,In,Lt(this,Cr).state)),rt}getCurrentResult(){return Lt(this,Mr)}trackResult(o,tt){const rt={};return Object.keys(o).forEach(nt=>{Object.defineProperty(rt,nt,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(nt),tt==null||tt(nt),o[nt])})}),rt}trackProp(o){Lt(this,Qn).add(o)}getCurrentQuery(){return Lt(this,Cr)}refetch({...o}={}){return this.fetch({...o})}fetchOptimistic(o){const tt=Lt(this,Br).defaultQueryOptions(o),rt=Lt(this,Br).getQueryCache().build(Lt(this,Br),tt);return rt.fetch().then(()=>this.createResult(rt,tt))}fetch(o){return fr(this,kr,oo).call(this,{...o,cancelRefetch:o.cancelRefetch??!0}).then(()=>(this.updateResult(),Lt(this,Mr)))}createResult(o,tt){var At;const rt=Lt(this,Cr),nt=this.options,ot=Lt(this,Mr),it=Lt(this,In),st=Lt(this,Zn),ct=o!==rt?o.state:Lt(this,ao),{state:lt}=o;let dt={...lt},ht=!1,mt;if(tt._optimisticResults){const kt=this.hasListeners(),It=!kt&&shouldFetchOnMount(o,tt),Ot=kt&&shouldFetchOptionally(o,rt,tt,nt);(It||Ot)&&(dt={...dt,...fetchState(lt.data,o.options)}),tt._optimisticResults==="isRestoring"&&(dt.fetchStatus="idle")}let{error:ft,errorUpdatedAt:pt,status:gt}=dt;if(tt.select&&dt.data!==void 0)if(ot&&dt.data===(it==null?void 0:it.data)&&tt.select===Lt(this,co))mt=Lt(this,qn);else try{ur(this,co,tt.select),mt=tt.select(dt.data),mt=replaceData(ot==null?void 0:ot.data,mt,tt),ur(this,qn,mt),ur(this,Qr,null)}catch(kt){ur(this,Qr,kt)}else mt=dt.data;if(tt.placeholderData!==void 0&&mt===void 0&>==="pending"){let kt;if(ot!=null&&ot.isPlaceholderData&&tt.placeholderData===(st==null?void 0:st.placeholderData))kt=ot.data;else if(kt=typeof tt.placeholderData=="function"?tt.placeholderData((At=Lt(this,Kn))==null?void 0:At.state.data,Lt(this,Kn)):tt.placeholderData,tt.select&&kt!==void 0)try{kt=tt.select(kt),ur(this,Qr,null)}catch(It){ur(this,Qr,It)}kt!==void 0&&(gt="success",mt=replaceData(ot==null?void 0:ot.data,kt,tt),ht=!0)}Lt(this,Qr)&&(ft=Lt(this,Qr),mt=Lt(this,qn),pt=Date.now(),gt="error");const yt=dt.fetchStatus==="fetching",bt=gt==="pending",xt=gt==="error",vt=bt&&yt,Et=mt!==void 0,St={status:gt,fetchStatus:dt.fetchStatus,isPending:bt,isSuccess:gt==="success",isError:xt,isInitialLoading:vt,isLoading:vt,data:mt,dataUpdatedAt:dt.dataUpdatedAt,error:ft,errorUpdatedAt:pt,failureCount:dt.fetchFailureCount,failureReason:dt.fetchFailureReason,errorUpdateCount:dt.errorUpdateCount,isFetched:dt.dataUpdateCount>0||dt.errorUpdateCount>0,isFetchedAfterMount:dt.dataUpdateCount>ct.dataUpdateCount||dt.errorUpdateCount>ct.errorUpdateCount,isFetching:yt,isRefetching:yt&&!bt,isLoadingError:xt&&!Et,isPaused:dt.fetchStatus==="paused",isPlaceholderData:ht,isRefetchError:xt&&Et,isStale:isStale(o,tt),refetch:this.refetch,promise:Lt(this,yn)};if(this.options.experimental_prefetchInRender){const kt=Nt=>{St.status==="error"?Nt.reject(St.error):St.data!==void 0&&Nt.resolve(St.data)},It=()=>{const Nt=ur(this,yn,St.promise=pendingThenable());kt(Nt)},Ot=Lt(this,yn);switch(Ot.status){case"pending":o.queryHash===rt.queryHash&&kt(Ot);break;case"fulfilled":(St.status==="error"||St.data!==Ot.value)&&It();break;case"rejected":(St.status!=="error"||St.error!==Ot.reason)&&It();break}}return St}updateResult(o){const tt=Lt(this,Mr),rt=this.createResult(Lt(this,Cr),this.options);if(ur(this,In,Lt(this,Cr).state),ur(this,Zn,this.options),Lt(this,In).data!==void 0&&ur(this,Kn,Lt(this,Cr)),shallowEqualObjects(rt,tt))return;ur(this,Mr,rt);const nt={},ot=()=>{if(!tt)return!0;const{notifyOnChangeProps:it}=this.options,st=typeof it=="function"?it():it;if(st==="all"||!st&&!Lt(this,Qn).size)return!0;const at=new Set(st??Lt(this,Qn));return this.options.throwOnError&&at.add("error"),Object.keys(Lt(this,Mr)).some(ct=>{const lt=ct;return Lt(this,Mr)[lt]!==tt[lt]&&at.has(lt)})};(o==null?void 0:o.listeners)!==!1&&ot()&&(nt.listeners=!0),fr(this,kr,ru).call(this,{...nt,...o})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&fr(this,kr,Ps).call(this)}},Br=new WeakMap,Cr=new WeakMap,ao=new WeakMap,Mr=new WeakMap,In=new WeakMap,Zn=new WeakMap,yn=new WeakMap,Qr=new WeakMap,co=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Pn=new WeakMap,jn=new WeakMap,bn=new WeakMap,Qn=new WeakMap,kr=new WeakSet,oo=function(o){fr(this,kr,Ds).call(this);let tt=Lt(this,Cr).fetch(this.options,o);return o!=null&&o.throwOnError||(tt=tt.catch(noop$4)),tt},Rs=function(){fr(this,kr,js).call(this);const o=resolveStaleTime(this.options.staleTime,Lt(this,Cr));if(isServer||Lt(this,Mr).isStale||!isValidTimeout(o))return;const rt=timeUntilStale(Lt(this,Mr).dataUpdatedAt,o)+1;ur(this,Pn,setTimeout(()=>{Lt(this,Mr).isStale||this.updateResult()},rt))},Ts=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Lt(this,Cr)):this.options.refetchInterval)??!1},Is=function(o){fr(this,kr,Ns).call(this),ur(this,bn,o),!(isServer||resolveEnabled(this.options.enabled,Lt(this,Cr))===!1||!isValidTimeout(Lt(this,bn))||Lt(this,bn)===0)&&ur(this,jn,setInterval(()=>{(this.options.refetchIntervalInBackground||focusManager.isFocused())&&fr(this,kr,oo).call(this)},Lt(this,bn)))},Ps=function(){fr(this,kr,Rs).call(this),fr(this,kr,Is).call(this,fr(this,kr,Ts).call(this))},js=function(){Lt(this,Pn)&&(clearTimeout(Lt(this,Pn)),ur(this,Pn,void 0))},Ns=function(){Lt(this,jn)&&(clearInterval(Lt(this,jn)),ur(this,jn,void 0))},Ds=function(){const o=Lt(this,Br).getQueryCache().build(Lt(this,Br),this.options);if(o===Lt(this,Cr))return;const tt=Lt(this,Cr);ur(this,Cr,o),ur(this,ao,o.state),this.hasListeners()&&(tt==null||tt.removeObserver(this),o.addObserver(this))},ru=function(o){notifyManager.batch(()=>{o.listeners&&this.listeners.forEach(tt=>{tt(Lt(this,Mr))}),Lt(this,Br).getQueryCache().notify({query:Lt(this,Cr),type:"observerResultsUpdated"})})},Ks);function shouldLoadOnMount(et,o){return resolveEnabled(o.enabled,et)!==!1&&et.state.data===void 0&&!(et.state.status==="error"&&o.retryOnMount===!1)}function shouldFetchOnMount(et,o){return shouldLoadOnMount(et,o)||et.state.data!==void 0&&shouldFetchOn(et,o,o.refetchOnMount)}function shouldFetchOn(et,o,tt){if(resolveEnabled(o.enabled,et)!==!1){const rt=typeof tt=="function"?tt(et):tt;return rt==="always"||rt!==!1&&isStale(et,o)}return!1}function shouldFetchOptionally(et,o,tt,rt){return(et!==o||resolveEnabled(rt.enabled,et)===!1)&&(!tt.suspense||et.state.status!=="error")&&isStale(et,tt)}function isStale(et,o){return resolveEnabled(o.enabled,et)!==!1&&et.isStaleByTime(resolveStaleTime(o.staleTime,et))}function shouldAssignObserverCurrentProperties(et,o){return!shallowEqualObjects(et.getCurrentResult(),o)}var xn,vn,Fr,sn,ln,Xo,Os,Qs,MutationObserver$1=(Qs=class extends Subscribable{constructor(tt,rt){super();hr(this,ln);hr(this,xn);hr(this,vn);hr(this,Fr);hr(this,sn);ur(this,xn,tt),this.setOptions(rt),this.bindMethods(),fr(this,ln,Xo).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(tt){var nt;const rt=this.options;this.options=Lt(this,xn).defaultMutationOptions(tt),shallowEqualObjects(this.options,rt)||Lt(this,xn).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Lt(this,Fr),observer:this}),rt!=null&&rt.mutationKey&&this.options.mutationKey&&hashKey(rt.mutationKey)!==hashKey(this.options.mutationKey)?this.reset():((nt=Lt(this,Fr))==null?void 0:nt.state.status)==="pending"&&Lt(this,Fr).setOptions(this.options)}onUnsubscribe(){var tt;this.hasListeners()||(tt=Lt(this,Fr))==null||tt.removeObserver(this)}onMutationUpdate(tt){fr(this,ln,Xo).call(this),fr(this,ln,Os).call(this,tt)}getCurrentResult(){return Lt(this,vn)}reset(){var tt;(tt=Lt(this,Fr))==null||tt.removeObserver(this),ur(this,Fr,void 0),fr(this,ln,Xo).call(this),fr(this,ln,Os).call(this)}mutate(tt,rt){var nt;return ur(this,sn,rt),(nt=Lt(this,Fr))==null||nt.removeObserver(this),ur(this,Fr,Lt(this,xn).getMutationCache().build(Lt(this,xn),this.options)),Lt(this,Fr).addObserver(this),Lt(this,Fr).execute(tt)}},xn=new WeakMap,vn=new WeakMap,Fr=new WeakMap,sn=new WeakMap,ln=new WeakSet,Xo=function(){var rt;const tt=((rt=Lt(this,Fr))==null?void 0:rt.state)??getDefaultState();ur(this,vn,{...tt,isPending:tt.status==="pending",isSuccess:tt.status==="success",isError:tt.status==="error",isIdle:tt.status==="idle",mutate:this.mutate,reset:this.reset})},Os=function(tt){notifyManager.batch(()=>{var rt,nt,ot,it,st,at,ct,lt;if(Lt(this,sn)&&this.hasListeners()){const dt=Lt(this,vn).variables,ht=Lt(this,vn).context;(tt==null?void 0:tt.type)==="success"?((nt=(rt=Lt(this,sn)).onSuccess)==null||nt.call(rt,tt.data,dt,ht),(it=(ot=Lt(this,sn)).onSettled)==null||it.call(ot,tt.data,null,dt,ht)):(tt==null?void 0:tt.type)==="error"&&((at=(st=Lt(this,sn)).onError)==null||at.call(st,tt.error,dt,ht),(lt=(ct=Lt(this,sn)).onSettled)==null||lt.call(ct,void 0,tt.error,dt,ht))}this.listeners.forEach(dt=>{dt(Lt(this,vn))})})},Qs);function hashFn(et){return JSON.stringify(et,(o,tt)=>isPlainObject$2(tt)?Object.keys(tt).sort().reduce((rt,nt)=>(rt[nt]=tt[nt],rt),{}):typeof tt=="bigint"?tt.toString():tt)}function isPlainObject$2(et){if(!hasObjectPrototype(et))return!1;const o=et.constructor;if(typeof o>"u")return!0;const tt=o.prototype;return!(!hasObjectPrototype(tt)||!tt.hasOwnProperty("isPrototypeOf"))}function hasObjectPrototype(et){return Object.prototype.toString.call(et)==="[object Object]"}function filterQueryOptions(et){const{_defaulted:o,behavior:tt,gcTime:rt,initialData:nt,initialDataUpdatedAt:ot,maxPages:it,meta:st,networkMode:at,queryFn:ct,queryHash:lt,queryKey:dt,queryKeyHashFn:ht,retry:mt,retryDelay:ft,structuralSharing:pt,getPreviousPageParam:gt,getNextPageParam:yt,initialPageParam:bt,_optimisticResults:xt,enabled:vt,notifyOnChangeProps:Et,placeholderData:Ct,refetchInterval:St,refetchIntervalInBackground:At,refetchOnMount:kt,refetchOnReconnect:It,refetchOnWindowFocus:Ot,retryOnMount:Nt,select:Yt,staleTime:Ft,suspense:Ht,throwOnError:Qt,config:Vt,connector:Bt,query:Wt,...jt}=et;return jt}function connectMutationOptions(et){return{mutationFn(o){return connect$1(et,o)},mutationKey:["connect"]}}function disconnectMutationOptions(et){return{mutationFn(o){return disconnect(et,o)},mutationKey:["disconnect"]}}function getBalanceQueryOptions(et,o={}){return{async queryFn({queryKey:tt}){const{address:rt,scopeKey:nt,...ot}=tt[1];if(!rt)throw new Error("address is required");return await getBalance(et,{...ot,address:rt})??null},queryKey:getBalanceQueryKey(o)}}function getBalanceQueryKey(et={}){return["balance",filterQueryOptions(et)]}function getBlockNumberQueryOptions(et,o={}){return{gcTime:0,async queryFn({queryKey:tt}){const{scopeKey:rt,...nt}=tt[1];return await getBlockNumber(et,nt)??null},queryKey:getBlockNumberQueryKey(o)}}function getBlockNumberQueryKey(et={}){return["blockNumber",filterQueryOptions(et)]}function getEnsAddressQueryOptions(et,o={}){return{async queryFn({queryKey:tt}){const{name:rt,scopeKey:nt,...ot}=tt[1];if(!rt)throw new Error("name is required");return getEnsAddress(et,{...ot,name:rt})},queryKey:getEnsAddressQueryKey(o)}}function getEnsAddressQueryKey(et={}){return["ensAddress",filterQueryOptions(et)]}function getEnsAvatarQueryOptions(et,o={}){return{async queryFn({queryKey:tt}){const{name:rt,scopeKey:nt,...ot}=tt[1];if(!rt)throw new Error("name is required");return getEnsAvatar(et,{...ot,name:rt})},queryKey:getEnsAvatarQueryKey(o)}}function getEnsAvatarQueryKey(et={}){return["ensAvatar",filterQueryOptions(et)]}function getEnsNameQueryOptions(et,o={}){return{async queryFn({queryKey:tt}){const{address:rt,scopeKey:nt,...ot}=tt[1];if(!rt)throw new Error("address is required");return getEnsName(et,{...ot,address:rt})},queryKey:getEnsNameQueryKey(o)}}function getEnsNameQueryKey(et={}){return["ensName",filterQueryOptions(et)]}function signMessageMutationOptions(et){return{mutationFn(o){return signMessage(et,o)},mutationKey:["signMessage"]}}function switchChainMutationOptions(et){return{mutationFn(o){return switchChain(et,o)},mutationKey:["switchChain"]}}var QueryClientContext=reactExports.createContext(void 0),useQueryClient=et=>{const o=reactExports.useContext(QueryClientContext);if(!o)throw new Error("No QueryClient set, use QueryClientProvider to set one");return o},QueryClientProvider=({client:et,children:o})=>(reactExports.useEffect(()=>(et.mount(),()=>{et.unmount()}),[et]),jsxRuntimeExports.jsx(QueryClientContext.Provider,{value:et,children:o})),IsRestoringContext=reactExports.createContext(!1),useIsRestoring=()=>reactExports.useContext(IsRestoringContext);IsRestoringContext.Provider;function createValue(){let et=!1;return{clearReset:()=>{et=!1},reset:()=>{et=!0},isReset:()=>et}}var QueryErrorResetBoundaryContext=reactExports.createContext(createValue()),useQueryErrorResetBoundary=()=>reactExports.useContext(QueryErrorResetBoundaryContext);function shouldThrowError(et,o){return typeof et=="function"?et(...o):!!et}function noop$3(){}var ensurePreventErrorBoundaryRetry=(et,o)=>{(et.suspense||et.throwOnError)&&(o.isReset()||(et.retryOnMount=!1))},useClearResetErrorBoundary=et=>{reactExports.useEffect(()=>{et.clearReset()},[et])},getHasError=({result:et,errorResetBoundary:o,throwOnError:tt,query:rt})=>et.isError&&!o.isReset()&&!et.isFetching&&rt&&shouldThrowError(tt,[et.error,rt]),ensureSuspenseTimers=et=>{et.suspense&&(et.staleTime===void 0&&(et.staleTime=1e3),typeof et.gcTime=="number"&&(et.gcTime=Math.max(et.gcTime,1e3)))},willFetch=(et,o)=>et.isLoading&&et.isFetching&&!o,shouldSuspend=(et,o)=>(et==null?void 0:et.suspense)&&o.isPending,fetchOptimistic=(et,o,tt)=>o.fetchOptimistic(et).catch(()=>{tt.clearReset()});function useBaseQuery(et,o,tt){var lt,dt,ht,mt,ft;const rt=useQueryClient(),nt=useIsRestoring(),ot=useQueryErrorResetBoundary(),it=rt.defaultQueryOptions(et);(dt=(lt=rt.getDefaultOptions().queries)==null?void 0:lt._experimental_beforeQuery)==null||dt.call(lt,it),it._optimisticResults=nt?"isRestoring":"optimistic",ensureSuspenseTimers(it),ensurePreventErrorBoundaryRetry(it,ot),useClearResetErrorBoundary(ot);const st=!rt.getQueryCache().get(it.queryHash),[at]=reactExports.useState(()=>new o(rt,it)),ct=at.getOptimisticResult(it);if(reactExports.useSyncExternalStore(reactExports.useCallback(pt=>{const gt=nt?()=>{}:at.subscribe(notifyManager.batchCalls(pt));return at.updateResult(),gt},[at,nt]),()=>at.getCurrentResult(),()=>at.getCurrentResult()),reactExports.useEffect(()=>{at.setOptions(it,{listeners:!1})},[it,at]),shouldSuspend(it,ct))throw fetchOptimistic(it,at,ot);if(getHasError({result:ct,errorResetBoundary:ot,throwOnError:it.throwOnError,query:rt.getQueryCache().get(it.queryHash)}))throw ct.error;if((mt=(ht=rt.getDefaultOptions().queries)==null?void 0:ht._experimental_afterQuery)==null||mt.call(ht,it,ct),it.experimental_prefetchInRender&&!isServer&&willFetch(ct,nt)){const pt=st?fetchOptimistic(it,at,ot):(ft=rt.getQueryCache().get(it.queryHash))==null?void 0:ft.promise;pt==null||pt.catch(noop$3).finally(()=>{at.hasListeners()||at.updateResult()})}return it.notifyOnChangeProps?ct:at.trackResult(ct)}function useQuery$1(et,o){return useBaseQuery(et,QueryObserver)}function useMutation(et,o){const tt=useQueryClient(),[rt]=reactExports.useState(()=>new MutationObserver$1(tt,et));reactExports.useEffect(()=>{rt.setOptions(et)},[rt,et]);const nt=reactExports.useSyncExternalStore(reactExports.useCallback(it=>rt.subscribe(notifyManager.batchCalls(it)),[rt]),()=>rt.getCurrentResult(),()=>rt.getCurrentResult()),ot=reactExports.useCallback((it,st)=>{rt.mutate(it,st).catch(noop$3)},[rt]);if(nt.error&&shouldThrowError(rt.options.throwOnError,[nt.error]))throw nt.error;return{...nt,mutate:ot,mutateAsync:nt.mutate}}function useQuery(et){const o=useQuery$1({...et,queryKeyHashFn:hashFn});return o.queryKey=et.queryKey,o}function useChainId(et={}){const o=useConfig(et);return reactExports.useSyncExternalStore(tt=>watchChainId(o,{onChange:tt}),()=>getChainId(o),()=>getChainId(o))}function useBalance(et={}){const{address:o,query:tt={}}=et,rt=useConfig(et),nt=useChainId({config:rt}),ot=getBalanceQueryOptions(rt,{...et,chainId:et.chainId??nt}),it=!!(o&&(tt.enabled??!0));return useQuery({...tt,...ot,enabled:it})}function useWatchBlockNumber(et={}){const{enabled:o=!0,onBlockNumber:tt,config:rt,...nt}=et,ot=useConfig(et),it=useChainId({config:ot}),st=et.chainId??it;reactExports.useEffect(()=>{if(o&&tt)return watchBlockNumber(ot,{...nt,chainId:st,onBlockNumber:tt})},[st,ot,o,tt,nt.onError,nt.emitMissed,nt.emitOnBegin,nt.poll,nt.pollingInterval,nt.syncConnectedChain])}function useBlockNumber(et={}){const{query:o={},watch:tt}=et,rt=useConfig(et),nt=useQueryClient(),ot=useChainId({config:rt}),it=et.chainId??ot,st=getBlockNumberQueryOptions(rt,{...et,chainId:it});return useWatchBlockNumber({config:et.config,chainId:et.chainId,...typeof tt=="object"?tt:{},enabled:!!((o.enabled??!0)&&(typeof tt=="object"?tt.enabled:tt)),onBlockNumber(at){nt.setQueryData(st.queryKey,at)}}),useQuery({...o,...st})}function useChains$1(et={}){const o=useConfig(et);return reactExports.useSyncExternalStore(tt=>watchChains(o,{onChange:tt}),()=>getChains(o),()=>getChains(o))}function useConnectors$1(et={}){const o=useConfig(et);return reactExports.useSyncExternalStore(tt=>watchConnectors(o,{onChange:tt}),()=>getConnectors(o),()=>getConnectors(o))}function useConnect$1(et={}){const{mutation:o}=et,tt=useConfig(et),rt=connectMutationOptions(tt),{mutate:nt,mutateAsync:ot,...it}=useMutation({...o,...rt});return reactExports.useEffect(()=>tt.subscribe(({status:st})=>st,(st,at)=>{at==="connected"&&st==="disconnected"&&it.reset()}),[tt,it.reset]),{...it,connect:nt,connectAsync:ot,connectors:useConnectors$1({config:tt})}}function useConnections(et={}){const o=useConfig(et);return reactExports.useSyncExternalStore(tt=>watchConnections(o,{onChange:tt}),()=>getConnections(o),()=>getConnections(o))}function useDisconnect(et={}){const{mutation:o}=et,tt=useConfig(et),rt=disconnectMutationOptions(tt),{mutate:nt,mutateAsync:ot,...it}=useMutation({...o,...rt});return{...it,connectors:useConnections({config:tt}).map(st=>st.connector),disconnect:nt,disconnectAsync:ot}}function useEnsAddress(et={}){const{name:o,query:tt={}}=et,rt=useConfig(et),nt=useChainId({config:rt}),ot=getEnsAddressQueryOptions(rt,{...et,chainId:et.chainId??nt}),it=!!(o&&(tt.enabled??!0));return useQuery({...tt,...ot,enabled:it})}function useEnsAvatar(et={}){const{name:o,query:tt={}}=et,rt=useConfig(et),nt=useChainId({config:rt}),ot=getEnsAvatarQueryOptions(rt,{...et,chainId:et.chainId??nt}),it=!!(o&&(tt.enabled??!0));return useQuery({...tt,...ot,enabled:it})}function useEnsName(et={}){const{address:o,query:tt={}}=et,rt=useConfig(et),nt=useChainId({config:rt}),ot=getEnsNameQueryOptions(rt,{...et,chainId:et.chainId??nt}),it=!!(o&&(tt.enabled??!0));return useQuery({...tt,...ot,enabled:it})}function useSignMessage(et={}){const{mutation:o}=et,tt=useConfig(et),rt=signMessageMutationOptions(tt),{mutate:nt,mutateAsync:ot,...it}=useMutation({...o,...rt});return{...it,signMessage:nt,signMessageAsync:ot}}function useSwitchChain(et={}){const{mutation:o}=et,tt=useConfig(et),rt=switchChainMutationOptions(tt),{mutate:nt,mutateAsync:ot,...it}=useMutation({...o,...rt});return{...it,chains:useChains$1({config:tt}),switchChain:nt,switchChainAsync:ot}}const contracts={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},formatters={block:defineBlock({format(et){var tt;return{transactions:(tt=et.transactions)==null?void 0:tt.map(rt=>{if(typeof rt=="string")return rt;const nt=formatTransaction(rt);return nt.typeHex==="0x7e"&&(nt.isSystemTx=rt.isSystemTx,nt.mint=rt.mint?hexToBigInt(rt.mint):void 0,nt.sourceHash=rt.sourceHash,nt.type="deposit"),nt}),stateRoot:et.stateRoot}}}),transaction:defineTransaction({format(et){const o={};return et.type==="0x7e"&&(o.isSystemTx=et.isSystemTx,o.mint=et.mint?hexToBigInt(et.mint):void 0,o.sourceHash=et.sourceHash,o.type="deposit"),o}}),transactionReceipt:defineTransactionReceipt({format(et){return{l1GasPrice:et.l1GasPrice?hexToBigInt(et.l1GasPrice):null,l1GasUsed:et.l1GasUsed?hexToBigInt(et.l1GasUsed):null,l1Fee:et.l1Fee?hexToBigInt(et.l1Fee):null,l1FeeScalar:et.l1FeeScalar?Number(et.l1FeeScalar):null}}})};function serializeTransaction(et,o){return isDeposit(et)?serializeTransactionDeposit(et):serializeTransaction$1(et,o)}const serializers={transaction:serializeTransaction};function serializeTransactionDeposit(et){assertTransactionDeposit(et);const{sourceHash:o,data:tt,from:rt,gas:nt,isSystemTx:ot,mint:it,to:st,value:at}=et,ct=[o,rt,st??"0x",it?toHex(it):"0x",at?toHex(at):"0x",nt?toHex(nt):"0x",ot?"0x1":"0x",tt??"0x"];return concatHex(["0x7e",toRlp(ct)])}function isDeposit(et){return et.type==="deposit"||typeof et.sourceHash<"u"}function assertTransactionDeposit(et){const{from:o,to:tt}=et;if(o&&!isAddress(o))throw new InvalidAddressError({address:o});if(tt&&!isAddress(tt))throw new InvalidAddressError({address:tt})}const chainConfig={contracts,formatters,serializers},arbitrum=defineChain({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),mainnet=defineChain({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://cloudflare-eth.com"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),sourceId=1,optimism=defineChain({...chainConfig,id:10,name:"OP Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io"]}},blockExplorers:{default:{name:"Optimism Explorer",url:"https://optimistic.etherscan.io",apiUrl:"https://api-optimistic.etherscan.io/api"}},contracts:{...chainConfig.contracts,disputeGameFactory:{[sourceId]:{address:"0xe5965Ab5962eDc7477C8520243A95517CD252fA9"}},l2OutputOracle:{[sourceId]:{address:"0xdfe97868233d1aa22e815a266982f2cf17685a27"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:4286263},portal:{[sourceId]:{address:"0xbEb5Fc579115071764c7423A4f12eDde41f106Ed"}},l1StandardBridge:{[sourceId]:{address:"0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1"}}},sourceId}),polygon=defineChain({id:137,name:"Polygon",nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-rpc.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com",apiUrl:"https://api.polygonscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:25770160}}});coinbaseWallet.type="coinbaseWallet";function coinbaseWallet(et={}){return et.version==="3"||et.headlessMode?version3(et):version4(et)}function version4(et){let o,tt,rt,nt,ot;return it=>({id:"coinbaseWalletSDK",name:"Coinbase Wallet",supportsSimulation:!0,type:coinbaseWallet.type,async connect({chainId:st}={}){try{const at=await this.getProvider(),ct=(await at.request({method:"eth_requestAccounts"})).map(dt=>getAddress(dt));rt||(rt=this.onAccountsChanged.bind(this),at.on("accountsChanged",rt)),nt||(nt=this.onChainChanged.bind(this),at.on("chainChanged",nt)),ot||(ot=this.onDisconnect.bind(this),at.on("disconnect",ot));let lt=await this.getChainId();if(st&<!==st){const dt=await this.switchChain({chainId:st}).catch(ht=>{if(ht.code===UserRejectedRequestError.code)throw ht;return{id:lt}});lt=(dt==null?void 0:dt.id)??lt}return{accounts:ct,chainId:lt}}catch(at){throw/(user closed modal|accounts received is empty|user denied account|request rejected)/i.test(at.message)?new UserRejectedRequestError(at):at}},async disconnect(){var at;const st=await this.getProvider();rt&&(st.removeListener("accountsChanged",rt),rt=void 0),nt&&(st.removeListener("chainChanged",nt),nt=void 0),ot&&(st.removeListener("disconnect",ot),ot=void 0),st.disconnect(),(at=st.close)==null||at.call(st)},async getAccounts(){return(await(await this.getProvider()).request({method:"eth_accounts"})).map(at=>getAddress(at))},async getChainId(){const at=await(await this.getProvider()).request({method:"eth_chainId"});return Number(at)},async getProvider(){if(!tt){const st=await(async()=>{const{default:at}=await __vitePreload(async()=>{const{default:ct}=await import("./index-D2uqR4Ry.js").then(lt=>lt.i);return{default:ct}},__vite__mapDeps([0,1,2,3]));return typeof at!="function"&&typeof at.default=="function"?at.default:at})();o=new st({...et,appChainIds:it.chains.map(at=>at.id)}),tt=o.makeWeb3Provider({...et,options:et.preference??"all"})}return tt},async isAuthorized(){try{return!!(await this.getAccounts()).length}catch{return!1}},async switchChain({addEthereumChainParameter:st,chainId:at}){var dt,ht,mt,ft;const ct=it.chains.find(pt=>pt.id===at);if(!ct)throw new SwitchChainError(new ChainNotConfiguredError);const lt=await this.getProvider();try{return await lt.request({method:"wallet_switchEthereumChain",params:[{chainId:numberToHex(ct.id)}]}),ct}catch(pt){if(pt.code===4902)try{let gt;st!=null&&st.blockExplorerUrls?gt=st.blockExplorerUrls:gt=(dt=ct.blockExplorers)!=null&&dt.default.url?[(ht=ct.blockExplorers)==null?void 0:ht.default.url]:[];let yt;(mt=st==null?void 0:st.rpcUrls)!=null&&mt.length?yt=st.rpcUrls:yt=[((ft=ct.rpcUrls.default)==null?void 0:ft.http[0])??""];const bt={blockExplorerUrls:gt,chainId:numberToHex(at),chainName:(st==null?void 0:st.chainName)??ct.name,iconUrls:st==null?void 0:st.iconUrls,nativeCurrency:(st==null?void 0:st.nativeCurrency)??ct.nativeCurrency,rpcUrls:yt};return await lt.request({method:"wallet_addEthereumChain",params:[bt]}),ct}catch(gt){throw new UserRejectedRequestError(gt)}throw new SwitchChainError(pt)}},onAccountsChanged(st){st.length===0?this.onDisconnect():it.emitter.emit("change",{accounts:st.map(at=>getAddress(at))})},onChainChanged(st){const at=Number(st);it.emitter.emit("change",{chainId:at})},async onDisconnect(st){it.emitter.emit("disconnect");const at=await this.getProvider();rt&&(at.removeListener("accountsChanged",rt),rt=void 0),nt&&(at.removeListener("chainChanged",nt),nt=void 0),ot&&(at.removeListener("disconnect",ot),ot=void 0)}})}function version3(et){let tt,rt,nt,ot,it;return st=>({id:"coinbaseWalletSDK",name:"Coinbase Wallet",supportsSimulation:!0,type:coinbaseWallet.type,async connect({chainId:at}={}){try{const ct=await this.getProvider(),lt=(await ct.request({method:"eth_requestAccounts"})).map(ht=>getAddress(ht));nt||(nt=this.onAccountsChanged.bind(this),ct.on("accountsChanged",nt)),ot||(ot=this.onChainChanged.bind(this),ct.on("chainChanged",ot)),it||(it=this.onDisconnect.bind(this),ct.on("disconnect",it));let dt=await this.getChainId();if(at&&dt!==at){const ht=await this.switchChain({chainId:at}).catch(mt=>{if(mt.code===UserRejectedRequestError.code)throw mt;return{id:dt}});dt=(ht==null?void 0:ht.id)??dt}return{accounts:lt,chainId:dt}}catch(ct){throw/(user closed modal|accounts received is empty|user denied account)/i.test(ct.message)?new UserRejectedRequestError(ct):ct}},async disconnect(){const at=await this.getProvider();nt&&(at.removeListener("accountsChanged",nt),nt=void 0),ot&&(at.removeListener("chainChanged",ot),ot=void 0),it&&(at.removeListener("disconnect",it),it=void 0),at.disconnect(),at.close()},async getAccounts(){return(await(await this.getProvider()).request({method:"eth_accounts"})).map(ct=>getAddress(ct))},async getChainId(){const ct=await(await this.getProvider()).request({method:"eth_chainId"});return Number(ct)},async getProvider(){var at;if(!rt){const ct=await(async()=>{const{default:ft}=await __vitePreload(async()=>{const{default:pt}=await import("./index-FH8NN1-S.js").then(gt=>gt.i);return{default:pt}},__vite__mapDeps([4,3,1,2]));return typeof ft!="function"&&typeof ft.default=="function"?ft.default:ft})();tt=new ct({...et,reloadOnDisconnect:!1});const lt=(at=tt.walletExtension)==null?void 0:at.getChainId(),dt=st.chains.find(ft=>et.chainId?ft.id===et.chainId:ft.id===lt)||st.chains[0],ht=et.chainId||(dt==null?void 0:dt.id),mt=et.jsonRpcUrl||(dt==null?void 0:dt.rpcUrls.default.http[0]);rt=tt.makeWeb3Provider(mt,ht)}return rt},async isAuthorized(){try{return!!(await this.getAccounts()).length}catch{return!1}},async switchChain({addEthereumChainParameter:at,chainId:ct}){var ht,mt,ft,pt;const lt=st.chains.find(gt=>gt.id===ct);if(!lt)throw new SwitchChainError(new ChainNotConfiguredError);const dt=await this.getProvider();try{return await dt.request({method:"wallet_switchEthereumChain",params:[{chainId:numberToHex(lt.id)}]}),lt}catch(gt){if(gt.code===4902)try{let yt;at!=null&&at.blockExplorerUrls?yt=at.blockExplorerUrls:yt=(ht=lt.blockExplorers)!=null&&ht.default.url?[(mt=lt.blockExplorers)==null?void 0:mt.default.url]:[];let bt;(ft=at==null?void 0:at.rpcUrls)!=null&&ft.length?bt=at.rpcUrls:bt=[((pt=lt.rpcUrls.default)==null?void 0:pt.http[0])??""];const xt={blockExplorerUrls:yt,chainId:numberToHex(ct),chainName:(at==null?void 0:at.chainName)??lt.name,iconUrls:at==null?void 0:at.iconUrls,nativeCurrency:(at==null?void 0:at.nativeCurrency)??lt.nativeCurrency,rpcUrls:bt};return await dt.request({method:"wallet_addEthereumChain",params:[xt]}),lt}catch(yt){throw new UserRejectedRequestError(yt)}throw new SwitchChainError(gt)}},onAccountsChanged(at){at.length===0?this.onDisconnect():st.emitter.emit("change",{accounts:at.map(ct=>getAddress(ct))})},onChainChanged(at){const ct=Number(at);st.emitter.emit("change",{chainId:ct})},async onDisconnect(at){st.emitter.emit("disconnect");const ct=await this.getProvider();nt&&(ct.removeListener("accountsChanged",nt),nt=void 0),ot&&(ct.removeListener("chainChanged",ot),ot=void 0),it&&(ct.removeListener("disconnect",it),it=void 0)}})}safe.type="safe";function safe(et={}){const{shimDisconnect:o=!1}=et;let tt,rt;return nt=>({id:"safe",name:"Safe",type:safe.type,async connect(){var at;const ot=await this.getProvider();if(!ot)throw new ProviderNotFoundError;const it=await this.getAccounts(),st=await this.getChainId();return rt||(rt=this.onDisconnect.bind(this),ot.on("disconnect",rt)),o&&await((at=nt.storage)==null?void 0:at.removeItem("safe.disconnected")),{accounts:it,chainId:st}},async disconnect(){var it;const ot=await this.getProvider();if(!ot)throw new ProviderNotFoundError;rt&&(ot.removeListener("disconnect",rt),rt=void 0),o&&await((it=nt.storage)==null?void 0:it.setItem("safe.disconnected",!0))},async getAccounts(){const ot=await this.getProvider();if(!ot)throw new ProviderNotFoundError;return(await ot.request({method:"eth_accounts"})).map(getAddress)},async getProvider(){if(typeof window<"u"&&(window==null?void 0:window.parent)!==window){if(!tt){const{default:it}=await __vitePreload(async()=>{const{default:lt}=await import("./index-Rg7xls9w.js");return{default:lt}},[]),st=new it(et),at=await withTimeout(()=>st.safe.getInfo(),{timeout:et.unstable_getInfoTimeout??10});if(!at)throw new Error("Could not load Safe information");const{SafeAppProvider:ct}=await __vitePreload(async()=>{const{SafeAppProvider:lt}=await import("./index-Dz_NkDRB.js").then(dt=>dt.i);return{SafeAppProvider:lt}},__vite__mapDeps([5,2]));tt=new ct(at,st)}return tt}},async getChainId(){const ot=await this.getProvider();if(!ot)throw new ProviderNotFoundError;return Number(ot.chainId)},async isAuthorized(){var ot;try{return o&&await((ot=nt.storage)==null?void 0:ot.getItem("safe.disconnected"))?!1:!!(await this.getAccounts()).length}catch{return!1}},onAccountsChanged(){},onChainChanged(){},onDisconnect(){nt.emitter.emit("disconnect")}})}walletConnect.type="walletConnect";function walletConnect(et){const o=et.isNewChainsStale??!0;let tt,rt;const nt="eip155";let ot,it,st,at,ct,lt;return dt=>({id:"walletConnect",name:"WalletConnect",type:walletConnect.type,async setup(){const ht=await this.getProvider().catch(()=>null);ht&&(st||(st=this.onConnect.bind(this),ht.on("connect",st)),ct||(ct=this.onSessionDelete.bind(this),ht.on("session_delete",ct)))},async connect({chainId:ht,...mt}={}){var ft,pt;try{const gt=await this.getProvider();if(!gt)throw new ProviderNotFoundError;at||(at=this.onDisplayUri,gt.on("display_uri",at));let yt=ht;if(!yt){const Et=await((ft=dt.storage)==null?void 0:ft.getItem("state"))??{};dt.chains.some(St=>St.id===Et.chainId)?yt=Et.chainId:yt=(pt=dt.chains[0])==null?void 0:pt.id}if(!yt)throw new Error("No chains found on connector.");const bt=await this.isChainsStale();if(gt.session&&bt&&await gt.disconnect(),!gt.session||bt){const Et=dt.chains.filter(Ct=>Ct.id!==yt).map(Ct=>Ct.id);await gt.connect({optionalChains:[yt,...Et],..."pairingTopic"in mt?{pairingTopic:mt.pairingTopic}:{}}),this.setRequestedChainsIds(dt.chains.map(Ct=>Ct.id))}const xt=(await gt.enable()).map(Et=>getAddress(Et)),vt=await this.getChainId();return at&&(gt.removeListener("display_uri",at),at=void 0),st&&(gt.removeListener("connect",st),st=void 0),ot||(ot=this.onAccountsChanged.bind(this),gt.on("accountsChanged",ot)),it||(it=this.onChainChanged.bind(this),gt.on("chainChanged",it)),lt||(lt=this.onDisconnect.bind(this),gt.on("disconnect",lt)),ct||(ct=this.onSessionDelete.bind(this),gt.on("session_delete",ct)),{accounts:xt,chainId:vt}}catch(gt){throw/(user rejected|connection request reset)/i.test(gt==null?void 0:gt.message)?new UserRejectedRequestError(gt):gt}},async disconnect(){const ht=await this.getProvider();try{await(ht==null?void 0:ht.disconnect())}catch(mt){if(!/No matching key/i.test(mt.message))throw mt}finally{it&&(ht==null||ht.removeListener("chainChanged",it),it=void 0),lt&&(ht==null||ht.removeListener("disconnect",lt),lt=void 0),st||(st=this.onConnect.bind(this),ht==null||ht.on("connect",st)),ot&&(ht==null||ht.removeListener("accountsChanged",ot),ot=void 0),ct&&(ht==null||ht.removeListener("session_delete",ct),ct=void 0),this.setRequestedChainsIds([])}},async getAccounts(){return(await this.getProvider()).accounts.map(mt=>getAddress(mt))},async getProvider({chainId:ht}={}){var ft;async function mt(){const pt=dt.chains.map(yt=>yt.id);if(!pt.length)return;const{EthereumProvider:gt}=await __vitePreload(async()=>{const{EthereumProvider:yt}=await import("./index.es-KLKTVizS.js");return{EthereumProvider:yt}},__vite__mapDeps([6,2,3]));return await gt.init({...et,disableProviderPing:!0,optionalChains:pt,projectId:et.projectId,rpcMap:Object.fromEntries(dt.chains.map(yt=>{const[bt]=extractRpcUrls({chain:yt,transports:dt.transports});return[yt.id,bt]})),showQrModal:et.showQrModal??!0})}return tt||(rt||(rt=mt()),tt=await rt,tt==null||tt.events.setMaxListeners(Number.POSITIVE_INFINITY)),ht&&await((ft=this.switchChain)==null?void 0:ft.call(this,{chainId:ht})),tt},async getChainId(){return(await this.getProvider()).chainId},async isAuthorized(){try{const[ht,mt]=await Promise.all([this.getAccounts(),this.getProvider()]);return ht.length?await this.isChainsStale()&&mt.session?(await mt.disconnect().catch(()=>{}),!1):!0:!1}catch{return!1}},async switchChain({addEthereumChainParameter:ht,chainId:mt}){var gt,yt,bt;const ft=await this.getProvider();if(!ft)throw new ProviderNotFoundError;const pt=dt.chains.find(xt=>xt.id===mt);if(!pt)throw new SwitchChainError(new ChainNotConfiguredError);try{await Promise.all([new Promise(vt=>{const Et=({chainId:Ct})=>{Ct===mt&&(dt.emitter.off("change",Et),vt())};dt.emitter.on("change",Et)}),ft.request({method:"wallet_switchEthereumChain",params:[{chainId:numberToHex(mt)}]})]);const xt=await this.getRequestedChainsIds();return this.setRequestedChainsIds([...xt,mt]),pt}catch(xt){const vt=xt;if(/(user rejected)/i.test(vt.message))throw new UserRejectedRequestError(vt);try{let Et;ht!=null&&ht.blockExplorerUrls?Et=ht.blockExplorerUrls:Et=(gt=pt.blockExplorers)!=null&>.default.url?[(yt=pt.blockExplorers)==null?void 0:yt.default.url]:[];let Ct;(bt=ht==null?void 0:ht.rpcUrls)!=null&&bt.length?Ct=ht.rpcUrls:Ct=[...pt.rpcUrls.default.http];const St={blockExplorerUrls:Et,chainId:numberToHex(mt),chainName:(ht==null?void 0:ht.chainName)??pt.name,iconUrls:ht==null?void 0:ht.iconUrls,nativeCurrency:(ht==null?void 0:ht.nativeCurrency)??pt.nativeCurrency,rpcUrls:Ct};await ft.request({method:"wallet_addEthereumChain",params:[St]});const At=await this.getRequestedChainsIds();return this.setRequestedChainsIds([...At,mt]),pt}catch(Et){throw new UserRejectedRequestError(Et)}}},onAccountsChanged(ht){ht.length===0?this.onDisconnect():dt.emitter.emit("change",{accounts:ht.map(mt=>getAddress(mt))})},onChainChanged(ht){const mt=Number(ht);dt.emitter.emit("change",{chainId:mt})},async onConnect(ht){const mt=Number(ht.chainId),ft=await this.getAccounts();dt.emitter.emit("connect",{accounts:ft,chainId:mt})},async onDisconnect(ht){this.setRequestedChainsIds([]),dt.emitter.emit("disconnect");const mt=await this.getProvider();ot&&(mt.removeListener("accountsChanged",ot),ot=void 0),it&&(mt.removeListener("chainChanged",it),it=void 0),lt&&(mt.removeListener("disconnect",lt),lt=void 0),ct&&(mt.removeListener("session_delete",ct),ct=void 0),st||(st=this.onConnect.bind(this),mt.on("connect",st))},onDisplayUri(ht){dt.emitter.emit("message",{type:"display_uri",data:ht})},onSessionDelete(){this.onDisconnect()},getNamespaceChainsIds(){var mt,ft,pt;return tt?((pt=(ft=(mt=tt.session)==null?void 0:mt.namespaces[nt])==null?void 0:ft.accounts)==null?void 0:pt.map(gt=>Number.parseInt(gt.split(":")[1]||"")))??[]:[]},async getRequestedChainsIds(){var ht;return await((ht=dt.storage)==null?void 0:ht.getItem(this.requestedChainsStorageKey))??[]},async isChainsStale(){if(!o)return!1;const ht=dt.chains.map(pt=>pt.id),mt=this.getNamespaceChainsIds();if(mt.length&&!mt.some(pt=>ht.includes(pt)))return!1;const ft=await this.getRequestedChainsIds();return!ht.every(pt=>ft.includes(pt))},async setRequestedChainsIds(ht){var mt;await((mt=dt.storage)==null?void 0:mt.setItem(this.requestedChainsStorageKey,ht))},get requestedChainsStorageKey(){return`${this.id}.requestedChains`}})}var __spreadArray$1=function(et,o,tt){if(tt||arguments.length===2)for(var rt=0,nt=o.length,ot;rt"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new ReactNativeInfo:typeof navigator<"u"?parseUserAgent(navigator.userAgent):getNodeVersion()}function matchUserAgent(et){return et!==""&&userAgentRules.reduce(function(o,tt){var rt=tt[0],nt=tt[1];if(o)return o;var ot=nt.exec(et);return!!ot&&[rt,ot]},!1)}function parseUserAgent(et){var o=matchUserAgent(et);if(!o)return null;var tt=o[0],rt=o[1];if(tt==="searchbot")return new BotInfo;var nt=rt[1]&&rt[1].split(".").join("_").split("_").slice(0,3);nt?nt.length0)throw new Error("Invalid string. Length must be a multiple of 4");var tt=et.indexOf("=");tt===-1&&(tt=o);var rt=tt===o?0:4-tt%4;return[tt,rt]}function byteLength(et){var o=getLens(et),tt=o[0],rt=o[1];return(tt+rt)*3/4-rt}function _byteLength(et,o,tt){return(o+tt)*3/4-tt}function toByteArray(et){var o,tt=getLens(et),rt=tt[0],nt=tt[1],ot=new Arr(_byteLength(et,rt,nt)),it=0,st=nt>0?rt-4:rt,at;for(at=0;at>16&255,ot[it++]=o>>8&255,ot[it++]=o&255;return nt===2&&(o=revLookup[et.charCodeAt(at)]<<2|revLookup[et.charCodeAt(at+1)]>>4,ot[it++]=o&255),nt===1&&(o=revLookup[et.charCodeAt(at)]<<10|revLookup[et.charCodeAt(at+1)]<<4|revLookup[et.charCodeAt(at+2)]>>2,ot[it++]=o>>8&255,ot[it++]=o&255),ot}function tripletToBase64(et){return lookup[et>>18&63]+lookup[et>>12&63]+lookup[et>>6&63]+lookup[et&63]}function encodeChunk(et,o,tt){for(var rt,nt=[],ot=o;otst?st:it+ot));return rt===1?(o=et[tt-1],nt.push(lookup[o>>2]+lookup[o<<4&63]+"==")):rt===2&&(o=(et[tt-2]<<8)+et[tt-1],nt.push(lookup[o>>10]+lookup[o>>4&63]+lookup[o<<2&63]+"=")),nt.join("")}var ieee754={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ieee754.read=function(et,o,tt,rt,nt){var ot,it,st=nt*8-rt-1,at=(1<>1,lt=-7,dt=tt?nt-1:0,ht=tt?-1:1,mt=et[o+dt];for(dt+=ht,ot=mt&(1<<-lt)-1,mt>>=-lt,lt+=st;lt>0;ot=ot*256+et[o+dt],dt+=ht,lt-=8);for(it=ot&(1<<-lt)-1,ot>>=-lt,lt+=rt;lt>0;it=it*256+et[o+dt],dt+=ht,lt-=8);if(ot===0)ot=1-ct;else{if(ot===at)return it?NaN:(mt?-1:1)*(1/0);it=it+Math.pow(2,rt),ot=ot-ct}return(mt?-1:1)*it*Math.pow(2,ot-rt)};ieee754.write=function(et,o,tt,rt,nt,ot){var it,st,at,ct=ot*8-nt-1,lt=(1<>1,ht=nt===23?Math.pow(2,-24)-Math.pow(2,-77):0,mt=rt?0:ot-1,ft=rt?1:-1,pt=o<0||o===0&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(st=isNaN(o)?1:0,it=lt):(it=Math.floor(Math.log(o)/Math.LN2),o*(at=Math.pow(2,-it))<1&&(it--,at*=2),it+dt>=1?o+=ht/at:o+=ht*Math.pow(2,1-dt),o*at>=2&&(it++,at/=2),it+dt>=lt?(st=0,it=lt):it+dt>=1?(st=(o*at-1)*Math.pow(2,nt),it=it+dt):(st=o*Math.pow(2,dt-1)*Math.pow(2,nt),it=0));nt>=8;et[tt+mt]=st&255,mt+=ft,st/=256,nt-=8);for(it=it<0;et[tt+mt]=it&255,mt+=ft,it/=256,ct-=8);et[tt+mt-ft]|=pt*128};/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */(function(et){const o=base64Js,tt=ieee754,rt=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;et.Buffer=st,et.SlowBuffer=bt,et.INSPECT_MAX_BYTES=50;const nt=2147483647;et.kMaxLength=nt,st.TYPED_ARRAY_SUPPORT=ot(),!st.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function ot(){try{const Tt=new Uint8Array(1),$t={foo:function(){return 42}};return Object.setPrototypeOf($t,Uint8Array.prototype),Object.setPrototypeOf(Tt,$t),Tt.foo()===42}catch{return!1}}Object.defineProperty(st.prototype,"parent",{enumerable:!0,get:function(){if(st.isBuffer(this))return this.buffer}}),Object.defineProperty(st.prototype,"offset",{enumerable:!0,get:function(){if(st.isBuffer(this))return this.byteOffset}});function it(Tt){if(Tt>nt)throw new RangeError('The value "'+Tt+'" is invalid for option "size"');const $t=new Uint8Array(Tt);return Object.setPrototypeOf($t,st.prototype),$t}function st(Tt,$t,_t){if(typeof Tt=="number"){if(typeof $t=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return dt(Tt)}return at(Tt,$t,_t)}st.poolSize=8192;function at(Tt,$t,_t){if(typeof Tt=="string")return ht(Tt,$t);if(ArrayBuffer.isView(Tt))return ft(Tt);if(Tt==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Tt);if(_r(Tt,ArrayBuffer)||Tt&&_r(Tt.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(_r(Tt,SharedArrayBuffer)||Tt&&_r(Tt.buffer,SharedArrayBuffer)))return pt(Tt,$t,_t);if(typeof Tt=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const Dt=Tt.valueOf&&Tt.valueOf();if(Dt!=null&&Dt!==Tt)return st.from(Dt,$t,_t);const qt=gt(Tt);if(qt)return qt;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof Tt[Symbol.toPrimitive]=="function")return st.from(Tt[Symbol.toPrimitive]("string"),$t,_t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Tt)}st.from=function(Tt,$t,_t){return at(Tt,$t,_t)},Object.setPrototypeOf(st.prototype,Uint8Array.prototype),Object.setPrototypeOf(st,Uint8Array);function ct(Tt){if(typeof Tt!="number")throw new TypeError('"size" argument must be of type number');if(Tt<0)throw new RangeError('The value "'+Tt+'" is invalid for option "size"')}function lt(Tt,$t,_t){return ct(Tt),Tt<=0?it(Tt):$t!==void 0?typeof _t=="string"?it(Tt).fill($t,_t):it(Tt).fill($t):it(Tt)}st.alloc=function(Tt,$t,_t){return lt(Tt,$t,_t)};function dt(Tt){return ct(Tt),it(Tt<0?0:yt(Tt)|0)}st.allocUnsafe=function(Tt){return dt(Tt)},st.allocUnsafeSlow=function(Tt){return dt(Tt)};function ht(Tt,$t){if((typeof $t!="string"||$t==="")&&($t="utf8"),!st.isEncoding($t))throw new TypeError("Unknown encoding: "+$t);const _t=xt(Tt,$t)|0;let Dt=it(_t);const qt=Dt.write(Tt,$t);return qt!==_t&&(Dt=Dt.slice(0,qt)),Dt}function mt(Tt){const $t=Tt.length<0?0:yt(Tt.length)|0,_t=it($t);for(let Dt=0;Dt<$t;Dt+=1)_t[Dt]=Tt[Dt]&255;return _t}function ft(Tt){if(_r(Tt,Uint8Array)){const $t=new Uint8Array(Tt);return pt($t.buffer,$t.byteOffset,$t.byteLength)}return mt(Tt)}function pt(Tt,$t,_t){if($t<0||Tt.byteLength<$t)throw new RangeError('"offset" is outside of buffer bounds');if(Tt.byteLength<$t+(_t||0))throw new RangeError('"length" is outside of buffer bounds');let Dt;return $t===void 0&&_t===void 0?Dt=new Uint8Array(Tt):_t===void 0?Dt=new Uint8Array(Tt,$t):Dt=new Uint8Array(Tt,$t,_t),Object.setPrototypeOf(Dt,st.prototype),Dt}function gt(Tt){if(st.isBuffer(Tt)){const $t=yt(Tt.length)|0,_t=it($t);return _t.length===0||Tt.copy(_t,0,0,$t),_t}if(Tt.length!==void 0)return typeof Tt.length!="number"||Rr(Tt.length)?it(0):mt(Tt);if(Tt.type==="Buffer"&&Array.isArray(Tt.data))return mt(Tt.data)}function yt(Tt){if(Tt>=nt)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+nt.toString(16)+" bytes");return Tt|0}function bt(Tt){return+Tt!=Tt&&(Tt=0),st.alloc(+Tt)}st.isBuffer=function($t){return $t!=null&&$t._isBuffer===!0&&$t!==st.prototype},st.compare=function($t,_t){if(_r($t,Uint8Array)&&($t=st.from($t,$t.offset,$t.byteLength)),_r(_t,Uint8Array)&&(_t=st.from(_t,_t.offset,_t.byteLength)),!st.isBuffer($t)||!st.isBuffer(_t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if($t===_t)return 0;let Dt=$t.length,qt=_t.length;for(let er=0,sr=Math.min(Dt,qt);erqt.length?(st.isBuffer(sr)||(sr=st.from(sr)),sr.copy(qt,er)):Uint8Array.prototype.set.call(qt,sr,er);else if(st.isBuffer(sr))sr.copy(qt,er);else throw new TypeError('"list" argument must be an Array of Buffers');er+=sr.length}return qt};function xt(Tt,$t){if(st.isBuffer(Tt))return Tt.length;if(ArrayBuffer.isView(Tt)||_r(Tt,ArrayBuffer))return Tt.byteLength;if(typeof Tt!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof Tt);const _t=Tt.length,Dt=arguments.length>2&&arguments[2]===!0;if(!Dt&&_t===0)return 0;let qt=!1;for(;;)switch($t){case"ascii":case"latin1":case"binary":return _t;case"utf8":case"utf-8":return cr(Tt).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _t*2;case"hex":return _t>>>1;case"base64":return gr(Tt).length;default:if(qt)return Dt?-1:cr(Tt).length;$t=(""+$t).toLowerCase(),qt=!0}}st.byteLength=xt;function vt(Tt,$t,_t){let Dt=!1;if(($t===void 0||$t<0)&&($t=0),$t>this.length||((_t===void 0||_t>this.length)&&(_t=this.length),_t<=0)||(_t>>>=0,$t>>>=0,_t<=$t))return"";for(Tt||(Tt="utf8");;)switch(Tt){case"hex":return Wt(this,$t,_t);case"utf8":case"utf-8":return Ft(this,$t,_t);case"ascii":return Vt(this,$t,_t);case"latin1":case"binary":return Bt(this,$t,_t);case"base64":return Yt(this,$t,_t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return jt(this,$t,_t);default:if(Dt)throw new TypeError("Unknown encoding: "+Tt);Tt=(Tt+"").toLowerCase(),Dt=!0}}st.prototype._isBuffer=!0;function Et(Tt,$t,_t){const Dt=Tt[$t];Tt[$t]=Tt[_t],Tt[_t]=Dt}st.prototype.swap16=function(){const $t=this.length;if($t%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _t=0;_t<$t;_t+=2)Et(this,_t,_t+1);return this},st.prototype.swap32=function(){const $t=this.length;if($t%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _t=0;_t<$t;_t+=4)Et(this,_t,_t+3),Et(this,_t+1,_t+2);return this},st.prototype.swap64=function(){const $t=this.length;if($t%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _t=0;_t<$t;_t+=8)Et(this,_t,_t+7),Et(this,_t+1,_t+6),Et(this,_t+2,_t+5),Et(this,_t+3,_t+4);return this},st.prototype.toString=function(){const $t=this.length;return $t===0?"":arguments.length===0?Ft(this,0,$t):vt.apply(this,arguments)},st.prototype.toLocaleString=st.prototype.toString,st.prototype.equals=function($t){if(!st.isBuffer($t))throw new TypeError("Argument must be a Buffer");return this===$t?!0:st.compare(this,$t)===0},st.prototype.inspect=function(){let $t="";const _t=et.INSPECT_MAX_BYTES;return $t=this.toString("hex",0,_t).replace(/(.{2})/g,"$1 ").trim(),this.length>_t&&($t+=" ... "),""},rt&&(st.prototype[rt]=st.prototype.inspect),st.prototype.compare=function($t,_t,Dt,qt,er){if(_r($t,Uint8Array)&&($t=st.from($t,$t.offset,$t.byteLength)),!st.isBuffer($t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof $t);if(_t===void 0&&(_t=0),Dt===void 0&&(Dt=$t?$t.length:0),qt===void 0&&(qt=0),er===void 0&&(er=this.length),_t<0||Dt>$t.length||qt<0||er>this.length)throw new RangeError("out of range index");if(qt>=er&&_t>=Dt)return 0;if(qt>=er)return-1;if(_t>=Dt)return 1;if(_t>>>=0,Dt>>>=0,qt>>>=0,er>>>=0,this===$t)return 0;let sr=er-qt,br=Dt-_t;const Ar=Math.min(sr,br),xr=this.slice(qt,er),Sr=$t.slice(_t,Dt);for(let vr=0;vr2147483647?_t=2147483647:_t<-2147483648&&(_t=-2147483648),_t=+_t,Rr(_t)&&(_t=qt?0:Tt.length-1),_t<0&&(_t=Tt.length+_t),_t>=Tt.length){if(qt)return-1;_t=Tt.length-1}else if(_t<0)if(qt)_t=0;else return-1;if(typeof $t=="string"&&($t=st.from($t,Dt)),st.isBuffer($t))return $t.length===0?-1:St(Tt,$t,_t,Dt,qt);if(typeof $t=="number")return $t=$t&255,typeof Uint8Array.prototype.indexOf=="function"?qt?Uint8Array.prototype.indexOf.call(Tt,$t,_t):Uint8Array.prototype.lastIndexOf.call(Tt,$t,_t):St(Tt,[$t],_t,Dt,qt);throw new TypeError("val must be string, number or Buffer")}function St(Tt,$t,_t,Dt,qt){let er=1,sr=Tt.length,br=$t.length;if(Dt!==void 0&&(Dt=String(Dt).toLowerCase(),Dt==="ucs2"||Dt==="ucs-2"||Dt==="utf16le"||Dt==="utf-16le")){if(Tt.length<2||$t.length<2)return-1;er=2,sr/=2,br/=2,_t/=2}function Ar(Sr,vr){return er===1?Sr[vr]:Sr.readUInt16BE(vr*er)}let xr;if(qt){let Sr=-1;for(xr=_t;xrsr&&(_t=sr-br),xr=_t;xr>=0;xr--){let Sr=!0;for(let vr=0;vrqt&&(Dt=qt)):Dt=qt;const er=$t.length;Dt>er/2&&(Dt=er/2);let sr;for(sr=0;sr>>0,isFinite(Dt)?(Dt=Dt>>>0,qt===void 0&&(qt="utf8")):(qt=Dt,Dt=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const er=this.length-_t;if((Dt===void 0||Dt>er)&&(Dt=er),$t.length>0&&(Dt<0||_t<0)||_t>this.length)throw new RangeError("Attempt to write outside buffer bounds");qt||(qt="utf8");let sr=!1;for(;;)switch(qt){case"hex":return At(this,$t,_t,Dt);case"utf8":case"utf-8":return kt(this,$t,_t,Dt);case"ascii":case"latin1":case"binary":return It(this,$t,_t,Dt);case"base64":return Ot(this,$t,_t,Dt);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Nt(this,$t,_t,Dt);default:if(sr)throw new TypeError("Unknown encoding: "+qt);qt=(""+qt).toLowerCase(),sr=!0}},st.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Yt(Tt,$t,_t){return $t===0&&_t===Tt.length?o.fromByteArray(Tt):o.fromByteArray(Tt.slice($t,_t))}function Ft(Tt,$t,_t){_t=Math.min(Tt.length,_t);const Dt=[];let qt=$t;for(;qt<_t;){const er=Tt[qt];let sr=null,br=er>239?4:er>223?3:er>191?2:1;if(qt+br<=_t){let Ar,xr,Sr,vr;switch(br){case 1:er<128&&(sr=er);break;case 2:Ar=Tt[qt+1],(Ar&192)===128&&(vr=(er&31)<<6|Ar&63,vr>127&&(sr=vr));break;case 3:Ar=Tt[qt+1],xr=Tt[qt+2],(Ar&192)===128&&(xr&192)===128&&(vr=(er&15)<<12|(Ar&63)<<6|xr&63,vr>2047&&(vr<55296||vr>57343)&&(sr=vr));break;case 4:Ar=Tt[qt+1],xr=Tt[qt+2],Sr=Tt[qt+3],(Ar&192)===128&&(xr&192)===128&&(Sr&192)===128&&(vr=(er&15)<<18|(Ar&63)<<12|(xr&63)<<6|Sr&63,vr>65535&&vr<1114112&&(sr=vr))}}sr===null?(sr=65533,br=1):sr>65535&&(sr-=65536,Dt.push(sr>>>10&1023|55296),sr=56320|sr&1023),Dt.push(sr),qt+=br}return Qt(Dt)}const Ht=4096;function Qt(Tt){const $t=Tt.length;if($t<=Ht)return String.fromCharCode.apply(String,Tt);let _t="",Dt=0;for(;Dt<$t;)_t+=String.fromCharCode.apply(String,Tt.slice(Dt,Dt+=Ht));return _t}function Vt(Tt,$t,_t){let Dt="";_t=Math.min(Tt.length,_t);for(let qt=$t;qt<_t;++qt)Dt+=String.fromCharCode(Tt[qt]&127);return Dt}function Bt(Tt,$t,_t){let Dt="";_t=Math.min(Tt.length,_t);for(let qt=$t;qt<_t;++qt)Dt+=String.fromCharCode(Tt[qt]);return Dt}function Wt(Tt,$t,_t){const Dt=Tt.length;(!$t||$t<0)&&($t=0),(!_t||_t<0||_t>Dt)&&(_t=Dt);let qt="";for(let er=$t;er<_t;++er)qt+=mr[Tt[er]];return qt}function jt(Tt,$t,_t){const Dt=Tt.slice($t,_t);let qt="";for(let er=0;erDt&&($t=Dt),_t<0?(_t+=Dt,_t<0&&(_t=0)):_t>Dt&&(_t=Dt),_t<$t&&(_t=$t);const qt=this.subarray($t,_t);return Object.setPrototypeOf(qt,st.prototype),qt};function Xt(Tt,$t,_t){if(Tt%1!==0||Tt<0)throw new RangeError("offset is not uint");if(Tt+$t>_t)throw new RangeError("Trying to access beyond buffer length")}st.prototype.readUintLE=st.prototype.readUIntLE=function($t,_t,Dt){$t=$t>>>0,_t=_t>>>0,Dt||Xt($t,_t,this.length);let qt=this[$t],er=1,sr=0;for(;++sr<_t&&(er*=256);)qt+=this[$t+sr]*er;return qt},st.prototype.readUintBE=st.prototype.readUIntBE=function($t,_t,Dt){$t=$t>>>0,_t=_t>>>0,Dt||Xt($t,_t,this.length);let qt=this[$t+--_t],er=1;for(;_t>0&&(er*=256);)qt+=this[$t+--_t]*er;return qt},st.prototype.readUint8=st.prototype.readUInt8=function($t,_t){return $t=$t>>>0,_t||Xt($t,1,this.length),this[$t]},st.prototype.readUint16LE=st.prototype.readUInt16LE=function($t,_t){return $t=$t>>>0,_t||Xt($t,2,this.length),this[$t]|this[$t+1]<<8},st.prototype.readUint16BE=st.prototype.readUInt16BE=function($t,_t){return $t=$t>>>0,_t||Xt($t,2,this.length),this[$t]<<8|this[$t+1]},st.prototype.readUint32LE=st.prototype.readUInt32LE=function($t,_t){return $t=$t>>>0,_t||Xt($t,4,this.length),(this[$t]|this[$t+1]<<8|this[$t+2]<<16)+this[$t+3]*16777216},st.prototype.readUint32BE=st.prototype.readUInt32BE=function($t,_t){return $t=$t>>>0,_t||Xt($t,4,this.length),this[$t]*16777216+(this[$t+1]<<16|this[$t+2]<<8|this[$t+3])},st.prototype.readBigUInt64LE=wr(function($t){$t=$t>>>0,Zt($t,"offset");const _t=this[$t],Dt=this[$t+7];(_t===void 0||Dt===void 0)&&nr($t,this.length-8);const qt=_t+this[++$t]*2**8+this[++$t]*2**16+this[++$t]*2**24,er=this[++$t]+this[++$t]*2**8+this[++$t]*2**16+Dt*2**24;return BigInt(qt)+(BigInt(er)<>>0,Zt($t,"offset");const _t=this[$t],Dt=this[$t+7];(_t===void 0||Dt===void 0)&&nr($t,this.length-8);const qt=_t*2**24+this[++$t]*2**16+this[++$t]*2**8+this[++$t],er=this[++$t]*2**24+this[++$t]*2**16+this[++$t]*2**8+Dt;return(BigInt(qt)<>>0,_t=_t>>>0,Dt||Xt($t,_t,this.length);let qt=this[$t],er=1,sr=0;for(;++sr<_t&&(er*=256);)qt+=this[$t+sr]*er;return er*=128,qt>=er&&(qt-=Math.pow(2,8*_t)),qt},st.prototype.readIntBE=function($t,_t,Dt){$t=$t>>>0,_t=_t>>>0,Dt||Xt($t,_t,this.length);let qt=_t,er=1,sr=this[$t+--qt];for(;qt>0&&(er*=256);)sr+=this[$t+--qt]*er;return er*=128,sr>=er&&(sr-=Math.pow(2,8*_t)),sr},st.prototype.readInt8=function($t,_t){return $t=$t>>>0,_t||Xt($t,1,this.length),this[$t]&128?(255-this[$t]+1)*-1:this[$t]},st.prototype.readInt16LE=function($t,_t){$t=$t>>>0,_t||Xt($t,2,this.length);const Dt=this[$t]|this[$t+1]<<8;return Dt&32768?Dt|4294901760:Dt},st.prototype.readInt16BE=function($t,_t){$t=$t>>>0,_t||Xt($t,2,this.length);const Dt=this[$t+1]|this[$t]<<8;return Dt&32768?Dt|4294901760:Dt},st.prototype.readInt32LE=function($t,_t){return $t=$t>>>0,_t||Xt($t,4,this.length),this[$t]|this[$t+1]<<8|this[$t+2]<<16|this[$t+3]<<24},st.prototype.readInt32BE=function($t,_t){return $t=$t>>>0,_t||Xt($t,4,this.length),this[$t]<<24|this[$t+1]<<16|this[$t+2]<<8|this[$t+3]},st.prototype.readBigInt64LE=wr(function($t){$t=$t>>>0,Zt($t,"offset");const _t=this[$t],Dt=this[$t+7];(_t===void 0||Dt===void 0)&&nr($t,this.length-8);const qt=this[$t+4]+this[$t+5]*2**8+this[$t+6]*2**16+(Dt<<24);return(BigInt(qt)<>>0,Zt($t,"offset");const _t=this[$t],Dt=this[$t+7];(_t===void 0||Dt===void 0)&&nr($t,this.length-8);const qt=(_t<<24)+this[++$t]*2**16+this[++$t]*2**8+this[++$t];return(BigInt(qt)<>>0,_t||Xt($t,4,this.length),tt.read(this,$t,!0,23,4)},st.prototype.readFloatBE=function($t,_t){return $t=$t>>>0,_t||Xt($t,4,this.length),tt.read(this,$t,!1,23,4)},st.prototype.readDoubleLE=function($t,_t){return $t=$t>>>0,_t||Xt($t,8,this.length),tt.read(this,$t,!0,52,8)},st.prototype.readDoubleBE=function($t,_t){return $t=$t>>>0,_t||Xt($t,8,this.length),tt.read(this,$t,!1,52,8)};function Kt(Tt,$t,_t,Dt,qt,er){if(!st.isBuffer(Tt))throw new TypeError('"buffer" argument must be a Buffer instance');if($t>qt||$tTt.length)throw new RangeError("Index out of range")}st.prototype.writeUintLE=st.prototype.writeUIntLE=function($t,_t,Dt,qt){if($t=+$t,_t=_t>>>0,Dt=Dt>>>0,!qt){const br=Math.pow(2,8*Dt)-1;Kt(this,$t,_t,Dt,br,0)}let er=1,sr=0;for(this[_t]=$t&255;++sr>>0,Dt=Dt>>>0,!qt){const br=Math.pow(2,8*Dt)-1;Kt(this,$t,_t,Dt,br,0)}let er=Dt-1,sr=1;for(this[_t+er]=$t&255;--er>=0&&(sr*=256);)this[_t+er]=$t/sr&255;return _t+Dt},st.prototype.writeUint8=st.prototype.writeUInt8=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,1,255,0),this[_t]=$t&255,_t+1},st.prototype.writeUint16LE=st.prototype.writeUInt16LE=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,2,65535,0),this[_t]=$t&255,this[_t+1]=$t>>>8,_t+2},st.prototype.writeUint16BE=st.prototype.writeUInt16BE=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,2,65535,0),this[_t]=$t>>>8,this[_t+1]=$t&255,_t+2},st.prototype.writeUint32LE=st.prototype.writeUInt32LE=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,4,4294967295,0),this[_t+3]=$t>>>24,this[_t+2]=$t>>>16,this[_t+1]=$t>>>8,this[_t]=$t&255,_t+4},st.prototype.writeUint32BE=st.prototype.writeUInt32BE=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,4,4294967295,0),this[_t]=$t>>>24,this[_t+1]=$t>>>16,this[_t+2]=$t>>>8,this[_t+3]=$t&255,_t+4};function Pt(Tt,$t,_t,Dt,qt){Ut($t,Dt,qt,Tt,_t,7);let er=Number($t&BigInt(4294967295));Tt[_t++]=er,er=er>>8,Tt[_t++]=er,er=er>>8,Tt[_t++]=er,er=er>>8,Tt[_t++]=er;let sr=Number($t>>BigInt(32)&BigInt(4294967295));return Tt[_t++]=sr,sr=sr>>8,Tt[_t++]=sr,sr=sr>>8,Tt[_t++]=sr,sr=sr>>8,Tt[_t++]=sr,_t}function Gt(Tt,$t,_t,Dt,qt){Ut($t,Dt,qt,Tt,_t,7);let er=Number($t&BigInt(4294967295));Tt[_t+7]=er,er=er>>8,Tt[_t+6]=er,er=er>>8,Tt[_t+5]=er,er=er>>8,Tt[_t+4]=er;let sr=Number($t>>BigInt(32)&BigInt(4294967295));return Tt[_t+3]=sr,sr=sr>>8,Tt[_t+2]=sr,sr=sr>>8,Tt[_t+1]=sr,sr=sr>>8,Tt[_t]=sr,_t+8}st.prototype.writeBigUInt64LE=wr(function($t,_t=0){return Pt(this,$t,_t,BigInt(0),BigInt("0xffffffffffffffff"))}),st.prototype.writeBigUInt64BE=wr(function($t,_t=0){return Gt(this,$t,_t,BigInt(0),BigInt("0xffffffffffffffff"))}),st.prototype.writeIntLE=function($t,_t,Dt,qt){if($t=+$t,_t=_t>>>0,!qt){const Ar=Math.pow(2,8*Dt-1);Kt(this,$t,_t,Dt,Ar-1,-Ar)}let er=0,sr=1,br=0;for(this[_t]=$t&255;++er>0)-br&255;return _t+Dt},st.prototype.writeIntBE=function($t,_t,Dt,qt){if($t=+$t,_t=_t>>>0,!qt){const Ar=Math.pow(2,8*Dt-1);Kt(this,$t,_t,Dt,Ar-1,-Ar)}let er=Dt-1,sr=1,br=0;for(this[_t+er]=$t&255;--er>=0&&(sr*=256);)$t<0&&br===0&&this[_t+er+1]!==0&&(br=1),this[_t+er]=($t/sr>>0)-br&255;return _t+Dt},st.prototype.writeInt8=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,1,127,-128),$t<0&&($t=255+$t+1),this[_t]=$t&255,_t+1},st.prototype.writeInt16LE=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,2,32767,-32768),this[_t]=$t&255,this[_t+1]=$t>>>8,_t+2},st.prototype.writeInt16BE=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,2,32767,-32768),this[_t]=$t>>>8,this[_t+1]=$t&255,_t+2},st.prototype.writeInt32LE=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,4,2147483647,-2147483648),this[_t]=$t&255,this[_t+1]=$t>>>8,this[_t+2]=$t>>>16,this[_t+3]=$t>>>24,_t+4},st.prototype.writeInt32BE=function($t,_t,Dt){return $t=+$t,_t=_t>>>0,Dt||Kt(this,$t,_t,4,2147483647,-2147483648),$t<0&&($t=4294967295+$t+1),this[_t]=$t>>>24,this[_t+1]=$t>>>16,this[_t+2]=$t>>>8,this[_t+3]=$t&255,_t+4},st.prototype.writeBigInt64LE=wr(function($t,_t=0){return Pt(this,$t,_t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),st.prototype.writeBigInt64BE=wr(function($t,_t=0){return Gt(this,$t,_t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function tr(Tt,$t,_t,Dt,qt,er){if(_t+Dt>Tt.length)throw new RangeError("Index out of range");if(_t<0)throw new RangeError("Index out of range")}function zt(Tt,$t,_t,Dt,qt){return $t=+$t,_t=_t>>>0,qt||tr(Tt,$t,_t,4),tt.write(Tt,$t,_t,Dt,23,4),_t+4}st.prototype.writeFloatLE=function($t,_t,Dt){return zt(this,$t,_t,!0,Dt)},st.prototype.writeFloatBE=function($t,_t,Dt){return zt(this,$t,_t,!1,Dt)};function lr(Tt,$t,_t,Dt,qt){return $t=+$t,_t=_t>>>0,qt||tr(Tt,$t,_t,8),tt.write(Tt,$t,_t,Dt,52,8),_t+8}st.prototype.writeDoubleLE=function($t,_t,Dt){return lr(this,$t,_t,!0,Dt)},st.prototype.writeDoubleBE=function($t,_t,Dt){return lr(this,$t,_t,!1,Dt)},st.prototype.copy=function($t,_t,Dt,qt){if(!st.isBuffer($t))throw new TypeError("argument should be a Buffer");if(Dt||(Dt=0),!qt&&qt!==0&&(qt=this.length),_t>=$t.length&&(_t=$t.length),_t||(_t=0),qt>0&&qt=this.length)throw new RangeError("Index out of range");if(qt<0)throw new RangeError("sourceEnd out of bounds");qt>this.length&&(qt=this.length),$t.length-_t>>0,Dt=Dt===void 0?this.length:Dt>>>0,$t||($t=0);let er;if(typeof $t=="number")for(er=_t;er2**32?qt=Rt(String(_t)):typeof _t=="bigint"&&(qt=String(_t),(_t>BigInt(2)**BigInt(32)||_t<-(BigInt(2)**BigInt(32)))&&(qt=Rt(qt)),qt+="n"),Dt+=` It must be ${$t}. Received ${qt}`,Dt},RangeError);function Rt(Tt){let $t="",_t=Tt.length;const Dt=Tt[0]==="-"?1:0;for(;_t>=Dt+4;_t-=3)$t=`_${Tt.slice(_t-3,_t)}${$t}`;return`${Tt.slice(0,_t)}${$t}`}function Mt(Tt,$t,_t){Zt($t,"offset"),(Tt[$t]===void 0||Tt[$t+_t]===void 0)&&nr($t,Tt.length-(_t+1))}function Ut(Tt,$t,_t,Dt,qt,er){if(Tt>_t||Tt<$t){const sr=typeof $t=="bigint"?"n":"";let br;throw $t===0||$t===BigInt(0)?br=`>= 0${sr} and < 2${sr} ** ${(er+1)*8}${sr}`:br=`>= -(2${sr} ** ${(er+1)*8-1}${sr}) and < 2 ** ${(er+1)*8-1}${sr}`,new rr.ERR_OUT_OF_RANGE("value",br,Tt)}Mt(Dt,qt,er)}function Zt(Tt,$t){if(typeof Tt!="number")throw new rr.ERR_INVALID_ARG_TYPE($t,"number",Tt)}function nr(Tt,$t,_t){throw Math.floor(Tt)!==Tt?(Zt(Tt,_t),new rr.ERR_OUT_OF_RANGE("offset","an integer",Tt)):$t<0?new rr.ERR_BUFFER_OUT_OF_BOUNDS:new rr.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${$t}`,Tt)}const ar=/[^+/0-9A-Za-z-_]/g;function dr(Tt){if(Tt=Tt.split("=")[0],Tt=Tt.trim().replace(ar,""),Tt.length<2)return"";for(;Tt.length%4!==0;)Tt=Tt+"=";return Tt}function cr(Tt,$t){$t=$t||1/0;let _t;const Dt=Tt.length;let qt=null;const er=[];for(let sr=0;sr55295&&_t<57344){if(!qt){if(_t>56319){($t-=3)>-1&&er.push(239,191,189);continue}else if(sr+1===Dt){($t-=3)>-1&&er.push(239,191,189);continue}qt=_t;continue}if(_t<56320){($t-=3)>-1&&er.push(239,191,189),qt=_t;continue}_t=(qt-55296<<10|_t-56320)+65536}else qt&&($t-=3)>-1&&er.push(239,191,189);if(qt=null,_t<128){if(($t-=1)<0)break;er.push(_t)}else if(_t<2048){if(($t-=2)<0)break;er.push(_t>>6|192,_t&63|128)}else if(_t<65536){if(($t-=3)<0)break;er.push(_t>>12|224,_t>>6&63|128,_t&63|128)}else if(_t<1114112){if(($t-=4)<0)break;er.push(_t>>18|240,_t>>12&63|128,_t>>6&63|128,_t&63|128)}else throw new Error("Invalid code point")}return er}function yr(Tt){const $t=[];for(let _t=0;_t>8,qt=_t%256,er.push(qt),er.push(Dt);return er}function gr(Tt){return o.toByteArray(dr(Tt))}function Pr(Tt,$t,_t,Dt){let qt;for(qt=0;qt=$t.length||qt>=Tt.length);++qt)$t[qt+_t]=Tt[qt];return qt}function _r(Tt,$t){return Tt instanceof $t||Tt!=null&&Tt.constructor!=null&&Tt.constructor.name!=null&&Tt.constructor.name===$t.name}function Rr(Tt){return Tt!==Tt}const mr=function(){const Tt="0123456789abcdef",$t=new Array(256);for(let _t=0;_t<16;++_t){const Dt=_t*16;for(let qt=0;qt<16;++qt)$t[Dt+qt]=Tt[_t]+Tt[qt]}return $t}();function wr(Tt){return typeof BigInt>"u"?ir:Tt}function ir(){throw new Error("BigInt not supported")}})(buffer);var extendStatics=function(et,o){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(tt,rt){tt.__proto__=rt}||function(tt,rt){for(var nt in rt)Object.prototype.hasOwnProperty.call(rt,nt)&&(tt[nt]=rt[nt])},extendStatics(et,o)};function __extends(et,o){if(typeof o!="function"&&o!==null)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");extendStatics(et,o);function tt(){this.constructor=et}et.prototype=o===null?Object.create(o):(tt.prototype=o.prototype,new tt)}var __assign=function(){return __assign=Object.assign||function(o){for(var tt,rt=1,nt=arguments.length;rt=0;st--)(it=et[st])&&(ot=(nt<3?it(ot):nt>3?it(o,tt,ot):it(o,tt))||ot);return nt>3&&ot&&Object.defineProperty(o,tt,ot),ot}function __param(et,o){return function(tt,rt){o(tt,rt,et)}}function __esDecorate(et,o,tt,rt,nt,ot){function it(yt){if(yt!==void 0&&typeof yt!="function")throw new TypeError("Function expected");return yt}for(var st=rt.kind,at=st==="getter"?"get":st==="setter"?"set":"value",ct=!o&&et?rt.static?et:et.prototype:null,lt=o||(ct?Object.getOwnPropertyDescriptor(ct,rt.name):{}),dt,ht=!1,mt=tt.length-1;mt>=0;mt--){var ft={};for(var pt in rt)ft[pt]=pt==="access"?{}:rt[pt];for(var pt in rt.access)ft.access[pt]=rt.access[pt];ft.addInitializer=function(yt){if(ht)throw new TypeError("Cannot add initializers after decoration has completed");ot.push(it(yt||null))};var gt=(0,tt[mt])(st==="accessor"?{get:lt.get,set:lt.set}:lt[at],ft);if(st==="accessor"){if(gt===void 0)continue;if(gt===null||typeof gt!="object")throw new TypeError("Object expected");(dt=it(gt.get))&&(lt.get=dt),(dt=it(gt.set))&&(lt.set=dt),(dt=it(gt.init))&&nt.unshift(dt)}else(dt=it(gt))&&(st==="field"?nt.unshift(dt):lt[at]=dt)}ct&&Object.defineProperty(ct,rt.name,lt),ht=!0}function __runInitializers(et,o,tt){for(var rt=arguments.length>2,nt=0;nt0&&ot[ot.length-1])&&(ct[0]===6||ct[0]===2)){tt=0;continue}if(ct[0]===3&&(!ot||ct[1]>ot[0]&&ct[1]=et.length&&(et=void 0),{value:et&&et[rt++],done:!et}}};throw new TypeError(o?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(et,o){var tt=typeof Symbol=="function"&&et[Symbol.iterator];if(!tt)return et;var rt=tt.call(et),nt,ot=[],it;try{for(;(o===void 0||o-- >0)&&!(nt=rt.next()).done;)ot.push(nt.value)}catch(st){it={error:st}}finally{try{nt&&!nt.done&&(tt=rt.return)&&tt.call(rt)}finally{if(it)throw it.error}}return ot}function __spread(){for(var et=[],o=0;o1||at(mt,pt)})},ft&&(nt[mt]=ft(nt[mt])))}function at(mt,ft){try{ct(rt[mt](ft))}catch(pt){ht(ot[0][3],pt)}}function ct(mt){mt.value instanceof __await?Promise.resolve(mt.value.v).then(lt,dt):ht(ot[0][2],mt)}function lt(mt){at("next",mt)}function dt(mt){at("throw",mt)}function ht(mt,ft){mt(ft),ot.shift(),ot.length&&at(ot[0][0],ot[0][1])}}function __asyncDelegator(et){var o,tt;return o={},rt("next"),rt("throw",function(nt){throw nt}),rt("return"),o[Symbol.iterator]=function(){return this},o;function rt(nt,ot){o[nt]=et[nt]?function(it){return(tt=!tt)?{value:__await(et[nt](it)),done:!1}:ot?ot(it):it}:ot}}function __asyncValues(et){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=et[Symbol.asyncIterator],tt;return o?o.call(et):(et=typeof __values=="function"?__values(et):et[Symbol.iterator](),tt={},rt("next"),rt("throw"),rt("return"),tt[Symbol.asyncIterator]=function(){return this},tt);function rt(ot){tt[ot]=et[ot]&&function(it){return new Promise(function(st,at){it=et[ot](it),nt(st,at,it.done,it.value)})}}function nt(ot,it,st,at){Promise.resolve(at).then(function(ct){ot({value:ct,done:st})},it)}}function __makeTemplateObject(et,o){return Object.defineProperty?Object.defineProperty(et,"raw",{value:o}):et.raw=o,et}var __setModuleDefault=Object.create?function(et,o){Object.defineProperty(et,"default",{enumerable:!0,value:o})}:function(et,o){et.default=o};function __importStar(et){if(et&&et.__esModule)return et;var o={};if(et!=null)for(var tt in et)tt!=="default"&&Object.prototype.hasOwnProperty.call(et,tt)&&__createBinding(o,et,tt);return __setModuleDefault(o,et),o}function __importDefault$1(et){return et&&et.__esModule?et:{default:et}}function __classPrivateFieldGet$1(et,o,tt,rt){if(tt==="a"&&!rt)throw new TypeError("Private accessor was defined without a getter");if(typeof o=="function"?et!==o||!rt:!o.has(et))throw new TypeError("Cannot read private member from an object whose class did not declare it");return tt==="m"?rt:tt==="a"?rt.call(et):rt?rt.value:o.get(et)}function __classPrivateFieldSet$1(et,o,tt,rt,nt){if(rt==="m")throw new TypeError("Private method is not writable");if(rt==="a"&&!nt)throw new TypeError("Private accessor was defined without a setter");if(typeof o=="function"?et!==o||!nt:!o.has(et))throw new TypeError("Cannot write private member to an object whose class did not declare it");return rt==="a"?nt.call(et,tt):nt?nt.value=tt:o.set(et,tt),tt}function __classPrivateFieldIn(et,o){if(o===null||typeof o!="object"&&typeof o!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof et=="function"?o===et:et.has(o)}function __addDisposableResource(et,o,tt){if(o!=null){if(typeof o!="object"&&typeof o!="function")throw new TypeError("Object expected.");var rt,nt;if(tt){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");rt=o[Symbol.asyncDispose]}if(rt===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");rt=o[Symbol.dispose],tt&&(nt=rt)}if(typeof rt!="function")throw new TypeError("Object not disposable.");nt&&(rt=function(){try{nt.call(this)}catch(ot){return Promise.reject(ot)}}),et.stack.push({value:o,dispose:rt,async:tt})}else tt&&et.stack.push({async:!0});return o}var _SuppressedError=typeof SuppressedError=="function"?SuppressedError:function(et,o,tt){var rt=new Error(tt);return rt.name="SuppressedError",rt.error=et,rt.suppressed=o,rt};function __disposeResources(et){function o(ot){et.error=et.hasError?new _SuppressedError(ot,et.error,"An error was suppressed during disposal."):ot,et.hasError=!0}var tt,rt=0;function nt(){for(;tt=et.stack.pop();)try{if(!tt.async&&rt===1)return rt=0,et.stack.push(tt),Promise.resolve().then(nt);if(tt.dispose){var ot=tt.dispose.call(tt.value);if(tt.async)return rt|=2,Promise.resolve(ot).then(nt,function(it){return o(it),nt()})}else rt|=1}catch(it){o(it)}if(rt===1)return et.hasError?Promise.reject(et.error):Promise.resolve();if(et.hasError)throw et.error}return nt()}function __rewriteRelativeImportExtension(et,o){return typeof et=="string"&&/^\.\.?\//.test(et)?et.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(tt,rt,nt,ot,it){return rt?o?".jsx":".js":nt&&(!ot||!it)?tt:nt+ot+"."+it.toLowerCase()+"js"}):et}const tslib_es6={__extends,__assign,__rest,__decorate,__param,__esDecorate,__runInitializers,__propKey,__setFunctionName,__metadata,__awaiter,__generator,__createBinding,__exportStar,__values,__read,__spread,__spreadArrays,__spreadArray,__await,__asyncGenerator,__asyncDelegator,__asyncValues,__makeTemplateObject,__importStar,__importDefault:__importDefault$1,__classPrivateFieldGet:__classPrivateFieldGet$1,__classPrivateFieldSet:__classPrivateFieldSet$1,__classPrivateFieldIn,__addDisposableResource,__disposeResources,__rewriteRelativeImportExtension},tslib_es6$1=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource,get __assign(){return __assign},__asyncDelegator,__asyncGenerator,__asyncValues,__await,__awaiter,__classPrivateFieldGet:__classPrivateFieldGet$1,__classPrivateFieldIn,__classPrivateFieldSet:__classPrivateFieldSet$1,__createBinding,__decorate,__disposeResources,__esDecorate,__exportStar,__extends,__generator,__importDefault:__importDefault$1,__importStar,__makeTemplateObject,__metadata,__param,__propKey,__read,__rest,__rewriteRelativeImportExtension,__runInitializers,__setFunctionName,__spread,__spreadArray,__spreadArrays,__values,default:tslib_es6},Symbol.toStringTag,{value:"Module"}));var define_process_env_default$2={},defaultEnvironment="production",env$2=typeof process>"u"||define_process_env_default$2===void 0?defaultEnvironment:"production",createDefinition=function(et){return{isEnabled:function(o){return et.some(function(tt){return!!o[tt]})}}},featureDefinitions={measureLayout:createDefinition(["layout","layoutId","drag"]),animation:createDefinition(["animate","exit","variants","whileHover","whileTap","whileFocus","whileDrag","whileInView"]),exit:createDefinition(["exit"]),drag:createDefinition(["drag","dragControls"]),focus:createDefinition(["whileFocus"]),hover:createDefinition(["whileHover","onHoverStart","onHoverEnd"]),tap:createDefinition(["whileTap","onTap","onTapStart","onTapCancel"]),pan:createDefinition(["onPan","onPanStart","onPanSessionStart","onPanEnd"]),inView:createDefinition(["whileInView","onViewportEnter","onViewportLeave"])};function loadFeatures(et){for(var o in et)et[o]!==null&&(o==="projectionNodeConstructor"?featureDefinitions.projectionNodeConstructor=et[o]:featureDefinitions[o].Component=et[o])}var invariant$1=function(){},LazyContext=reactExports.createContext({strict:!1}),featureNames=Object.keys(featureDefinitions),numFeatures=featureNames.length;function useFeatures(et,o,tt){var rt=[],nt=reactExports.useContext(LazyContext);if(!o)return null;env$2!=="production"&&tt&&nt.strict;for(var ot=0;ot"u")return o;var tt=new Map;return new Proxy(o,{get:function(rt,nt){return tt.has(nt)||tt.set(nt,o(nt)),tt.get(nt)}})}var lowercaseSVGElements=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","svg","switch","symbol","text","tspan","use","view"];function isSVGComponent(et){return typeof et!="string"||et.includes("-")?!1:!!(lowercaseSVGElements.indexOf(et)>-1||/[A-Z]/.test(et))}var scaleCorrectors={};function addScaleCorrector(et){Object.assign(scaleCorrectors,et)}var transformAxes=["","X","Y","Z"],order$1=["translate","scale","rotate","skew"],transformProps=["transformPerspective","x","y","z"];order$1.forEach(function(et){return transformAxes.forEach(function(o){return transformProps.push(et+o)})});function sortTransformProps(et,o){return transformProps.indexOf(et)-transformProps.indexOf(o)}var transformPropSet=new Set(transformProps);function isTransformProp(et){return transformPropSet.has(et)}var transformOriginProps=new Set(["originX","originY","originZ"]);function isTransformOriginProp(et){return transformOriginProps.has(et)}function isForcedMotionValue(et,o){var tt=o.layout,rt=o.layoutId;return isTransformProp(et)||isTransformOriginProp(et)||(tt||rt!==void 0)&&(!!scaleCorrectors[et]||et==="opacity")}var isMotionValue=function(et){return!!(et!==null&&typeof et=="object"&&et.getVelocity)},translateAlias={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"};function buildTransform(et,o,tt,rt){var nt=et.transform,ot=et.transformKeys,it=o.enableHardwareAcceleration,st=it===void 0?!0:it,at=o.allowTransformNone,ct=at===void 0?!0:at,lt="";ot.sort(sortTransformProps);for(var dt=!1,ht=ot.length,mt=0;mttt=>Math.max(Math.min(tt,o),et),sanitize=et=>et%1?Number(et.toFixed(5)):et,floatRegex=/(-)?([\d]*\.?[\d])+/g,colorRegex=/(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi,singleColorRegex=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i;function isString(et){return typeof et=="string"}const number$3={test:et=>typeof et=="number",parse:parseFloat,transform:et=>et},alpha=Object.assign(Object.assign({},number$3),{transform:clamp$2(0,1)}),scale=Object.assign(Object.assign({},number$3),{default:1}),createUnitType=et=>({test:o=>isString(o)&&o.endsWith(et)&&o.split(" ").length===1,parse:parseFloat,transform:o=>`${o}${et}`}),degrees=createUnitType("deg"),percent=createUnitType("%"),px=createUnitType("px"),vh=createUnitType("vh"),vw=createUnitType("vw"),progressPercentage=Object.assign(Object.assign({},percent),{parse:et=>percent.parse(et)/100,transform:et=>percent.transform(et*100)}),isColorString=(et,o)=>tt=>!!(isString(tt)&&singleColorRegex.test(tt)&&tt.startsWith(et)||o&&Object.prototype.hasOwnProperty.call(tt,o)),splitColor=(et,o,tt)=>rt=>{if(!isString(rt))return rt;const[nt,ot,it,st]=rt.match(floatRegex);return{[et]:parseFloat(nt),[o]:parseFloat(ot),[tt]:parseFloat(it),alpha:st!==void 0?parseFloat(st):1}},hsla={test:isColorString("hsl","hue"),parse:splitColor("hue","saturation","lightness"),transform:({hue:et,saturation:o,lightness:tt,alpha:rt=1})=>"hsla("+Math.round(et)+", "+percent.transform(sanitize(o))+", "+percent.transform(sanitize(tt))+", "+sanitize(alpha.transform(rt))+")"},clampRgbUnit=clamp$2(0,255),rgbUnit=Object.assign(Object.assign({},number$3),{transform:et=>Math.round(clampRgbUnit(et))}),rgba={test:isColorString("rgb","red"),parse:splitColor("red","green","blue"),transform:({red:et,green:o,blue:tt,alpha:rt=1})=>"rgba("+rgbUnit.transform(et)+", "+rgbUnit.transform(o)+", "+rgbUnit.transform(tt)+", "+sanitize(alpha.transform(rt))+")"};function parseHex(et){let o="",tt="",rt="",nt="";return et.length>5?(o=et.substr(1,2),tt=et.substr(3,2),rt=et.substr(5,2),nt=et.substr(7,2)):(o=et.substr(1,1),tt=et.substr(2,1),rt=et.substr(3,1),nt=et.substr(4,1),o+=o,tt+=tt,rt+=rt,nt+=nt),{red:parseInt(o,16),green:parseInt(tt,16),blue:parseInt(rt,16),alpha:nt?parseInt(nt,16)/255:1}}const hex={test:isColorString("#"),parse:parseHex,transform:rgba.transform},color$1={test:et=>rgba.test(et)||hex.test(et)||hsla.test(et),parse:et=>rgba.test(et)?rgba.parse(et):hsla.test(et)?hsla.parse(et):hex.parse(et),transform:et=>isString(et)?et:et.hasOwnProperty("red")?rgba.transform(et):hsla.transform(et)},colorToken="${c}",numberToken="${n}";function test(et){var o,tt,rt,nt;return isNaN(et)&&isString(et)&&((tt=(o=et.match(floatRegex))===null||o===void 0?void 0:o.length)!==null&&tt!==void 0?tt:0)+((nt=(rt=et.match(colorRegex))===null||rt===void 0?void 0:rt.length)!==null&&nt!==void 0?nt:0)>0}function analyse$1(et){typeof et=="number"&&(et=`${et}`);const o=[];let tt=0;const rt=et.match(colorRegex);rt&&(tt=rt.length,et=et.replace(colorRegex,colorToken),o.push(...rt.map(color$1.parse)));const nt=et.match(floatRegex);return nt&&(et=et.replace(floatRegex,numberToken),o.push(...nt.map(number$3.parse))),{values:o,numColors:tt,tokenised:et}}function parse$4(et){return analyse$1(et).values}function createTransformer(et){const{values:o,numColors:tt,tokenised:rt}=analyse$1(et),nt=o.length;return ot=>{let it=rt;for(let st=0;sttypeof et=="number"?0:et;function getAnimatableNone$1(et){const o=parse$4(et);return createTransformer(et)(o.map(convertNumbersToZero))}const complex={test,parse:parse$4,createTransformer,getAnimatableNone:getAnimatableNone$1},maxDefaults=new Set(["brightness","contrast","saturate","opacity"]);function applyDefaultFilter(et){let[o,tt]=et.slice(0,-1).split("(");if(o==="drop-shadow")return et;const[rt]=tt.match(floatRegex)||[];if(!rt)return et;const nt=tt.replace(rt,"");let ot=maxDefaults.has(o)?1:0;return rt!==tt&&(ot*=100),o+"("+ot+nt+")"}const functionRegex=/([a-z-]*)\(.*?\)/g,filter$1=Object.assign(Object.assign({},complex),{getAnimatableNone:et=>{const o=et.match(functionRegex);return o?o.map(applyDefaultFilter).join(" "):et}});var int=__assign(__assign({},number$3),{transform:Math.round}),numberValueTypes={borderWidth:px,borderTopWidth:px,borderRightWidth:px,borderBottomWidth:px,borderLeftWidth:px,borderRadius:px,radius:px,borderTopLeftRadius:px,borderTopRightRadius:px,borderBottomRightRadius:px,borderBottomLeftRadius:px,width:px,maxWidth:px,height:px,maxHeight:px,size:px,top:px,right:px,bottom:px,left:px,padding:px,paddingTop:px,paddingRight:px,paddingBottom:px,paddingLeft:px,margin:px,marginTop:px,marginRight:px,marginBottom:px,marginLeft:px,rotate:degrees,rotateX:degrees,rotateY:degrees,rotateZ:degrees,scale,scaleX:scale,scaleY:scale,scaleZ:scale,skew:degrees,skewX:degrees,skewY:degrees,distance:px,translateX:px,translateY:px,translateZ:px,x:px,y:px,z:px,perspective:px,transformPerspective:px,opacity:alpha,originX:progressPercentage,originY:progressPercentage,originZ:px,zIndex:int,fillOpacity:alpha,strokeOpacity:alpha,numOctaves:int};function buildHTMLStyles(et,o,tt,rt){var nt,ot=et.style,it=et.vars,st=et.transform,at=et.transformKeys,ct=et.transformOrigin;at.length=0;var lt=!1,dt=!1,ht=!0;for(var mt in o){var ft=o[mt];if(isCSSVariable$1(mt)){it[mt]=ft;continue}var pt=numberValueTypes[mt],gt=getValueAsType(ft,pt);if(isTransformProp(mt)){if(lt=!0,st[mt]=gt,at.push(mt),!ht)continue;ft!==((nt=pt.default)!==null&&nt!==void 0?nt:0)&&(ht=!1)}else isTransformOriginProp(mt)?(ct[mt]=gt,dt=!0):ot[mt]=gt}lt?ot.transform=buildTransform(et,tt,ht,rt):rt?ot.transform=rt({},""):!o.transform&&ot.transform&&(ot.transform="none"),dt&&(ot.transformOrigin=buildTransformOrigin(ct))}var createHtmlRenderState=function(){return{style:{},transform:{},transformKeys:[],transformOrigin:{},vars:{}}};function copyRawValuesOnly(et,o,tt){for(var rt in o)!isMotionValue(o[rt])&&!isForcedMotionValue(rt,tt)&&(et[rt]=o[rt])}function useInitialMotionValues(et,o,tt){var rt=et.transformTemplate;return reactExports.useMemo(function(){var nt=createHtmlRenderState();buildHTMLStyles(nt,o,{enableHardwareAcceleration:!tt},rt);var ot=nt.vars,it=nt.style;return __assign(__assign({},ot),it)},[o])}function useStyle(et,o,tt){var rt=et.style||{},nt={};return copyRawValuesOnly(nt,rt,et),Object.assign(nt,useInitialMotionValues(et,o,tt)),et.transformValues&&(nt=et.transformValues(nt)),nt}function useHTMLProps(et,o,tt){var rt={},nt=useStyle(et,o,tt);return et.drag&&et.dragListener!==!1&&(rt.draggable=!1,nt.userSelect=nt.WebkitUserSelect=nt.WebkitTouchCallout="none",nt.touchAction=et.drag===!0?"none":"pan-".concat(et.drag==="x"?"y":"x")),rt.style=nt,rt}var validMotionProps=new Set(["initial","animate","exit","style","variants","transition","transformTemplate","transformValues","custom","inherit","layout","layoutId","layoutDependency","onLayoutAnimationStart","onLayoutAnimationComplete","onLayoutMeasure","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","drag","dragControls","dragListener","dragConstraints","dragDirectionLock","dragSnapToOrigin","_dragX","_dragY","dragElastic","dragMomentum","dragPropagation","dragTransition","whileDrag","onPan","onPanStart","onPanEnd","onPanSessionStart","onTap","onTapStart","onTapCancel","onHoverStart","onHoverEnd","whileFocus","whileTap","whileHover","whileInView","onViewportEnter","onViewportLeave","viewport","layoutScroll"]);function isValidMotionProp(et){return validMotionProps.has(et)}var shouldForward=function(et){return!isValidMotionProp(et)};function loadExternalIsValidProp(et){et&&(shouldForward=function(o){return o.startsWith("on")?!isValidMotionProp(o):et(o)})}try{loadExternalIsValidProp(require("@emotion/is-prop-valid").default)}catch{}function filterProps(et,o,tt){var rt={};for(var nt in et)(shouldForward(nt)||tt===!0&&isValidMotionProp(nt)||!o&&!isValidMotionProp(nt)||et.draggable&&nt.startsWith("onDrag"))&&(rt[nt]=et[nt]);return rt}function calcOrigin$1(et,o,tt){return typeof et=="string"?et:px.transform(o+tt*et)}function calcSVGTransformOrigin(et,o,tt){var rt=calcOrigin$1(o,et.x,et.width),nt=calcOrigin$1(tt,et.y,et.height);return"".concat(rt," ").concat(nt)}var camelKeys={offset:"strokeDashoffset",array:"strokeDasharray"};function buildSVGPath(et,o,tt,rt,nt){tt===void 0&&(tt=1),rt===void 0&&(rt=0),et.pathLength=1;var ot=camelKeys;et[ot.offset]=px.transform(-rt);var it=px.transform(o),st=px.transform(tt);et[ot.array]="".concat(it," ").concat(st)}function buildSVGAttrs(et,o,tt,rt){var nt=o.attrX,ot=o.attrY,it=o.originX,st=o.originY,at=o.pathLength,ct=o.pathSpacing,lt=ct===void 0?1:ct,dt=o.pathOffset,ht=dt===void 0?0:dt,mt=__rest(o,["attrX","attrY","originX","originY","pathLength","pathSpacing","pathOffset"]);buildHTMLStyles(et,mt,tt,rt),et.attrs=et.style,et.style={};var ft=et.attrs,pt=et.style,gt=et.dimensions;ft.transform&&(gt&&(pt.transform=ft.transform),delete ft.transform),gt&&(it!==void 0||st!==void 0||pt.transform)&&(pt.transformOrigin=calcSVGTransformOrigin(gt,it!==void 0?it:.5,st!==void 0?st:.5)),nt!==void 0&&(ft.x=nt),ot!==void 0&&(ft.y=ot),at!==void 0&&buildSVGPath(ft,at,lt,ht)}var createSvgRenderState=function(){return __assign(__assign({},createHtmlRenderState()),{attrs:{}})};function useSVGProps(et,o){var tt=reactExports.useMemo(function(){var nt=createSvgRenderState();return buildSVGAttrs(nt,o,{enableHardwareAcceleration:!1},et.transformTemplate),__assign(__assign({},nt.attrs),{style:__assign({},nt.style)})},[o]);if(et.style){var rt={};copyRawValuesOnly(rt,et.style,et),tt.style=__assign(__assign({},rt),tt.style)}return tt}function createUseRender(et){et===void 0&&(et=!1);var o=function(tt,rt,nt,ot,it,st){var at=it.latestValues,ct=isSVGComponent(tt)?useSVGProps:useHTMLProps,lt=ct(rt,at,st),dt=filterProps(rt,typeof tt=="string",et),ht=__assign(__assign(__assign({},dt),lt),{ref:ot});return nt&&(ht["data-projection-id"]=nt),reactExports.createElement(tt,ht)};return o}var CAMEL_CASE_PATTERN=/([a-z])([A-Z])/g,REPLACE_TEMPLATE="$1-$2",camelToDash=function(et){return et.replace(CAMEL_CASE_PATTERN,REPLACE_TEMPLATE).toLowerCase()};function renderHTML(et,o,tt,rt){var nt=o.style,ot=o.vars;Object.assign(et.style,nt,rt&&rt.getProjectionStyles(tt));for(var it in ot)et.style.setProperty(it,ot[it])}var camelCaseAttributes=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength"]);function renderSVG(et,o,tt,rt){renderHTML(et,o,void 0,rt);for(var nt in o.attrs)et.setAttribute(camelCaseAttributes.has(nt)?nt:camelToDash(nt),o.attrs[nt])}function scrapeMotionValuesFromProps$1(et){var o=et.style,tt={};for(var rt in o)(isMotionValue(o[rt])||isForcedMotionValue(rt,et))&&(tt[rt]=o[rt]);return tt}function scrapeMotionValuesFromProps(et){var o=scrapeMotionValuesFromProps$1(et);for(var tt in et)if(isMotionValue(et[tt])){var rt=tt==="x"||tt==="y"?"attr"+tt.toUpperCase():tt;o[rt]=et[tt]}return o}function isAnimationControls(et){return typeof et=="object"&&typeof et.start=="function"}var isKeyframesTarget=function(et){return Array.isArray(et)},isCustomValue=function(et){return!!(et&&typeof et=="object"&&et.mix&&et.toValue)},resolveFinalValueInKeyframes=function(et){return isKeyframesTarget(et)?et[et.length-1]||0:et};function resolveMotionValue(et){var o=isMotionValue(et)?et.get():et;return isCustomValue(o)?o.toValue():o}function makeState(et,o,tt,rt){var nt=et.scrapeMotionValuesFromProps,ot=et.createRenderState,it=et.onMount,st={latestValues:makeLatestValues(o,tt,rt,nt),renderState:ot()};return it&&(st.mount=function(at){return it(o,at,st)}),st}var makeUseVisualState=function(et){return function(o,tt){var rt=reactExports.useContext(MotionContext),nt=reactExports.useContext(PresenceContext);return tt?makeState(et,o,rt,nt):useConstant(function(){return makeState(et,o,rt,nt)})}};function makeLatestValues(et,o,tt,rt){var nt={},ot=(tt==null?void 0:tt.initial)===!1,it=rt(et);for(var st in it)nt[st]=resolveMotionValue(it[st]);var at=et.initial,ct=et.animate,lt=checkIfControllingVariants(et),dt=checkIfVariantNode(et);o&&dt&&!lt&&et.inherit!==!1&&(at??(at=o.initial),ct??(ct=o.animate));var ht=ot||at===!1,mt=ht?ct:at;if(mt&&typeof mt!="boolean"&&!isAnimationControls(mt)){var ft=Array.isArray(mt)?mt:[mt];ft.forEach(function(pt){var gt=resolveVariantFromProps(et,pt);if(gt){var yt=gt.transitionEnd;gt.transition;var bt=__rest(gt,["transitionEnd","transition"]);for(var xt in bt){var vt=bt[xt];if(Array.isArray(vt)){var Et=ht?vt.length-1:0;vt=vt[Et]}vt!==null&&(nt[xt]=vt)}for(var xt in yt)nt[xt]=yt[xt]}})}return nt}var svgMotionConfig={useVisualState:makeUseVisualState({scrapeMotionValuesFromProps,createRenderState:createSvgRenderState,onMount:function(et,o,tt){var rt=tt.renderState,nt=tt.latestValues;try{rt.dimensions=typeof o.getBBox=="function"?o.getBBox():o.getBoundingClientRect()}catch{rt.dimensions={x:0,y:0,width:0,height:0}}buildSVGAttrs(rt,nt,{enableHardwareAcceleration:!1},et.transformTemplate),renderSVG(o,rt)}})},htmlMotionConfig={useVisualState:makeUseVisualState({scrapeMotionValuesFromProps:scrapeMotionValuesFromProps$1,createRenderState:createHtmlRenderState})};function createDomMotionConfig(et,o,tt,rt,nt){var ot=o.forwardMotionProps,it=ot===void 0?!1:ot,st=isSVGComponent(et)?svgMotionConfig:htmlMotionConfig;return __assign(__assign({},st),{preloadedFeatures:tt,useRender:createUseRender(it),createVisualElement:rt,projectionNodeConstructor:nt,Component:et})}var AnimationType;(function(et){et.Animate="animate",et.Hover="whileHover",et.Tap="whileTap",et.Drag="whileDrag",et.Focus="whileFocus",et.InView="whileInView",et.Exit="exit"})(AnimationType||(AnimationType={}));function addDomEvent(et,o,tt,rt){return rt===void 0&&(rt={passive:!0}),et.addEventListener(o,tt,rt),function(){return et.removeEventListener(o,tt)}}function useDomEvent(et,o,tt,rt){reactExports.useEffect(function(){var nt=et.current;if(tt&&nt)return addDomEvent(nt,o,tt,rt)},[et,o,tt,rt])}function useFocusGesture(et){var o=et.whileFocus,tt=et.visualElement,rt=function(){var ot;(ot=tt.animationState)===null||ot===void 0||ot.setActive(AnimationType.Focus,!0)},nt=function(){var ot;(ot=tt.animationState)===null||ot===void 0||ot.setActive(AnimationType.Focus,!1)};useDomEvent(tt,"focus",o?rt:void 0),useDomEvent(tt,"blur",o?nt:void 0)}function isMouseEvent(et){return typeof PointerEvent<"u"&&et instanceof PointerEvent?et.pointerType==="mouse":et instanceof MouseEvent}function isTouchEvent(et){var o=!!et.touches;return o}function filterPrimaryPointer(et){return function(o){var tt=o instanceof MouseEvent,rt=!tt||tt&&o.button===0;rt&&et(o)}}var defaultPagePoint={pageX:0,pageY:0};function pointFromTouch(et,o){o===void 0&&(o="page");var tt=et.touches[0]||et.changedTouches[0],rt=tt||defaultPagePoint;return{x:rt[o+"X"],y:rt[o+"Y"]}}function pointFromMouse(et,o){return o===void 0&&(o="page"),{x:et[o+"X"],y:et[o+"Y"]}}function extractEventInfo(et,o){return o===void 0&&(o="page"),{point:isTouchEvent(et)?pointFromTouch(et,o):pointFromMouse(et,o)}}var wrapHandler=function(et,o){o===void 0&&(o=!1);var tt=function(rt){return et(rt,extractEventInfo(rt))};return o?filterPrimaryPointer(tt):tt},supportsPointerEvents=function(){return isBrowser$3&&window.onpointerdown===null},supportsTouchEvents=function(){return isBrowser$3&&window.ontouchstart===null},supportsMouseEvents=function(){return isBrowser$3&&window.onmousedown===null},mouseEventNames={pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointercancel:"mousecancel",pointerover:"mouseover",pointerout:"mouseout",pointerenter:"mouseenter",pointerleave:"mouseleave"},touchEventNames={pointerdown:"touchstart",pointermove:"touchmove",pointerup:"touchend",pointercancel:"touchcancel"};function getPointerEventName(et){return supportsPointerEvents()?et:supportsTouchEvents()?touchEventNames[et]:supportsMouseEvents()?mouseEventNames[et]:et}function addPointerEvent(et,o,tt,rt){return addDomEvent(et,getPointerEventName(o),wrapHandler(tt,o==="pointerdown"),rt)}function usePointerEvent(et,o,tt,rt){return useDomEvent(et,getPointerEventName(o),tt&&wrapHandler(tt,o==="pointerdown"),rt)}function createLock(et){var o=null;return function(){var tt=function(){o=null};return o===null?(o=et,tt):!1}}var globalHorizontalLock=createLock("dragHorizontal"),globalVerticalLock=createLock("dragVertical");function getGlobalLock(et){var o=!1;if(et==="y")o=globalVerticalLock();else if(et==="x")o=globalHorizontalLock();else{var tt=globalHorizontalLock(),rt=globalVerticalLock();tt&&rt?o=function(){tt(),rt()}:(tt&&tt(),rt&&rt())}return o}function isDragActive(){var et=getGlobalLock(!0);return et?(et(),!1):!0}function createHoverEvent(et,o,tt){return function(rt,nt){var ot;!isMouseEvent(rt)||isDragActive()||((ot=et.animationState)===null||ot===void 0||ot.setActive(AnimationType.Hover,o),tt==null||tt(rt,nt))}}function useHoverGesture(et){var o=et.onHoverStart,tt=et.onHoverEnd,rt=et.whileHover,nt=et.visualElement;usePointerEvent(nt,"pointerenter",o||rt?createHoverEvent(nt,!0,o):void 0,{passive:!o}),usePointerEvent(nt,"pointerleave",tt||rt?createHoverEvent(nt,!1,tt):void 0,{passive:!tt})}var isNodeOrChild=function(et,o){return o?et===o?!0:isNodeOrChild(et,o.parentElement):!1};function useUnmountEffect(et){return reactExports.useEffect(function(){return function(){return et()}},[])}const clamp$1=(et,o,tt)=>Math.min(Math.max(tt,et),o),safeMin=.001,minDuration=.01,maxDuration=10,minDamping=.05,maxDamping=1;function findSpring({duration:et=800,bounce:o=.25,velocity:tt=0,mass:rt=1}){let nt,ot,it=1-o;it=clamp$1(minDamping,maxDamping,it),et=clamp$1(minDuration,maxDuration,et/1e3),it<1?(nt=ct=>{const lt=ct*it,dt=lt*et,ht=lt-tt,mt=calcAngularFreq(ct,it),ft=Math.exp(-dt);return safeMin-ht/mt*ft},ot=ct=>{const dt=ct*it*et,ht=dt*tt+tt,mt=Math.pow(it,2)*Math.pow(ct,2)*et,ft=Math.exp(-dt),pt=calcAngularFreq(Math.pow(ct,2),it);return(-nt(ct)+safeMin>0?-1:1)*((ht-mt)*ft)/pt}):(nt=ct=>{const lt=Math.exp(-ct*et),dt=(ct-tt)*et+1;return-safeMin+lt*dt},ot=ct=>{const lt=Math.exp(-ct*et),dt=(tt-ct)*(et*et);return lt*dt});const st=5/et,at=approximateRoot(nt,ot,st);if(et=et*1e3,isNaN(at))return{stiffness:100,damping:10,duration:et};{const ct=Math.pow(at,2)*rt;return{stiffness:ct,damping:it*2*Math.sqrt(rt*ct),duration:et}}}const rootIterations=12;function approximateRoot(et,o,tt){let rt=tt;for(let nt=1;ntet[tt]!==void 0)}function getSpringOptions(et){let o=Object.assign({velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1},et);if(!isSpringType(et,physicsKeys)&&isSpringType(et,durationKeys)){const tt=findSpring(et);o=Object.assign(Object.assign(Object.assign({},o),tt),{velocity:0,mass:1}),o.isResolvedFromDuration=!0}return o}function spring(et){var{from:o=0,to:tt=1,restSpeed:rt=2,restDelta:nt}=et,ot=__rest(et,["from","to","restSpeed","restDelta"]);const it={done:!1,value:o};let{stiffness:st,damping:at,mass:ct,velocity:lt,duration:dt,isResolvedFromDuration:ht}=getSpringOptions(ot),mt=zero$1,ft=zero$1;function pt(){const gt=lt?-(lt/1e3):0,yt=tt-o,bt=at/(2*Math.sqrt(st*ct)),xt=Math.sqrt(st/ct)/1e3;if(nt===void 0&&(nt=Math.min(Math.abs(tt-o)/100,.4)),bt<1){const vt=calcAngularFreq(xt,bt);mt=Et=>{const Ct=Math.exp(-bt*xt*Et);return tt-Ct*((gt+bt*xt*yt)/vt*Math.sin(vt*Et)+yt*Math.cos(vt*Et))},ft=Et=>{const Ct=Math.exp(-bt*xt*Et);return bt*xt*Ct*(Math.sin(vt*Et)*(gt+bt*xt*yt)/vt+yt*Math.cos(vt*Et))-Ct*(Math.cos(vt*Et)*(gt+bt*xt*yt)-vt*yt*Math.sin(vt*Et))}}else if(bt===1)mt=vt=>tt-Math.exp(-xt*vt)*(yt+(gt+xt*yt)*vt);else{const vt=xt*Math.sqrt(bt*bt-1);mt=Et=>{const Ct=Math.exp(-bt*xt*Et),St=Math.min(vt*Et,300);return tt-Ct*((gt+bt*xt*yt)*Math.sinh(St)+vt*yt*Math.cosh(St))/vt}}}return pt(),{next:gt=>{const yt=mt(gt);if(ht)it.done=gt>=dt;else{const bt=ft(gt)*1e3,xt=Math.abs(bt)<=rt,vt=Math.abs(tt-yt)<=nt;it.done=xt&&vt}return it.value=it.done?tt:yt,it},flipTarget:()=>{lt=-lt,[o,tt]=[tt,o],pt()}}}spring.needsInterpolation=(et,o)=>typeof et=="string"||typeof o=="string";const zero$1=et=>0,progress=(et,o,tt)=>{const rt=o-et;return rt===0?1:(tt-et)/rt},mix=(et,o,tt)=>-tt*et+tt*o+et;function hueToRgb(et,o,tt){return tt<0&&(tt+=1),tt>1&&(tt-=1),tt<1/6?et+(o-et)*6*tt:tt<1/2?o:tt<2/3?et+(o-et)*(2/3-tt)*6:et}function hslaToRgba({hue:et,saturation:o,lightness:tt,alpha:rt}){et/=360,o/=100,tt/=100;let nt=0,ot=0,it=0;if(!o)nt=ot=it=tt;else{const st=tt<.5?tt*(1+o):tt+o-tt*o,at=2*tt-st;nt=hueToRgb(at,st,et+1/3),ot=hueToRgb(at,st,et),it=hueToRgb(at,st,et-1/3)}return{red:Math.round(nt*255),green:Math.round(ot*255),blue:Math.round(it*255),alpha:rt}}const mixLinearColor=(et,o,tt)=>{const rt=et*et,nt=o*o;return Math.sqrt(Math.max(0,tt*(nt-rt)+rt))},colorTypes=[hex,rgba,hsla],getColorType=et=>colorTypes.find(o=>o.test(et)),mixColor=(et,o)=>{let tt=getColorType(et),rt=getColorType(o),nt=tt.parse(et),ot=rt.parse(o);tt===hsla&&(nt=hslaToRgba(nt),tt=rgba),rt===hsla&&(ot=hslaToRgba(ot),rt=rgba);const it=Object.assign({},nt);return st=>{for(const at in it)at!=="alpha"&&(it[at]=mixLinearColor(nt[at],ot[at],st));return it.alpha=mix(nt.alpha,ot.alpha,st),tt.transform(it)}},isNum=et=>typeof et=="number",combineFunctions=(et,o)=>tt=>o(et(tt)),pipe$1=(...et)=>et.reduce(combineFunctions);function getMixer(et,o){return isNum(et)?tt=>mix(et,o,tt):color$1.test(et)?mixColor(et,o):mixComplex(et,o)}const mixArray=(et,o)=>{const tt=[...et],rt=tt.length,nt=et.map((ot,it)=>getMixer(ot,o[it]));return ot=>{for(let it=0;it{const tt=Object.assign(Object.assign({},et),o),rt={};for(const nt in tt)et[nt]!==void 0&&o[nt]!==void 0&&(rt[nt]=getMixer(et[nt],o[nt]));return nt=>{for(const ot in rt)tt[ot]=rt[ot](nt);return tt}};function analyse(et){const o=complex.parse(et),tt=o.length;let rt=0,nt=0,ot=0;for(let it=0;it{const tt=complex.createTransformer(o),rt=analyse(et),nt=analyse(o);return rt.numHSL===nt.numHSL&&rt.numRGB===nt.numRGB&&rt.numNumbers>=nt.numNumbers?pipe$1(mixArray(rt.parsed,nt.parsed),tt):it=>`${it>0?o:et}`},mixNumber=(et,o)=>tt=>mix(et,o,tt);function detectMixerFactory(et){if(typeof et=="number")return mixNumber;if(typeof et=="string")return color$1.test(et)?mixColor:mixComplex;if(Array.isArray(et))return mixArray;if(typeof et=="object")return mixObject}function createMixers(et,o,tt){const rt=[],nt=tt||detectMixerFactory(et[0]),ot=et.length-1;for(let it=0;ittt(progress(et,o,rt))}function slowInterpolate(et,o){const tt=et.length,rt=tt-1;return nt=>{let ot=0,it=!1;if(nt<=et[0]?it=!0:nt>=et[rt]&&(ot=rt-1,it=!0),!it){let at=1;for(;atnt||at===rt);at++);ot=at-1}const st=progress(et[ot],et[ot+1],nt);return o[ot](st)}}function interpolate(et,o,{clamp:tt=!0,ease:rt,mixer:nt}={}){const ot=et.length;invariant$1(ot===o.length),invariant$1(!rt||!Array.isArray(rt)||rt.length===ot-1),et[0]>et[ot-1]&&(et=[].concat(et),o=[].concat(o),et.reverse(),o.reverse());const it=createMixers(o,rt,nt),st=ot===2?fastInterpolate(et,it):slowInterpolate(et,it);return tt?at=>st(clamp$1(et[0],et[ot-1],at)):st}const reverseEasing=et=>o=>1-et(1-o),mirrorEasing=et=>o=>o<=.5?et(2*o)/2:(2-et(2*(1-o)))/2,createExpoIn=et=>o=>Math.pow(o,et),createBackIn=et=>o=>o*o*((et+1)*o-et),createAnticipate=et=>{const o=createBackIn(et);return tt=>(tt*=2)<1?.5*o(tt):.5*(2-Math.pow(2,-10*(tt-1)))},DEFAULT_OVERSHOOT_STRENGTH=1.525,BOUNCE_FIRST_THRESHOLD=4/11,BOUNCE_SECOND_THRESHOLD=8/11,BOUNCE_THIRD_THRESHOLD=9/10,linear=et=>et,easeIn=createExpoIn(2),easeOut=reverseEasing(easeIn),easeInOut=mirrorEasing(easeIn),circIn=et=>1-Math.sin(Math.acos(et)),circOut=reverseEasing(circIn),circInOut=mirrorEasing(circOut),backIn=createBackIn(DEFAULT_OVERSHOOT_STRENGTH),backOut=reverseEasing(backIn),backInOut=mirrorEasing(backIn),anticipate=createAnticipate(DEFAULT_OVERSHOOT_STRENGTH),ca=4356/361,cb=35442/1805,cc=16061/1805,bounceOut=et=>{if(et===1||et===0)return et;const o=et*et;return etet<.5?.5*(1-bounceOut(1-et*2)):.5*bounceOut(et*2-1)+.5;function defaultEasing(et,o){return et.map(()=>o||easeInOut).splice(0,et.length-1)}function defaultOffset(et){const o=et.length;return et.map((tt,rt)=>rt!==0?rt/(o-1):0)}function convertOffsetToTimes(et,o){return et.map(tt=>tt*o)}function keyframes$1({from:et=0,to:o=1,ease:tt,offset:rt,duration:nt=300}){const ot={done:!1,value:et},it=Array.isArray(o)?o:[et,o],st=convertOffsetToTimes(rt&&rt.length===it.length?rt:defaultOffset(it),nt);function at(){return interpolate(st,it,{ease:Array.isArray(tt)?tt:defaultEasing(it,tt)})}let ct=at();return{next:lt=>(ot.value=ct(lt),ot.done=lt>=nt,ot),flipTarget:()=>{it.reverse(),ct=at()}}}function decay({velocity:et=0,from:o=0,power:tt=.8,timeConstant:rt=350,restDelta:nt=.5,modifyTarget:ot}){const it={done:!1,value:o};let st=tt*et;const at=o+st,ct=ot===void 0?at:ot(at);return ct!==at&&(st=ct-o),{next:lt=>{const dt=-st*Math.exp(-lt/rt);return it.done=!(dt>nt||dt<-nt),it.value=it.done?ct:ct+dt,it},flipTarget:()=>{}}}const types$3={keyframes:keyframes$1,spring,decay};function detectAnimationFromOptions(et){if(Array.isArray(et.to))return keyframes$1;if(types$3[et.type])return types$3[et.type];const o=new Set(Object.keys(et));return o.has("ease")||o.has("duration")&&!o.has("dampingRatio")?keyframes$1:o.has("dampingRatio")||o.has("stiffness")||o.has("mass")||o.has("damping")||o.has("restSpeed")||o.has("restDelta")?spring:keyframes$1}const defaultTimestep=1/60*1e3,getCurrentTime=typeof performance<"u"?()=>performance.now():()=>Date.now(),onNextFrame=typeof window<"u"?et=>window.requestAnimationFrame(et):et=>setTimeout(()=>et(getCurrentTime()),defaultTimestep);function createRenderStep(et){let o=[],tt=[],rt=0,nt=!1,ot=!1;const it=new WeakSet,st={schedule:(at,ct=!1,lt=!1)=>{const dt=lt&&nt,ht=dt?o:tt;return ct&&it.add(at),ht.indexOf(at)===-1&&(ht.push(at),dt&&nt&&(rt=o.length)),at},cancel:at=>{const ct=tt.indexOf(at);ct!==-1&&tt.splice(ct,1),it.delete(at)},process:at=>{if(nt){ot=!0;return}if(nt=!0,[o,tt]=[tt,o],tt.length=0,rt=o.length,rt)for(let ct=0;ct(et[o]=createRenderStep(()=>runNextFrame=!0),et),{}),sync=stepsOrder.reduce((et,o)=>{const tt=steps[o];return et[o]=(rt,nt=!1,ot=!1)=>(runNextFrame||startLoop(),tt.schedule(rt,nt,ot)),et},{}),cancelSync=stepsOrder.reduce((et,o)=>(et[o]=steps[o].cancel,et),{}),flushSync=stepsOrder.reduce((et,o)=>(et[o]=()=>steps[o].process(frame),et),{}),processStep=et=>steps[et].process(frame),processFrame=et=>{runNextFrame=!1,frame.delta=useDefaultElapsed?defaultTimestep:Math.max(Math.min(et-frame.timestamp,maxElapsed),1),frame.timestamp=et,isProcessing=!0,stepsOrder.forEach(processStep),isProcessing=!1,runNextFrame&&(useDefaultElapsed=!1,onNextFrame(processFrame))},startLoop=()=>{runNextFrame=!0,useDefaultElapsed=!0,isProcessing||onNextFrame(processFrame)},getFrameData=()=>frame;function loopElapsed(et,o,tt=0){return et-o-tt}function reverseElapsed(et,o,tt=0,rt=!0){return rt?loopElapsed(o+-et,o,tt):o-(et-o)+tt}function hasRepeatDelayElapsed(et,o,tt,rt){return rt?et>=o+tt:et<=-tt}const framesync=et=>{const o=({delta:tt})=>et(tt);return{start:()=>sync.update(o,!0),stop:()=>cancelSync.update(o)}};function animate$1(et){var o,tt,{from:rt,autoplay:nt=!0,driver:ot=framesync,elapsed:it=0,repeat:st=0,repeatType:at="loop",repeatDelay:ct=0,onPlay:lt,onStop:dt,onComplete:ht,onRepeat:mt,onUpdate:ft}=et,pt=__rest(et,["from","autoplay","driver","elapsed","repeat","repeatType","repeatDelay","onPlay","onStop","onComplete","onRepeat","onUpdate"]);let{to:gt}=pt,yt,bt=0,xt=pt.duration,vt,Et=!1,Ct=!0,St;const At=detectAnimationFromOptions(pt);!((tt=(o=At).needsInterpolation)===null||tt===void 0)&&tt.call(o,rt,gt)&&(St=interpolate([0,100],[rt,gt],{clamp:!1}),rt=0,gt=100);const kt=At(Object.assign(Object.assign({},pt),{from:rt,to:gt}));function It(){bt++,at==="reverse"?(Ct=bt%2===0,it=reverseElapsed(it,xt,ct,Ct)):(it=loopElapsed(it,xt,ct),at==="mirror"&&kt.flipTarget()),Et=!1,mt&&mt()}function Ot(){yt.stop(),ht&&ht()}function Nt(Ft){if(Ct||(Ft=-Ft),it+=Ft,!Et){const Ht=kt.next(Math.max(0,it));vt=Ht.value,St&&(vt=St(vt)),Et=Ct?Ht.done:it<=0}ft==null||ft(vt),Et&&(bt===0&&(xt??(xt=it)),bt{dt==null||dt(),yt.stop()}}}function velocityPerSecond(et,o){return o?et*(1e3/o):0}function inertia({from:et=0,velocity:o=0,min:tt,max:rt,power:nt=.8,timeConstant:ot=750,bounceStiffness:it=500,bounceDamping:st=10,restDelta:at=1,modifyTarget:ct,driver:lt,onUpdate:dt,onComplete:ht,onStop:mt}){let ft;function pt(xt){return tt!==void 0&&xtrt}function gt(xt){return tt===void 0?rt:rt===void 0||Math.abs(tt-xt){var Et;dt==null||dt(vt),(Et=xt.onUpdate)===null||Et===void 0||Et.call(xt,vt)},onComplete:ht,onStop:mt}))}function bt(xt){yt(Object.assign({type:"spring",stiffness:it,damping:st,restDelta:at},xt))}if(pt(et))bt({from:et,velocity:o,to:gt(et)});else{let xt=nt*o+et;typeof ct<"u"&&(xt=ct(xt));const vt=gt(xt),Et=vt===tt?-1:1;let Ct,St;const At=kt=>{Ct=St,St=kt,o=velocityPerSecond(kt-Ct,getFrameData().delta),(Et===1&&kt>vt||Et===-1&&ktft==null?void 0:ft.stop()}}const isPoint=et=>et.hasOwnProperty("x")&&et.hasOwnProperty("y"),isPoint3D=et=>isPoint(et)&&et.hasOwnProperty("z"),distance1D=(et,o)=>Math.abs(et-o);function distance(et,o){if(isNum(et)&&isNum(o))return distance1D(et,o);if(isPoint(et)&&isPoint(o)){const tt=distance1D(et.x,o.x),rt=distance1D(et.y,o.y),nt=isPoint3D(et)&&isPoint3D(o)?distance1D(et.z,o.z):0;return Math.sqrt(Math.pow(tt,2)+Math.pow(rt,2)+Math.pow(nt,2))}}const a=(et,o)=>1-3*o+3*et,b$3=(et,o)=>3*o-6*et,c$2=et=>3*et,calcBezier=(et,o,tt)=>((a(o,tt)*et+b$3(o,tt))*et+c$2(o))*et,getSlope=(et,o,tt)=>3*a(o,tt)*et*et+2*b$3(o,tt)*et+c$2(o),subdivisionPrecision=1e-7,subdivisionMaxIterations=10;function binarySubdivide(et,o,tt,rt,nt){let ot,it,st=0;do it=o+(tt-o)/2,ot=calcBezier(it,rt,nt)-et,ot>0?tt=it:o=it;while(Math.abs(ot)>subdivisionPrecision&&++st=newtonMinSlope?newtonRaphsonIterate(it,dt,et,tt):ht===0?dt:binarySubdivide(it,st,st+kSampleStepSize,et,tt)}return it=>it===0||it===1?it:calcBezier(ot(it),o,rt)}function useTapGesture(et){var o=et.onTap,tt=et.onTapStart,rt=et.onTapCancel,nt=et.whileTap,ot=et.visualElement,it=o||tt||rt||nt,st=reactExports.useRef(!1),at=reactExports.useRef(null),ct={passive:!(tt||o||rt||ft)};function lt(){var pt;(pt=at.current)===null||pt===void 0||pt.call(at),at.current=null}function dt(){var pt;return lt(),st.current=!1,(pt=ot.animationState)===null||pt===void 0||pt.setActive(AnimationType.Tap,!1),!isDragActive()}function ht(pt,gt){dt()&&(isNodeOrChild(ot.getInstance(),pt.target)?o==null||o(pt,gt):rt==null||rt(pt,gt))}function mt(pt,gt){dt()&&(rt==null||rt(pt,gt))}function ft(pt,gt){var yt;lt(),!st.current&&(st.current=!0,at.current=pipe$1(addPointerEvent(window,"pointerup",ht,ct),addPointerEvent(window,"pointercancel",mt,ct)),(yt=ot.animationState)===null||yt===void 0||yt.setActive(AnimationType.Tap,!0),tt==null||tt(pt,gt))}usePointerEvent(ot,"pointerdown",it?ft:void 0,ct),useUnmountEffect(lt)}var warned=new Set;function warnOnce(et,o,tt){warned.has(o)||(console.warn(o),warned.add(o))}var observerCallbacks=new WeakMap,observers$1=new WeakMap,fireObserverCallback=function(et){var o;(o=observerCallbacks.get(et.target))===null||o===void 0||o(et)},fireAllObserverCallbacks=function(et){et.forEach(fireObserverCallback)};function initIntersectionObserver(et){var o=et.root,tt=__rest(et,["root"]),rt=o||document;observers$1.has(rt)||observers$1.set(rt,{});var nt=observers$1.get(rt),ot=JSON.stringify(tt);return nt[ot]||(nt[ot]=new IntersectionObserver(fireAllObserverCallbacks,__assign({root:o},tt))),nt[ot]}function observeIntersection(et,o,tt){var rt=initIntersectionObserver(o);return observerCallbacks.set(et,tt),rt.observe(et),function(){observerCallbacks.delete(et),rt.unobserve(et)}}function useViewport(et){var o=et.visualElement,tt=et.whileInView,rt=et.onViewportEnter,nt=et.onViewportLeave,ot=et.viewport,it=ot===void 0?{}:ot,st=reactExports.useRef({hasEnteredView:!1,isInView:!1}),at=!!(tt||rt||nt);it.once&&st.current.hasEnteredView&&(at=!1);var ct=typeof IntersectionObserver>"u"?useMissingIntersectionObserver:useIntersectionObserver;ct(at,st.current,o,it)}var thresholdNames={some:0,all:1};function useIntersectionObserver(et,o,tt,rt){var nt=rt.root,ot=rt.margin,it=rt.amount,st=it===void 0?"some":it,at=rt.once;reactExports.useEffect(function(){if(et){var ct={root:nt==null?void 0:nt.current,rootMargin:ot,threshold:typeof st=="number"?st:thresholdNames[st]},lt=function(dt){var ht,mt=dt.isIntersecting;if(o.isInView!==mt&&(o.isInView=mt,!(at&&!mt&&o.hasEnteredView))){mt&&(o.hasEnteredView=!0),(ht=tt.animationState)===null||ht===void 0||ht.setActive(AnimationType.InView,mt);var ft=tt.getProps(),pt=mt?ft.onViewportEnter:ft.onViewportLeave;pt==null||pt(dt)}};return observeIntersection(tt.getInstance(),ct,lt)}},[et,nt,ot,st])}function useMissingIntersectionObserver(et,o,tt,rt){var nt=rt.fallback,ot=nt===void 0?!0:nt;reactExports.useEffect(function(){!et||!ot||(env$2!=="production"&&warnOnce(!1,"IntersectionObserver not available on this device. whileInView animations will trigger on mount."),requestAnimationFrame(function(){var it;o.hasEnteredView=!0;var st=tt.getProps().onViewportEnter;st==null||st(null),(it=tt.animationState)===null||it===void 0||it.setActive(AnimationType.InView,!0)}))},[et])}var makeRenderlessComponent=function(et){return function(o){return et(o),null}},gestureAnimations={inView:makeRenderlessComponent(useViewport),tap:makeRenderlessComponent(useTapGesture),focus:makeRenderlessComponent(useFocusGesture),hover:makeRenderlessComponent(useHoverGesture)},counter=0,incrementId=function(){return counter++},useId$1=function(){return useConstant(incrementId)};function usePresence$1(){var et=reactExports.useContext(PresenceContext);if(et===null)return[!0,null];var o=et.isPresent,tt=et.onExitComplete,rt=et.register,nt=useId$1();reactExports.useEffect(function(){return rt(nt)},[]);var ot=function(){return tt==null?void 0:tt(nt)};return!o&&tt?[!1,ot]:[!0]}function shallowCompare(et,o){if(!Array.isArray(o))return!1;var tt=o.length;if(tt!==et.length)return!1;for(var rt=0;rt-1&&et.splice(tt,1)}var SubscriptionManager$1=function(){function et(){this.subscriptions=[]}return et.prototype.add=function(o){var tt=this;return addUniqueItem(this.subscriptions,o),function(){return removeItem(tt.subscriptions,o)}},et.prototype.notify=function(o,tt,rt){var nt=this.subscriptions.length;if(nt)if(nt===1)this.subscriptions[0](o,tt,rt);else for(var ot=0;otbt&&Ot,Qt=Array.isArray(It)?It:[It],Vt=Qt.reduce(ot,{});Nt===!1&&(Vt={});var Bt=kt.prevResolvedValues,Wt=Bt===void 0?{}:Bt,jt=__assign(__assign({},Wt),Vt),Xt=function(tr){Ht=!0,gt.delete(tr),kt.needsAnimating[tr]=!0};for(var Kt in jt){var Pt=Vt[Kt],Gt=Wt[Kt];yt.hasOwnProperty(Kt)||(Pt!==Gt?isKeyframesTarget(Pt)&&isKeyframesTarget(Gt)?!shallowCompare(Pt,Gt)||Ft?Xt(Kt):kt.protectedKeys[Kt]=!0:Pt!==void 0?Xt(Kt):gt.add(Kt):Pt!==void 0&>.has(Kt)?Xt(Kt):kt.protectedKeys[Kt]=!0)}kt.prevProp=It,kt.prevResolvedValues=Vt,kt.isActive&&(yt=__assign(__assign({},yt),Vt)),nt&&et.blockInitialAnimation&&(Ht=!1),Ht&&!Yt&&pt.push.apply(pt,__spreadArray([],__read(Qt.map(function(tr){return{animation:tr,options:__assign({type:At},lt)}})),!1))},vt=0;vt=3;if(!(!mt&&!ft)){var pt=ht.point,gt=getFrameData().timestamp;nt.history.push(__assign(__assign({},pt),{timestamp:gt}));var yt=nt.handlers,bt=yt.onStart,xt=yt.onMove;mt||(bt&&bt(nt.lastMoveEvent,ht),nt.startEvent=nt.lastMoveEvent),xt&&xt(nt.lastMoveEvent,ht)}}},this.handlePointerMove=function(ht,mt){if(nt.lastMoveEvent=ht,nt.lastMoveEventInfo=transformPoint(mt,nt.transformPagePoint),isMouseEvent(ht)&&ht.buttons===0){nt.handlePointerUp(ht,mt);return}sync.update(nt.updatePoint,!0)},this.handlePointerUp=function(ht,mt){nt.end();var ft=nt.handlers,pt=ft.onEnd,gt=ft.onSessionEnd,yt=getPanInfo(transformPoint(mt,nt.transformPagePoint),nt.history);nt.startEvent&&pt&&pt(ht,yt),gt&>(ht,yt)},!(isTouchEvent(o)&&o.touches.length>1)){this.handlers=tt,this.transformPagePoint=it;var st=extractEventInfo(o),at=transformPoint(st,this.transformPagePoint),ct=at.point,lt=getFrameData().timestamp;this.history=[__assign(__assign({},ct),{timestamp:lt})];var dt=tt.onSessionStart;dt&&dt(o,getPanInfo(at,this.history)),this.removeListeners=pipe$1(addPointerEvent(window,"pointermove",this.handlePointerMove),addPointerEvent(window,"pointerup",this.handlePointerUp),addPointerEvent(window,"pointercancel",this.handlePointerUp))}}return et.prototype.updateHandlers=function(o){this.handlers=o},et.prototype.end=function(){this.removeListeners&&this.removeListeners(),cancelSync.update(this.updatePoint)},et}();function transformPoint(et,o){return o?{point:o(et.point)}:et}function subtractPoint(et,o){return{x:et.x-o.x,y:et.y-o.y}}function getPanInfo(et,o){var tt=et.point;return{point:tt,delta:subtractPoint(tt,lastDevicePoint(o)),offset:subtractPoint(tt,startDevicePoint(o)),velocity:getVelocity(o,.1)}}function startDevicePoint(et){return et[0]}function lastDevicePoint(et){return et[et.length-1]}function getVelocity(et,o){if(et.length<2)return{x:0,y:0};for(var tt=et.length-1,rt=null,nt=lastDevicePoint(et);tt>=0&&(rt=et[tt],!(nt.timestamp-rt.timestamp>secondsToMilliseconds(o)));)tt--;if(!rt)return{x:0,y:0};var ot=(nt.timestamp-rt.timestamp)/1e3;if(ot===0)return{x:0,y:0};var it={x:(nt.x-rt.x)/ot,y:(nt.y-rt.y)/ot};return it.x===1/0&&(it.x=0),it.y===1/0&&(it.y=0),it}function calcLength(et){return et.max-et.min}function isNear(et,o,tt){return o===void 0&&(o=0),tt===void 0&&(tt=.01),distance(et,o)nt&&(et=tt?mix(nt,et,tt.max):Math.min(et,nt)),et}function calcRelativeAxisConstraints(et,o,tt){return{min:o!==void 0?et.min+o:void 0,max:tt!==void 0?et.max+tt-(et.max-et.min):void 0}}function calcRelativeConstraints(et,o){var tt=o.top,rt=o.left,nt=o.bottom,ot=o.right;return{x:calcRelativeAxisConstraints(et.x,rt,ot),y:calcRelativeAxisConstraints(et.y,tt,nt)}}function calcViewportAxisConstraints(et,o){var tt,rt=o.min-et.min,nt=o.max-et.max;return o.max-o.minrt?tt=progress(o.min,o.max-rt,et.min):rt>nt&&(tt=progress(et.min,et.max-nt,o.min)),clamp$1(0,1,tt)}function rebaseAxisConstraints(et,o){var tt={};return o.min!==void 0&&(tt.min=o.min-et.min),o.max!==void 0&&(tt.max=o.max-et.min),tt}var defaultElastic=.35;function resolveDragElastic(et){return et===void 0&&(et=defaultElastic),et===!1?et=0:et===!0&&(et=defaultElastic),{x:resolveAxisElastic(et,"left","right"),y:resolveAxisElastic(et,"top","bottom")}}function resolveAxisElastic(et,o,tt){return{min:resolvePointElastic(et,o),max:resolvePointElastic(et,tt)}}function resolvePointElastic(et,o){var tt;return typeof et=="number"?et:(tt=et[o])!==null&&tt!==void 0?tt:0}var createAxisDelta=function(){return{translate:0,scale:1,origin:0,originPoint:0}},createDelta=function(){return{x:createAxisDelta(),y:createAxisDelta()}},createAxis=function(){return{min:0,max:0}},createBox=function(){return{x:createAxis(),y:createAxis()}};function eachAxis(et){return[et("x"),et("y")]}function convertBoundingBoxToBox(et){var o=et.top,tt=et.left,rt=et.right,nt=et.bottom;return{x:{min:tt,max:rt},y:{min:o,max:nt}}}function convertBoxToBoundingBox(et){var o=et.x,tt=et.y;return{top:tt.min,right:o.max,bottom:tt.max,left:o.min}}function transformBoxPoints(et,o){if(!o)return et;var tt=o({x:et.left,y:et.top}),rt=o({x:et.right,y:et.bottom});return{top:tt.y,left:tt.x,bottom:rt.y,right:rt.x}}function isIdentityScale(et){return et===void 0||et===1}function hasScale(et){var o=et.scale,tt=et.scaleX,rt=et.scaleY;return!isIdentityScale(o)||!isIdentityScale(tt)||!isIdentityScale(rt)}function hasTransform(et){return hasScale(et)||hasTranslate(et.x)||hasTranslate(et.y)||et.z||et.rotate||et.rotateX||et.rotateY}function hasTranslate(et){return et&&et!=="0%"}function scalePoint(et,o,tt){var rt=et-tt,nt=o*rt;return tt+nt}function applyPointDelta(et,o,tt,rt,nt){return nt!==void 0&&(et=scalePoint(et,nt,rt)),scalePoint(et,tt,rt)+o}function applyAxisDelta(et,o,tt,rt,nt){o===void 0&&(o=0),tt===void 0&&(tt=1),et.min=applyPointDelta(et.min,o,tt,rt,nt),et.max=applyPointDelta(et.max,o,tt,rt,nt)}function applyBoxDelta(et,o){var tt=o.x,rt=o.y;applyAxisDelta(et.x,tt.translate,tt.scale,tt.originPoint),applyAxisDelta(et.y,rt.translate,rt.scale,rt.originPoint)}function applyTreeDeltas(et,o,tt,rt){var nt,ot;rt===void 0&&(rt=!1);var it=tt.length;if(it){o.x=o.y=1;for(var st,at,ct=0;cto?tt="y":Math.abs(et.x)>o&&(tt="x"),tt}function useDrag(et){var o=et.dragControls,tt=et.visualElement,rt=useConstant(function(){return new VisualElementDragControls(tt)});reactExports.useEffect(function(){return o&&o.subscribe(rt)},[rt,o]),reactExports.useEffect(function(){return rt.addListeners()},[rt])}function usePanGesture(et){var o=et.onPan,tt=et.onPanStart,rt=et.onPanEnd,nt=et.onPanSessionStart,ot=et.visualElement,it=o||tt||rt||nt,st=reactExports.useRef(null),at=reactExports.useContext(MotionConfigContext).transformPagePoint,ct={onSessionStart:nt,onStart:tt,onMove:o,onEnd:function(dt,ht){st.current=null,rt&&rt(dt,ht)}};reactExports.useEffect(function(){st.current!==null&&st.current.updateHandlers(ct)});function lt(dt){st.current=new PanSession(dt,ct,{transformPagePoint:at})}usePointerEvent(ot,"pointerdown",it&<),useUnmountEffect(function(){return st.current&&st.current.end()})}var drag={pan:makeRenderlessComponent(usePanGesture),drag:makeRenderlessComponent(useDrag)},names$1=["LayoutMeasure","BeforeLayoutMeasure","LayoutUpdate","ViewportBoxUpdate","Update","Render","AnimationComplete","LayoutAnimationComplete","AnimationStart","LayoutAnimationStart","SetAxisTarget","Unmount"];function createLifecycles(){var et=names$1.map(function(){return new SubscriptionManager$1}),o={},tt={clearAllListeners:function(){return et.forEach(function(rt){return rt.clear()})},updatePropListeners:function(rt){names$1.forEach(function(nt){var ot,it="on"+nt,st=rt[it];(ot=o[nt])===null||ot===void 0||ot.call(o),st&&(o[nt]=tt[it](st))})}};return et.forEach(function(rt,nt){tt["on"+names$1[nt]]=function(ot){return rt.add(ot)},tt["notify"+names$1[nt]]=function(){for(var ot=[],it=0;it=0?window.pageYOffset:null,ct=convertChangedValueTypes(o,et,st);return ot.length&&ot.forEach(function(lt){var dt=__read(lt,2),ht=dt[0],mt=dt[1];et.getValue(ht).set(mt)}),et.syncRender(),at!==null&&window.scrollTo({top:at}),{target:ct,transitionEnd:rt}}else return{target:o,transitionEnd:rt}};function unitConversion(et,o,tt,rt){return hasPositionalKey(o)?checkAndConvertChangedValueTypes(et,o,tt,rt):{target:o,transitionEnd:rt}}var parseDomVariant=function(et,o,tt,rt){var nt=resolveCSSVariables(et,o,rt);return o=nt.target,rt=nt.transitionEnd,unitConversion(et,o,tt,rt)};function getComputedStyle$1(et){return window.getComputedStyle(et)}var htmlConfig={treeType:"dom",readValueFromInstance:function(et,o){if(isTransformProp(o)){var tt=getDefaultValueType(o);return tt&&tt.default||0}else{var rt=getComputedStyle$1(et);return(isCSSVariable$1(o)?rt.getPropertyValue(o):rt[o])||0}},sortNodePosition:function(et,o){return et.compareDocumentPosition(o)&2?1:-1},getBaseTarget:function(et,o){var tt;return(tt=et.style)===null||tt===void 0?void 0:tt[o]},measureViewportBox:function(et,o){var tt=o.transformPagePoint;return measureViewportBox(et,tt)},resetTransform:function(et,o,tt){var rt=tt.transformTemplate;o.style.transform=rt?rt({},""):"none",et.scheduleRender()},restoreTransform:function(et,o){et.style.transform=o.style.transform},removeValueFromRenderState:function(et,o){var tt=o.vars,rt=o.style;delete tt[et],delete rt[et]},makeTargetAnimatable:function(et,o,tt,rt){var nt=tt.transformValues;rt===void 0&&(rt=!0);var ot=o.transition,it=o.transitionEnd,st=__rest(o,["transition","transitionEnd"]),at=getOrigin(st,ot||{},et);if(nt&&(it&&(it=nt(it)),st&&(st=nt(st)),at&&(at=nt(at))),rt){checkTargetForNewValues(et,st,at);var ct=parseDomVariant(et,st,at,it);it=ct.transitionEnd,st=ct.target}return __assign({transition:ot,transitionEnd:it},st)},scrapeMotionValuesFromProps:scrapeMotionValuesFromProps$1,build:function(et,o,tt,rt,nt){et.isVisible!==void 0&&(o.style.visibility=et.isVisible?"visible":"hidden"),buildHTMLStyles(o,tt,rt,nt.transformTemplate)},render:renderHTML},htmlVisualElement=visualElement(htmlConfig),svgVisualElement=visualElement(__assign(__assign({},htmlConfig),{getBaseTarget:function(et,o){return et[o]},readValueFromInstance:function(et,o){var tt;return isTransformProp(o)?((tt=getDefaultValueType(o))===null||tt===void 0?void 0:tt.default)||0:(o=camelCaseAttributes.has(o)?o:camelToDash(o),et.getAttribute(o))},scrapeMotionValuesFromProps,build:function(et,o,tt,rt,nt){buildSVGAttrs(o,tt,rt,nt.transformTemplate)},render:renderSVG})),createDomVisualElement=function(et,o){return isSVGComponent(et)?svgVisualElement(o,{enableHardwareAcceleration:!1}):htmlVisualElement(o,{enableHardwareAcceleration:!0})};function pixelsToPercent(et,o){return o.max===o.min?0:et/(o.max-o.min)*100}var correctBorderRadius={correct:function(et,o){if(!o.target)return et;if(typeof et=="string")if(px.test(et))et=parseFloat(et);else return et;var tt=pixelsToPercent(et,o.target.x),rt=pixelsToPercent(et,o.target.y);return"".concat(tt,"% ").concat(rt,"%")}},varToken="_$css",correctBoxShadow={correct:function(et,o){var tt=o.treeScale,rt=o.projectionDelta,nt=et,ot=et.includes("var("),it=[];ot&&(et=et.replace(cssVariableRegex,function(pt){return it.push(pt),varToken}));var st=complex.parse(et);if(st.length>5)return nt;var at=complex.createTransformer(et),ct=typeof st[0]!="number"?1:0,lt=rt.x.scale*tt.x,dt=rt.y.scale*tt.y;st[0+ct]/=lt,st[1+ct]/=dt;var ht=mix(lt,dt,.5);typeof st[2+ct]=="number"&&(st[2+ct]/=ht),typeof st[3+ct]=="number"&&(st[3+ct]/=ht);var mt=at(st);if(ot){var ft=0;mt=mt.replace(varToken,function(){var pt=it[ft];return ft++,pt})}return mt}},MeasureLayoutWithContext=function(et){__extends(o,et);function o(){return et!==null&&et.apply(this,arguments)||this}return o.prototype.componentDidMount=function(){var tt=this,rt=this.props,nt=rt.visualElement,ot=rt.layoutGroup,it=rt.switchLayoutGroup,st=rt.layoutId,at=nt.projection;addScaleCorrector(defaultScaleCorrectors),at&&(ot!=null&&ot.group&&ot.group.add(at),it!=null&&it.register&&st&&it.register(at),at.root.didUpdate(),at.addEventListener("animationComplete",function(){tt.safeToRemove()}),at.setOptions(__assign(__assign({},at.options),{onExitComplete:function(){return tt.safeToRemove()}}))),globalProjectionState.hasEverUpdated=!0},o.prototype.getSnapshotBeforeUpdate=function(tt){var rt=this,nt=this.props,ot=nt.layoutDependency,it=nt.visualElement,st=nt.drag,at=nt.isPresent,ct=it.projection;return ct&&(ct.isPresent=at,st||tt.layoutDependency!==ot||ot===void 0?ct.willUpdate():this.safeToRemove(),tt.isPresent!==at&&(at?ct.promote():ct.relegate()||sync.postRender(function(){var lt;!((lt=ct.getStack())===null||lt===void 0)&<.members.length||rt.safeToRemove()}))),null},o.prototype.componentDidUpdate=function(){var tt=this.props.visualElement.projection;tt&&(tt.root.didUpdate(),!tt.currentAnimation&&tt.isLead()&&this.safeToRemove())},o.prototype.componentWillUnmount=function(){var tt=this.props,rt=tt.visualElement,nt=tt.layoutGroup,ot=tt.switchLayoutGroup,it=rt.projection;it&&(it.scheduleCheckAfterUnmount(),nt!=null&&nt.group&&nt.group.remove(it),ot!=null&&ot.deregister&&ot.deregister(it))},o.prototype.safeToRemove=function(){var tt=this.props.safeToRemove;tt==null||tt()},o.prototype.render=function(){return null},o}(React.Component);function MeasureLayout(et){var o=__read(usePresence$1(),2),tt=o[0],rt=o[1],nt=reactExports.useContext(LayoutGroupContext);return React.createElement(MeasureLayoutWithContext,__assign({},et,{layoutGroup:nt,switchLayoutGroup:reactExports.useContext(SwitchLayoutGroupContext),isPresent:tt,safeToRemove:rt}))}var defaultScaleCorrectors={borderRadius:__assign(__assign({},correctBorderRadius),{applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]}),borderTopLeftRadius:correctBorderRadius,borderTopRightRadius:correctBorderRadius,borderBottomLeftRadius:correctBorderRadius,borderBottomRightRadius:correctBorderRadius,boxShadow:correctBoxShadow},layoutFeatures={measureLayout:MeasureLayout};function animate(et,o,tt){tt===void 0&&(tt={});var rt=isMotionValue(et)?et:motionValue(et);return startAnimation("",rt,o,tt),{stop:function(){return rt.stop()},isAnimating:function(){return rt.isAnimating()}}}var borders=["TopLeft","TopRight","BottomLeft","BottomRight"],numBorders=borders.length,asNumber=function(et){return typeof et=="string"?parseFloat(et):et},isPx=function(et){return typeof et=="number"||px.test(et)};function mixValues(et,o,tt,rt,nt,ot){var it,st,at,ct;nt?(et.opacity=mix(0,(it=tt.opacity)!==null&&it!==void 0?it:1,easeCrossfadeIn(rt)),et.opacityExit=mix((st=o.opacity)!==null&&st!==void 0?st:1,0,easeCrossfadeOut(rt))):ot&&(et.opacity=mix((at=o.opacity)!==null&&at!==void 0?at:1,(ct=tt.opacity)!==null&&ct!==void 0?ct:1,rt));for(var lt=0;lto?1:tt(progress(et,o,rt))}}function copyAxisInto(et,o){et.min=o.min,et.max=o.max}function copyBoxInto(et,o){copyAxisInto(et.x,o.x),copyAxisInto(et.y,o.y)}function removePointDelta(et,o,tt,rt,nt){return et-=o,et=scalePoint(et,1/tt,rt),nt!==void 0&&(et=scalePoint(et,1/nt,rt)),et}function removeAxisDelta(et,o,tt,rt,nt,ot,it){if(o===void 0&&(o=0),tt===void 0&&(tt=1),rt===void 0&&(rt=.5),ot===void 0&&(ot=et),it===void 0&&(it=et),percent.test(o)){o=parseFloat(o);var st=mix(it.min,it.max,o/100);o=st-it.min}if(typeof o=="number"){var at=mix(ot.min,ot.max,rt);et===ot&&(at-=o),et.min=removePointDelta(et.min,o,tt,at,nt),et.max=removePointDelta(et.max,o,tt,at,nt)}}function removeAxisTransforms(et,o,tt,rt,nt){var ot=__read(tt,3),it=ot[0],st=ot[1],at=ot[2];removeAxisDelta(et,o[it],o[st],o[at],o.scale,rt,nt)}var xKeys=["x","scaleX","originX"],yKeys=["y","scaleY","originY"];function removeBoxTransforms(et,o,tt,rt){removeAxisTransforms(et.x,o,xKeys,tt==null?void 0:tt.x,rt==null?void 0:rt.x),removeAxisTransforms(et.y,o,yKeys,tt==null?void 0:tt.y,rt==null?void 0:rt.y)}function isAxisDeltaZero(et){return et.translate===0&&et.scale===1}function isDeltaZero(et){return isAxisDeltaZero(et.x)&&isAxisDeltaZero(et.y)}function boxEquals(et,o){return et.x.min===o.x.min&&et.x.max===o.x.max&&et.y.min===o.y.min&&et.y.max===o.y.max}var NodeStack=function(){function et(){this.members=[]}return et.prototype.add=function(o){addUniqueItem(this.members,o),o.scheduleRender()},et.prototype.remove=function(o){if(removeItem(this.members,o),o===this.prevLead&&(this.prevLead=void 0),o===this.lead){var tt=this.members[this.members.length-1];tt&&this.promote(tt)}},et.prototype.relegate=function(o){var tt=this.members.findIndex(function(it){return o===it});if(tt===0)return!1;for(var rt,nt=tt;nt>=0;nt--){var ot=this.members[nt];if(ot.isPresent!==!1){rt=ot;break}}return rt?(this.promote(rt),!0):!1},et.prototype.promote=function(o,tt){var rt,nt=this.lead;if(o!==nt&&(this.prevLead=nt,this.lead=o,o.show(),nt)){nt.instance&&nt.scheduleRender(),o.scheduleRender(),o.resumeFrom=nt,tt&&(o.resumeFrom.preserveOpacity=!0),nt.snapshot&&(o.snapshot=nt.snapshot,o.snapshot.latestValues=nt.animationValues||nt.latestValues,o.snapshot.isShared=!0),!((rt=o.root)===null||rt===void 0)&&rt.isUpdating&&(o.isLayoutDirty=!0);var ot=o.options.crossfade;ot===!1&&nt.hide()}},et.prototype.exitAnimationComplete=function(){this.members.forEach(function(o){var tt,rt,nt,ot,it;(rt=(tt=o.options).onExitComplete)===null||rt===void 0||rt.call(tt),(it=(nt=o.resumingFrom)===null||nt===void 0?void 0:(ot=nt.options).onExitComplete)===null||it===void 0||it.call(ot)})},et.prototype.scheduleRender=function(){this.members.forEach(function(o){o.instance&&o.scheduleRender(!1)})},et.prototype.removeLeadSnapshot=function(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)},et}(),identityProjection="translate3d(0px, 0px, 0) scale(1, 1) scale(1, 1)";function buildProjectionTransform(et,o,tt){var rt=et.x.translate/o.x,nt=et.y.translate/o.y,ot="translate3d(".concat(rt,"px, ").concat(nt,"px, 0) ");if(ot+="scale(".concat(1/o.x,", ").concat(1/o.y,") "),tt){var it=tt.rotate,st=tt.rotateX,at=tt.rotateY;it&&(ot+="rotate(".concat(it,"deg) ")),st&&(ot+="rotateX(".concat(st,"deg) ")),at&&(ot+="rotateY(".concat(at,"deg) "))}var ct=et.x.scale*o.x,lt=et.y.scale*o.y;return ot+="scale(".concat(ct,", ").concat(lt,")"),ot===identityProjection?"none":ot}var compareByDepth=function(et,o){return et.depth-o.depth},FlatTree=function(){function et(){this.children=[],this.isDirty=!1}return et.prototype.add=function(o){addUniqueItem(this.children,o),this.isDirty=!0},et.prototype.remove=function(o){removeItem(this.children,o),this.isDirty=!0},et.prototype.forEach=function(o){this.isDirty&&this.children.sort(compareByDepth),this.isDirty=!1,this.children.forEach(o)},et}(),animationTarget=1e3;function createProjectionNode(et){var o=et.attachResizeListener,tt=et.defaultParent,rt=et.measureScroll,nt=et.checkIsScrollRoot,ot=et.resetTransform;return function(){function it(st,at,ct){var lt=this;at===void 0&&(at={}),ct===void 0&&(ct=tt==null?void 0:tt()),this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.potentialNodes=new Map,this.checkUpdateFailed=function(){lt.isUpdating&&(lt.isUpdating=!1,lt.clearAllSnapshots())},this.updateProjection=function(){lt.nodes.forEach(resolveTargetDelta),lt.nodes.forEach(calcProjection)},this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.id=st,this.latestValues=at,this.root=ct?ct.root||ct:this,this.path=ct?__spreadArray(__spreadArray([],__read(ct.path),!1),[ct],!1):[],this.parent=ct,this.depth=ct?ct.depth+1:0,st&&this.root.registerPotentialNode(st,this);for(var dt=0;dt=0;rt--)if(et.path[rt].instance){tt=et.path[rt];break}var nt=tt&&tt!==et.root?tt.instance:document,ot=nt.querySelector('[data-projection-id="'.concat(o,'"]'));ot&&et.mount(ot,!0)}function roundAxis(et){et.min=Math.round(et.min),et.max=Math.round(et.max)}function roundBox(et){roundAxis(et.x),roundAxis(et.y)}var DocumentProjectionNode=createProjectionNode({attachResizeListener:function(et,o){return addDomEvent(et,"resize",o)},measureScroll:function(){return{x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}},checkIsScrollRoot:function(){return!0}}),rootProjectionNode={current:void 0},HTMLProjectionNode=createProjectionNode({measureScroll:function(et){return{x:et.scrollLeft,y:et.scrollTop}},defaultParent:function(){if(!rootProjectionNode.current){var et=new DocumentProjectionNode(0,{});et.mount(window),et.setOptions({layoutScroll:!0}),rootProjectionNode.current=et}return rootProjectionNode.current},resetTransform:function(et,o){et.style.transform=o??"none"},checkIsScrollRoot:function(et){return window.getComputedStyle(et).position==="fixed"}}),featureBundle=__assign(__assign(__assign(__assign({},animations),gestureAnimations),drag),layoutFeatures),motion=createMotionProxy(function(et,o){return createDomMotionConfig(et,o,featureBundle,createDomVisualElement,HTMLProjectionNode)});function useIsMounted$1(){var et=reactExports.useRef(!1);return useIsomorphicLayoutEffect$3(function(){return et.current=!0,function(){et.current=!1}},[]),et}function useForceUpdate(){var et=useIsMounted$1(),o=__read(reactExports.useState(0),2),tt=o[0],rt=o[1],nt=reactExports.useCallback(function(){et.current&&rt(tt+1)},[tt]),ot=reactExports.useCallback(function(){return sync.postRender(nt)},[nt]);return[ot,tt]}var PresenceChild=function(et){var o=et.children,tt=et.initial,rt=et.isPresent,nt=et.onExitComplete,ot=et.custom,it=et.presenceAffectsLayout,st=useConstant(newChildrenMap),at=useId$1(),ct=reactExports.useMemo(function(){return{id:at,initial:tt,isPresent:rt,custom:ot,onExitComplete:function(lt){var dt,ht;st.set(lt,!0);try{for(var mt=__values(st.values()),ft=mt.next();!ft.done;ft=mt.next()){var pt=ft.value;if(!pt)return}}catch(gt){dt={error:gt}}finally{try{ft&&!ft.done&&(ht=mt.return)&&ht.call(mt)}finally{if(dt)throw dt.error}}nt==null||nt()},register:function(lt){return st.set(lt,!1),function(){return st.delete(lt)}}}},it?void 0:[rt]);return reactExports.useMemo(function(){st.forEach(function(lt,dt){return st.set(dt,!1)})},[rt]),reactExports.useEffect(function(){!rt&&!st.size&&(nt==null||nt())},[rt]),reactExports.createElement(PresenceContext.Provider,{value:ct},o)};function newChildrenMap(){return new Map}var getChildKey=function(et){return et.key||""};function updateChildLookup(et,o){et.forEach(function(tt){var rt=getChildKey(tt);o.set(rt,tt)})}function onlyElements(et){var o=[];return reactExports.Children.forEach(et,function(tt){reactExports.isValidElement(tt)&&o.push(tt)}),o}var AnimatePresence=function(et){var o=et.children,tt=et.custom,rt=et.initial,nt=rt===void 0?!0:rt,ot=et.onExitComplete,it=et.exitBeforeEnter,st=et.presenceAffectsLayout,at=st===void 0?!0:st,ct=__read(useForceUpdate(),1),lt=ct[0],dt=reactExports.useContext(LayoutGroupContext).forceRender;dt&&(lt=dt);var ht=useIsMounted$1(),mt=onlyElements(o),ft=mt,pt=new Set,gt=reactExports.useRef(ft),yt=reactExports.useRef(new Map).current,bt=reactExports.useRef(!0);if(useIsomorphicLayoutEffect$3(function(){bt.current=!1,updateChildLookup(mt,yt),gt.current=ft}),useUnmountEffect(function(){bt.current=!0,yt.clear(),pt.clear()}),bt.current)return reactExports.createElement(reactExports.Fragment,null,ft.map(function(At){return reactExports.createElement(PresenceChild,{key:getChildKey(At),isPresent:!0,initial:nt?void 0:!1,presenceAffectsLayout:at},At)}));ft=__spreadArray([],__read(ft),!1);for(var xt=gt.current.map(getChildKey),vt=mt.map(getChildKey),Et=xt.length,Ct=0;Ct1&&console.warn("You're attempting to animate multiple children within AnimatePresence, but its exitBeforeEnter prop is set to true. This will lead to odd visual behaviour."),reactExports.createElement(reactExports.Fragment,null,pt.size?ft:ft.map(function(At){return reactExports.cloneElement(At)}))};function MotionConfig(et){var o=et.children,tt=et.isValidProp,rt=__rest(et,["children","isValidProp"]);tt&&loadExternalIsValidProp(tt),rt=__assign(__assign({},reactExports.useContext(MotionConfigContext)),rt),rt.isStatic=useConstant(function(){return rt.isStatic});var nt=reactExports.useMemo(function(){return rt},[JSON.stringify(rt.transition),rt.transformPagePoint,rt.reducedMotion]);return reactExports.createElement(MotionConfigContext.Provider,{value:nt},o)}var reactIs$2={exports:{}},reactIs_production_min$1={};/** + * @license React + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var b$2=Symbol.for("react.element"),c$1=Symbol.for("react.portal"),d$2=Symbol.for("react.fragment"),e$1=Symbol.for("react.strict_mode"),f$1=Symbol.for("react.profiler"),g$2=Symbol.for("react.provider"),h$2=Symbol.for("react.context"),k$2=Symbol.for("react.server_context"),l$1=Symbol.for("react.forward_ref"),m$3=Symbol.for("react.suspense"),n$1=Symbol.for("react.suspense_list"),p$1=Symbol.for("react.memo"),q$2=Symbol.for("react.lazy"),t$1=Symbol.for("react.offscreen"),u;u=Symbol.for("react.module.reference");function v$2(et){if(typeof et=="object"&&et!==null){var o=et.$$typeof;switch(o){case b$2:switch(et=et.type,et){case d$2:case f$1:case e$1:case m$3:case n$1:return et;default:switch(et=et&&et.$$typeof,et){case k$2:case h$2:case l$1:case q$2:case p$1:case g$2:return et;default:return o}}case c$1:return o}}}reactIs_production_min$1.ContextConsumer=h$2;reactIs_production_min$1.ContextProvider=g$2;reactIs_production_min$1.Element=b$2;reactIs_production_min$1.ForwardRef=l$1;reactIs_production_min$1.Fragment=d$2;reactIs_production_min$1.Lazy=q$2;reactIs_production_min$1.Memo=p$1;reactIs_production_min$1.Portal=c$1;reactIs_production_min$1.Profiler=f$1;reactIs_production_min$1.StrictMode=e$1;reactIs_production_min$1.Suspense=m$3;reactIs_production_min$1.SuspenseList=n$1;reactIs_production_min$1.isAsyncMode=function(){return!1};reactIs_production_min$1.isConcurrentMode=function(){return!1};reactIs_production_min$1.isContextConsumer=function(et){return v$2(et)===h$2};reactIs_production_min$1.isContextProvider=function(et){return v$2(et)===g$2};reactIs_production_min$1.isElement=function(et){return typeof et=="object"&&et!==null&&et.$$typeof===b$2};reactIs_production_min$1.isForwardRef=function(et){return v$2(et)===l$1};reactIs_production_min$1.isFragment=function(et){return v$2(et)===d$2};reactIs_production_min$1.isLazy=function(et){return v$2(et)===q$2};reactIs_production_min$1.isMemo=function(et){return v$2(et)===p$1};reactIs_production_min$1.isPortal=function(et){return v$2(et)===c$1};reactIs_production_min$1.isProfiler=function(et){return v$2(et)===f$1};reactIs_production_min$1.isStrictMode=function(et){return v$2(et)===e$1};reactIs_production_min$1.isSuspense=function(et){return v$2(et)===m$3};reactIs_production_min$1.isSuspenseList=function(et){return v$2(et)===n$1};reactIs_production_min$1.isValidElementType=function(et){return typeof et=="string"||typeof et=="function"||et===d$2||et===f$1||et===e$1||et===m$3||et===n$1||et===t$1||typeof et=="object"&&et!==null&&(et.$$typeof===q$2||et.$$typeof===p$1||et.$$typeof===g$2||et.$$typeof===h$2||et.$$typeof===l$1||et.$$typeof===u||et.getModuleId!==void 0)};reactIs_production_min$1.typeOf=v$2;reactIs$2.exports=reactIs_production_min$1;var reactIsExports$1=reactIs$2.exports;function stylis_min(et){function o(Kt,Pt,Gt,tr,zt){for(var lr=0,rr=0,Jt=0,Rt=0,Mt,Ut,Zt=0,nr=0,ar,dr=ar=Mt=0,cr=0,yr=0,pr=0,gr=0,Pr=Gt.length,_r=Pr-1,Rr,mr="",wr="",ir="",Tt="",$t;crMt)&&(gr=(mr=mr.replace(" ",":")).length),0tr&&(tr=(Pt=Pt.trim()).charCodeAt(0)),tr){case 38:return Pt.replace(yt,"$1"+Kt.trim());case 58:return Kt.trim()+Pt.replace(yt,"$1"+Kt.trim());default:if(0<1*Gt&&0rr.charCodeAt(8))break;case 115:zt=zt.replace(rr,"-webkit-"+rr)+";"+zt;break;case 207:case 102:zt=zt.replace(rr,"-webkit-"+(102Gt.charCodeAt(0)&&(Gt=Gt.trim()),Xt=Gt,Gt=[Xt],01?o-1:0),rt=1;rt0?" Args: "+tt.join(", "):""))}var j=function(){function et(tt){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=tt}var o=et.prototype;return o.indexOfGroup=function(tt){for(var rt=0,nt=0;nt=this.groupSizes.length){for(var nt=this.groupSizes,ot=nt.length,it=ot;tt>=it;)(it<<=1)<0&&D(16,""+tt);this.groupSizes=new Uint32Array(it),this.groupSizes.set(nt),this.length=it;for(var st=ot;st=this.length||this.groupSizes[tt]===0)return rt;for(var nt=this.groupSizes[tt],ot=this.indexOfGroup(tt),it=ot+nt,st=ot;st=k&&(k=o+1),T.set(et,o),x.set(o,et)},M="style["+N+'][data-styled-version="5.3.11"]',G=new RegExp("^"+N+'\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)'),L=function(et,o,tt){for(var rt,nt=tt.split(","),ot=0,it=nt.length;ot=0;ct--){var lt=at[ct];if(lt&<.nodeType===1&<.hasAttribute(N))return lt}}(tt),ot=nt!==void 0?nt.nextSibling:null;rt.setAttribute(N,"active"),rt.setAttribute("data-styled-version","5.3.11");var it=Y();return it&&rt.setAttribute("nonce",it),tt.insertBefore(rt,ot),rt},H=function(){function et(tt){var rt=this.element=q(tt);rt.appendChild(document.createTextNode("")),this.sheet=function(nt){if(nt.sheet)return nt.sheet;for(var ot=document.styleSheets,it=0,st=ot.length;it=0){var nt=document.createTextNode(rt),ot=this.nodes[tt];return this.element.insertBefore(nt,ot||null),this.length++,!0}return!1},o.deleteRule=function(tt){this.element.removeChild(this.nodes[tt]),this.length--},o.getRule=function(tt){return tt0&&(dt+=ht+",")}),ot+=""+ct+lt+'{content:"'+dt+`"}/*!sc*/ +`}}}return ot}(this)},et}(),Z=/(a)(d)/gi,K=function(et){return String.fromCharCode(et+(et>25?39:97))};function Q(et){var o,tt="";for(o=Math.abs(et);o>52;o=o/52|0)tt=K(o%52)+tt;return(K(o%52)+tt).replace(Z,"$1-$2")}var ee=function(et,o){for(var tt=o.length;tt;)et=33*et^o.charCodeAt(--tt);return et},te=function(et){return ee(5381,et)};function ne(et){for(var o=0;o>>0);if(!tt.hasNameForId(nt,st)){var at=rt(it,"."+st,void 0,nt);tt.insertRules(nt,st,at)}ot.push(st),this.staticRulesId=st}else{for(var ct=this.rules.length,lt=ee(this.baseHash,rt.hash),dt="",ht=0;ht>>0);if(!tt.hasNameForId(nt,gt)){var yt=rt(dt,"."+gt,void 0,nt);tt.insertRules(nt,gt,yt)}ot.push(gt)}}return ot.join(" ")},et}(),se=/^\s*\/\/.*$/gm,ie=[":","[",".","#"];function ae(et){var o,tt,rt,nt,ot=w$1,it=ot.options,st=it===void 0?w$1:it,at=ot.plugins,ct=at===void 0?S:at,lt=new stylis_min(st),dt=[],ht=function(pt){function gt(yt){if(yt)try{pt(yt+"}")}catch{}}return function(yt,bt,xt,vt,Et,Ct,St,At,kt,It){switch(yt){case 1:if(kt===0&&bt.charCodeAt(0)===64)return pt(bt+";"),"";break;case 2:if(At===0)return bt+"/*|*/";break;case 3:switch(At){case 102:case 112:return pt(xt[0]+bt),"";default:return bt+(It===0?"/*|*/":"")}case-2:bt.split("/*|*/}").forEach(gt)}}}(function(pt){dt.push(pt)}),mt=function(pt,gt,yt){return gt===0&&ie.indexOf(yt[tt.length])!==-1||yt.match(nt)?pt:"."+o};function ft(pt,gt,yt,bt){bt===void 0&&(bt="&");var xt=pt.replace(se,""),vt=gt&&yt?yt+" "+gt+" { "+xt+" }":xt;return o=bt,tt=gt,rt=new RegExp("\\"+tt+"\\b","g"),nt=new RegExp("(\\"+tt+"\\b){2,}"),lt(yt||!gt?"":gt,vt)}return lt.use([].concat(ct,[function(pt,gt,yt){pt===2&&yt.length&&yt[0].lastIndexOf(tt)>0&&(yt[0]=yt[0].replace(rt,mt))},ht,function(pt){if(pt===-2){var gt=dt;return dt=[],gt}}])),ft.hash=ct.length?ct.reduce(function(pt,gt){return gt.name||D(15),ee(pt,gt.name)},5381).toString():"",ft}var ce=React.createContext();ce.Consumer;var le=React.createContext(),de=(le.Consumer,new X),he=ae();function pe(){return reactExports.useContext(ce)||de}function fe(){return reactExports.useContext(le)||he}var ye=function(){function et(o,tt){var rt=this;this.inject=function(nt,ot){ot===void 0&&(ot=he);var it=rt.name+ot.hash;nt.hasNameForId(rt.id,it)||nt.insertRules(rt.id,it,ot(rt.rules,it,"@keyframes"))},this.toString=function(){return D(12,String(rt.name))},this.name=o,this.id="sc-keyframes-"+o,this.rules=tt}return et.prototype.getName=function(o){return o===void 0&&(o=he),this.name+o.hash},et}(),ve=/([A-Z])/,ge=/([A-Z])/g,Se=/^ms-/,we=function(et){return"-"+et.toLowerCase()};function Ee(et){return ve.test(et)?et.replace(ge,we).replace(Se,"-ms-"):et}var be=function(et){return et==null||et===!1||et===""};function _e(et,o,tt,rt){if(Array.isArray(et)){for(var nt,ot=[],it=0,st=et.length;it1?o-1:0),rt=1;rt?@[\\\]^`{|}~-]+/g,De=/(^-|-$)/g;function je(et){return et.replace(Re,"-").replace(De,"")}var Te=function(et){return Q(te(et)>>>0)};function xe(et){return typeof et=="string"&&!0}var ke=function(et){return typeof et=="function"||typeof et=="object"&&et!==null&&!Array.isArray(et)},Ve=function(et){return et!=="__proto__"&&et!=="constructor"&&et!=="prototype"};function Be(et,o,tt){var rt=et[tt];ke(o)&&ke(rt)?ze(rt,o):et[tt]=o}function ze(et){for(var o=arguments.length,tt=new Array(o>1?o-1:0),rt=1;rt=0||(It[At]=Ct[At]);return It}(o,["componentId"]),Et=xt&&xt+"-"+(xe(bt)?bt:je(b(bt)));return Ye(bt,y$1({},vt,{attrs:ht,componentId:Et}),tt)},Object.defineProperty(ft,"defaultProps",{get:function(){return this._foldedDefaultProps},set:function(bt){this._foldedDefaultProps=rt?ze({},et.defaultProps,bt):bt}}),Object.defineProperty(ft,"toString",{value:function(){return"."+ft.styledComponentId}}),nt&&m$1(ft,et,{attrs:!0,componentStyle:!0,displayName:!0,foldedComponentIds:!0,shouldForwardProp:!0,styledComponentId:!0,target:!0,withComponent:!0}),ft}var qe=function(et){return function o(tt,rt,nt){if(nt===void 0&&(nt=w$1),!reactIsExports$1.isValidElementType(rt))return D(1,String(rt));var ot=function(){return tt(rt,nt,Ae.apply(void 0,arguments))};return ot.withConfig=function(it){return o(tt,rt,y$1({},nt,{},it))},ot.attrs=function(it){return o(tt,rt,y$1({},nt,{attrs:Array.prototype.concat(nt.attrs,it).filter(Boolean)}))},ot}(Ye,et)};["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","textPath","tspan"].forEach(function(et){qe[et]=qe(et)});function We(et){for(var o=arguments.length,tt=new Array(o>1?o-1:0),rt=1;rt>--at&1}const dt=31,ht=2**dt,mt=ht>>>1,ft=mt>>1,pt=ht-1;let gt=0;for(let Et=0;Et1;){let It=Ct+St>>>1;Et>>1|lt(),At=At<<1^mt,kt=(kt^mt)<<1|mt|1;bt=At,xt=1+kt-At}let vt=rt-4;return yt.map(Et=>{switch(Et-vt){case 3:return vt+65792+(et[st++]<<16|et[st++]<<8|et[st++]);case 2:return vt+256+(et[st++]<<8|et[st++]);case 1:return vt+et[st++];default:return Et-1}})}function read_payload(et){let o=0;return()=>et[o++]}function read_compressed_payload(et){return read_payload(decode_arithmetic(unsafe_atob(et)))}function unsafe_atob(et){let o=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach((nt,ot)=>o[nt.charCodeAt(0)]=ot);let tt=et.length,rt=new Uint8Array(6*tt>>3);for(let nt=0,ot=0,it=0,st=0;nt=8&&(rt[ot++]=st>>(it-=8));return rt}function signed(et){return et&1?~et>>1:et>>1}function read_deltas(et,o){let tt=Array(et);for(let rt=0,nt=0;rt{let o=read_sorted(et);if(o.length)return o})}function read_mapped(et){let o=[];for(;;){let tt=et();if(tt==0)break;o.push(read_linear_table(tt,et))}for(;;){let tt=et()-1;if(tt<0)break;o.push(read_replacement_table(tt,et))}return o.flat()}function read_array_while(et){let o=[];for(;;){let tt=et(o.length);if(!tt)break;o.push(tt)}return o}function read_transposed(et,o,tt){let rt=Array(et).fill().map(()=>[]);for(let nt=0;ntrt[it].push(ot));return rt}function read_linear_table(et,o){let tt=1+o(),rt=o(),nt=read_array_while(o);return read_transposed(nt.length,1+et,o).flatMap((it,st)=>{let[at,...ct]=it;return Array(nt[st]).fill().map((lt,dt)=>{let ht=dt*rt;return[at+dt*tt,ct.map(mt=>mt+ht)]})})}function read_replacement_table(et,o){let tt=1+o();return read_transposed(tt,1+et,o).map(nt=>[nt[0],nt.slice(1)])}function read_trie(et){let o=[],tt=read_sorted(et);return nt(rt([]),[]),o;function rt(ot){let it=et(),st=read_array_while(()=>{let at=read_sorted(et).map(ct=>tt[ct]);if(at.length)return rt(at)});return{S:it,B:st,Q:ot}}function nt({S:ot,B:it},st,at){if(!(ot&4&&at===st[st.length-1])){ot&2&&(at=st[st.length-1]),ot&1&&o.push(st);for(let ct of it)for(let lt of ct.Q)nt(ct,[...st,lt],at)}}}function hex_cp(et){return et.toString(16).toUpperCase().padStart(2,"0")}function quote_cp(et){return`{${hex_cp(et)}}`}function explode_cp(et){let o=[];for(let tt=0,rt=et.length;tt>24&255}function unpack_cp(et){return et&16777215}let SHIFTED_RANK,EXCLUSIONS,DECOMP,RECOMP;function init$1(){let et=read_compressed_payload(COMPRESSED);SHIFTED_RANK=new Map(read_sorted_arrays(et).flatMap((o,tt)=>o.map(rt=>[rt,tt+1<<24]))),EXCLUSIONS=new Set(read_sorted(et)),DECOMP=new Map,RECOMP=new Map;for(let[o,tt]of read_mapped(et)){if(!EXCLUSIONS.has(o)&&tt.length==2){let[rt,nt]=tt,ot=RECOMP.get(rt);ot||(ot=new Map,RECOMP.set(rt,ot)),ot.set(nt,o)}DECOMP.set(o,tt.reverse())}}function is_hangul(et){return et>=S0&&et=L0&&et=V0&&oT0&&o0&&nt(T0+ct)}else{let it=DECOMP.get(ot);it?tt.push(...it):nt(ot)}if(!tt.length)break;ot=tt.pop()}if(rt&&o.length>1){let ot=unpack_cc(o[0]);for(let it=1;it0&&nt>=it)it==0?(o.push(rt,...tt),tt.length=0,rt=st):tt.push(st),nt=it;else{let at=compose_pair(rt,st);at>=0?rt=at:nt==0&&it==0?(o.push(rt),rt=st):(tt.push(st),nt=it)}}return rt>=0&&o.push(rt,...tt),o}function nfd(et){return decomposed(et).map(unpack_cp)}function nfc(et){return composed_from_decomposed(decomposed(et))}const HYPHEN=45,STOP_CH=".",FE0F=65039,UNIQUE_PH=1,Array_from=et=>Array.from(et);function group_has_cp(et,o){return et.P.has(o)||et.Q.has(o)}class Emoji extends Array{get is_emoji(){return!0}}let MAPPED,IGNORED,CM,NSM,ESCAPE,GROUPS,WHOLE_VALID,WHOLE_MAP,VALID,EMOJI_LIST,EMOJI_ROOT;function init(){if(MAPPED)return;let et=read_compressed_payload(COMPRESSED$1);const o=()=>read_sorted(et),tt=()=>new Set(o()),rt=(lt,dt)=>dt.forEach(ht=>lt.add(ht));MAPPED=new Map(read_mapped(et)),IGNORED=tt(),CM=o(),NSM=new Set(o().map(lt=>CM[lt])),CM=new Set(CM),ESCAPE=tt(),tt();let nt=read_sorted_arrays(et),ot=et();const it=()=>{let lt=new Set;return o().forEach(dt=>rt(lt,nt[dt])),rt(lt,o()),lt};GROUPS=read_array_while(lt=>{let dt=read_array_while(et).map(ht=>ht+96);if(dt.length){let ht=lt>=ot;dt[0]-=32,dt=str_from_cps(dt),ht&&(dt=`Restricted[${dt}]`);let mt=it(),ft=it(),pt=!et();return{N:dt,P:mt,Q:ft,M:pt,R:ht}}}),WHOLE_VALID=tt(),WHOLE_MAP=new Map;let st=o().concat(Array_from(WHOLE_VALID)).sort((lt,dt)=>lt-dt);st.forEach((lt,dt)=>{let ht=et(),mt=st[dt]=ht?st[dt-ht]:{V:[],M:new Map};mt.V.push(lt),WHOLE_VALID.has(lt)||WHOLE_MAP.set(lt,mt)});for(let{V:lt,M:dt}of new Set(WHOLE_MAP.values())){let ht=[];for(let ft of lt){let pt=GROUPS.filter(yt=>group_has_cp(yt,ft)),gt=ht.find(({G:yt})=>pt.some(bt=>yt.has(bt)));gt||(gt={G:new Set,V:[]},ht.push(gt)),gt.V.push(ft),rt(gt.G,pt)}let mt=ht.flatMap(ft=>Array_from(ft.G));for(let{G:ft,V:pt}of ht){let gt=new Set(mt.filter(yt=>!ft.has(yt)));for(let yt of pt)dt.set(yt,gt)}}VALID=new Set;let at=new Set;const ct=lt=>VALID.has(lt)?at.add(lt):VALID.add(lt);for(let lt of GROUPS){for(let dt of lt.P)ct(dt);for(let dt of lt.Q)ct(dt)}for(let lt of VALID)!WHOLE_MAP.has(lt)&&!at.has(lt)&&WHOLE_MAP.set(lt,UNIQUE_PH);rt(VALID,nfd(VALID)),EMOJI_LIST=read_trie(et).map(lt=>Emoji.from(lt)).sort(compare_arrays),EMOJI_ROOT=new Map;for(let lt of EMOJI_LIST){let dt=[EMOJI_ROOT];for(let ht of lt){let mt=dt.map(ft=>{let pt=ft.get(ht);return pt||(pt=new Map,ft.set(ht,pt)),pt});ht===FE0F?dt.push(...mt):dt=mt}for(let ht of dt)ht.V=lt}}function quoted_cp(et){return(should_escape(et)?"":`${bidi_qq(safe_str_from_cps([et]))} `)+quote_cp(et)}function bidi_qq(et){return`"${et}"‎`}function check_label_extension(et){if(et.length>=4&&et[2]==HYPHEN&&et[3]==HYPHEN)throw new Error(`invalid label extension: "${str_from_cps(et.slice(0,4))}"`)}function check_leading_underscore(et){for(let tt=et.lastIndexOf(95);tt>0;)if(et[--tt]!==95)throw new Error("underscore allowed only at start")}function check_fenced(et){let o=et[0],tt=FENCED.get(o);if(tt)throw error_placement(`leading ${tt}`);let rt=et.length,nt=-1;for(let ot=1;oto&&(o>>=1,et=[...et.slice(0,o),8230,...et.slice(-o)]);let nt=0,ot=et.length;for(let it=0;it{let ot=explode_cp(nt),it={input:ot,offset:rt};rt+=ot.length+1;try{let st=it.tokens=tokens_from_str(ot,o,tt),at=st.length,ct;if(!at)throw new Error("empty label");let lt=it.output=st.flat();if(check_leading_underscore(lt),!(it.emoji=at>1||st[0].is_emoji)&<.every(ht=>ht<128))check_label_extension(lt),ct="ASCII";else{let ht=st.flatMap(mt=>mt.is_emoji?[]:mt);if(!ht.length)ct="Emoji";else{if(CM.has(lt[0]))throw error_placement("leading combining mark");for(let pt=1;ptit.has(st)):Array_from(it),!tt.length)return}else rt.push(nt)}if(tt){for(let nt of tt)if(rt.every(ot=>group_has_cp(nt,ot)))throw new Error(`whole-script confusable: ${et.N}/${nt.N}`)}}function determine_group(et){let o=GROUPS;for(let tt of et){let rt=o.filter(nt=>group_has_cp(nt,tt));if(!rt.length)throw GROUPS.some(nt=>group_has_cp(nt,tt))?error_group_member(o[0],tt):error_disallowed(tt);if(o=rt,rt.length==1)break}return o}function flatten$1(et){return et.map(({input:o,error:tt,output:rt})=>{if(tt){let nt=tt.message;throw new Error(et.length==1?nt:`Invalid label ${bidi_qq(safe_str_from_cps(o,63))}: ${nt}`)}return str_from_cps(rt)}).join(STOP_CH)}function error_disallowed(et){return new Error(`disallowed character: ${quoted_cp(et)}`)}function error_group_member(et,o){let tt=quoted_cp(o),rt=GROUPS.find(nt=>nt.P.has(o));return rt&&(tt=`${rt.N} ${tt}`),new Error(`illegal mixture: ${et.N} + ${tt}`)}function error_placement(et){return new Error(`illegal placement: ${et}`)}function check_group(et,o){for(let tt of o)if(!group_has_cp(et,tt))throw error_group_member(et,tt);if(et.M){let tt=nfd(o);for(let rt=1,nt=tt.length;rtNSM_MAX)throw new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(tt.slice(rt-1,ot)))} (${ot-rt}/${NSM_MAX})`);rt=ot}}}function tokens_from_str(et,o,tt){let rt=[],nt=[];for(et=et.slice().reverse();et.length;){let ot=consume_emoji_reversed(et);if(ot)nt.length&&(rt.push(o(nt)),nt=[]),rt.push(tt(ot));else{let it=et.pop();if(VALID.has(it))nt.push(it);else{let st=MAPPED.get(it);if(st)nt.push(...st);else if(!IGNORED.has(it))throw error_disallowed(it)}}}return nt.length&&rt.push(o(nt)),rt}function filter_fe0f(et){return et.filter(o=>o!=FE0F)}function consume_emoji_reversed(et,o){let tt=EMOJI_ROOT,rt,nt=et.length;for(;nt&&(tt=tt.get(et[--nt]),!!tt);){let{V:ot}=tt;ot&&(rt=ot,et.length=nt)}return rt}function normalize$2(et){return ens_normalize(et)}function debounce$1(et,o,tt){var rt,nt,ot,it,st;o==null&&(o=100);function at(){var lt=Date.now()-it;lt=0?rt=setTimeout(at,o-lt):(rt=null,tt||(st=et.apply(ot,nt),ot=nt=null))}var ct=function(){ot=this,nt=arguments,it=Date.now();var lt=tt&&!rt;return rt||(rt=setTimeout(at,o)),lt&&(st=et.apply(ot,nt),ot=nt=null),st};return ct.clear=function(){rt&&(clearTimeout(rt),rt=null)},ct.flush=function(){rt&&(st=et.apply(ot,nt),ot=nt=null,clearTimeout(rt),rt=null)},ct}debounce$1.debounce=debounce$1;var debounce_1=debounce$1;const createDebounce=getDefaultExportFromCjs(debounce_1);function useMeasure(et){let{debounce:o,scroll:tt,polyfill:rt,offsetSize:nt}=et===void 0?{debounce:0,scroll:!1,offsetSize:!1}:et;const ot=rt||(typeof window>"u"?class{}:window.ResizeObserver);if(!ot)throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");const[it,st]=reactExports.useState({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),at=reactExports.useRef({element:null,scrollContainers:null,resizeObserver:null,lastBounds:it}),ct=o?typeof o=="number"?o:o.scroll:null,lt=o?typeof o=="number"?o:o.resize:null,dt=reactExports.useRef(!1);reactExports.useEffect(()=>(dt.current=!0,()=>void(dt.current=!1)));const[ht,mt,ft]=reactExports.useMemo(()=>{const bt=()=>{if(!at.current.element)return;const{left:xt,top:vt,width:Et,height:Ct,bottom:St,right:At,x:kt,y:It}=at.current.element.getBoundingClientRect(),Ot={left:xt,top:vt,width:Et,height:Ct,bottom:St,right:At,x:kt,y:It};at.current.element instanceof HTMLElement&&nt&&(Ot.height=at.current.element.offsetHeight,Ot.width=at.current.element.offsetWidth),Object.freeze(Ot),dt.current&&!areBoundsEqual(at.current.lastBounds,Ot)&&st(at.current.lastBounds=Ot)};return[bt,lt?createDebounce(bt,lt):bt,ct?createDebounce(bt,ct):bt]},[st,nt,ct,lt]);function pt(){at.current.scrollContainers&&(at.current.scrollContainers.forEach(bt=>bt.removeEventListener("scroll",ft,!0)),at.current.scrollContainers=null),at.current.resizeObserver&&(at.current.resizeObserver.disconnect(),at.current.resizeObserver=null)}function gt(){at.current.element&&(at.current.resizeObserver=new ot(ft),at.current.resizeObserver.observe(at.current.element),tt&&at.current.scrollContainers&&at.current.scrollContainers.forEach(bt=>bt.addEventListener("scroll",ft,{capture:!0,passive:!0})))}const yt=bt=>{!bt||bt===at.current.element||(pt(),at.current.element=bt,at.current.scrollContainers=findScrollContainers(bt),gt())};return useOnWindowScroll(ft,!!tt),useOnWindowResize(mt),reactExports.useEffect(()=>{pt(),gt()},[tt,ft,mt]),reactExports.useEffect(()=>pt,[]),[yt,it,ht]}function useOnWindowResize(et){reactExports.useEffect(()=>{const o=et;return window.addEventListener("resize",o),()=>void window.removeEventListener("resize",o)},[et])}function useOnWindowScroll(et,o){reactExports.useEffect(()=>{if(o){const tt=et;return window.addEventListener("scroll",tt,{capture:!0,passive:!0}),()=>void window.removeEventListener("scroll",tt,!0)}},[et,o])}function findScrollContainers(et){const o=[];if(!et||et===document.body)return o;const{overflow:tt,overflowX:rt,overflowY:nt}=window.getComputedStyle(et);return[tt,rt,nt].some(ot=>ot==="auto"||ot==="scroll")&&o.push(et),[...o,...findScrollContainers(et.parentElement)]}const keys$1=["x","y","top","bottom","left","right","width","height"],areBoundsEqual=(et,o)=>keys$1.every(tt=>et[tt]===o[tt]);var MapShim=function(){if(typeof Map<"u")return Map;function et(o,tt){var rt=-1;return o.some(function(nt,ot){return nt[0]===tt?(rt=ot,!0):!1}),rt}return function(){function o(){this.__entries__=[]}return Object.defineProperty(o.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),o.prototype.get=function(tt){var rt=et(this.__entries__,tt),nt=this.__entries__[rt];return nt&&nt[1]},o.prototype.set=function(tt,rt){var nt=et(this.__entries__,tt);~nt?this.__entries__[nt][1]=rt:this.__entries__.push([tt,rt])},o.prototype.delete=function(tt){var rt=this.__entries__,nt=et(rt,tt);~nt&&rt.splice(nt,1)},o.prototype.has=function(tt){return!!~et(this.__entries__,tt)},o.prototype.clear=function(){this.__entries__.splice(0)},o.prototype.forEach=function(tt,rt){rt===void 0&&(rt=null);for(var nt=0,ot=this.__entries__;nt0},et.prototype.connect_=function(){!isBrowser$2||this.connected_||(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),mutationObserverSupported?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},et.prototype.disconnect_=function(){!isBrowser$2||!this.connected_||(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},et.prototype.onTransitionEnd_=function(o){var tt=o.propertyName,rt=tt===void 0?"":tt,nt=transitionKeys.some(function(ot){return!!~rt.indexOf(ot)});nt&&this.refresh()},et.getInstance=function(){return this.instance_||(this.instance_=new et),this.instance_},et.instance_=null,et}(),defineConfigurable=function(et,o){for(var tt=0,rt=Object.keys(o);tt"u"||!(Element instanceof Object))){if(!(o instanceof getWindowOf(o).Element))throw new TypeError('parameter 1 is not of type "Element".');var tt=this.observations_;tt.has(o)||(tt.set(o,new ResizeObservation(o)),this.controller_.addObserver(this),this.controller_.refresh())}},et.prototype.unobserve=function(o){if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");if(!(typeof Element>"u"||!(Element instanceof Object))){if(!(o instanceof getWindowOf(o).Element))throw new TypeError('parameter 1 is not of type "Element".');var tt=this.observations_;tt.has(o)&&(tt.delete(o),tt.size||this.controller_.removeObserver(this))}},et.prototype.disconnect=function(){this.clearActive(),this.observations_.clear(),this.controller_.removeObserver(this)},et.prototype.gatherActive=function(){var o=this;this.clearActive(),this.observations_.forEach(function(tt){tt.isActive()&&o.activeObservations_.push(tt)})},et.prototype.broadcastActive=function(){if(this.hasActive()){var o=this.callbackCtx_,tt=this.activeObservations_.map(function(rt){return new ResizeObserverEntry(rt.target,rt.broadcastRect())});this.callback_.call(o,tt,o),this.clearActive()}},et.prototype.clearActive=function(){this.activeObservations_.splice(0)},et.prototype.hasActive=function(){return this.activeObservations_.length>0},et}(),observers=typeof WeakMap<"u"?new WeakMap:new MapShim,ResizeObserver$1=function(){function et(o){if(!(this instanceof et))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var tt=ResizeObserverController.getInstance(),rt=new ResizeObserverSPI(o,tt,this);observers.set(this,rt)}return et}();["observe","unobserve","disconnect"].forEach(function(et){ResizeObserver$1.prototype[et]=function(){var o;return(o=observers.get(this))[et].apply(o,arguments)}});var index$1=function(){return typeof global$1.ResizeObserver<"u"?global$1.ResizeObserver:ResizeObserver$1}(),browser$1={},canPromise$1=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},qrcode={},utils$2={};let toSJISFunction;const CODEWORDS_COUNT=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];utils$2.getSymbolSize=function(o){if(!o)throw new Error('"version" cannot be null or undefined');if(o<1||o>40)throw new Error('"version" should be in range from 1 to 40');return o*4+17};utils$2.getSymbolTotalCodewords=function(o){return CODEWORDS_COUNT[o]};utils$2.getBCHDigit=function(et){let o=0;for(;et!==0;)o++,et>>>=1;return o};utils$2.setToSJISFunction=function(o){if(typeof o!="function")throw new Error('"toSJISFunc" is not a valid function.');toSJISFunction=o};utils$2.isKanjiModeEnabled=function(){return typeof toSJISFunction<"u"};utils$2.toSJIS=function(o){return toSJISFunction(o)};var errorCorrectionLevel={};(function(et){et.L={bit:1},et.M={bit:0},et.Q={bit:3},et.H={bit:2};function o(tt){if(typeof tt!="string")throw new Error("Param is not a string");switch(tt.toLowerCase()){case"l":case"low":return et.L;case"m":case"medium":return et.M;case"q":case"quartile":return et.Q;case"h":case"high":return et.H;default:throw new Error("Unknown EC Level: "+tt)}}et.isValid=function(rt){return rt&&typeof rt.bit<"u"&&rt.bit>=0&&rt.bit<4},et.from=function(rt,nt){if(et.isValid(rt))return rt;try{return o(rt)}catch{return nt}}})(errorCorrectionLevel);function BitBuffer$1(){this.buffer=[],this.length=0}BitBuffer$1.prototype={get:function(et){const o=Math.floor(et/8);return(this.buffer[o]>>>7-et%8&1)===1},put:function(et,o){for(let tt=0;tt>>o-tt-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(et){const o=Math.floor(this.length/8);this.buffer.length<=o&&this.buffer.push(0),et&&(this.buffer[o]|=128>>>this.length%8),this.length++}};var bitBuffer=BitBuffer$1;function BitMatrix$1(et){if(!et||et<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=et,this.data=new Uint8Array(et*et),this.reservedBit=new Uint8Array(et*et)}BitMatrix$1.prototype.set=function(et,o,tt,rt){const nt=et*this.size+o;this.data[nt]=tt,rt&&(this.reservedBit[nt]=!0)};BitMatrix$1.prototype.get=function(et,o){return this.data[et*this.size+o]};BitMatrix$1.prototype.xor=function(et,o,tt){this.data[et*this.size+o]^=tt};BitMatrix$1.prototype.isReserved=function(et,o){return this.reservedBit[et*this.size+o]};var bitMatrix=BitMatrix$1,alignmentPattern={};(function(et){const o=utils$2.getSymbolSize;et.getRowColCoords=function(rt){if(rt===1)return[];const nt=Math.floor(rt/7)+2,ot=o(rt),it=ot===145?26:Math.ceil((ot-13)/(2*nt-2))*2,st=[ot-7];for(let at=1;at=0&&nt<=7},et.from=function(nt){return et.isValid(nt)?parseInt(nt,10):void 0},et.getPenaltyN1=function(nt){const ot=nt.size;let it=0,st=0,at=0,ct=null,lt=null;for(let dt=0;dt=5&&(it+=o.N1+(st-5)),ct=mt,st=1),mt=nt.get(ht,dt),mt===lt?at++:(at>=5&&(it+=o.N1+(at-5)),lt=mt,at=1)}st>=5&&(it+=o.N1+(st-5)),at>=5&&(it+=o.N1+(at-5))}return it},et.getPenaltyN2=function(nt){const ot=nt.size;let it=0;for(let st=0;st=10&&(st===1488||st===93)&&it++,at=at<<1&2047|nt.get(lt,ct),lt>=10&&(at===1488||at===93)&&it++}return it*o.N3},et.getPenaltyN4=function(nt){let ot=0;const it=nt.data.length;for(let at=0;at=0;){const it=ot[0];for(let at=0;at0){const ot=new Uint8Array(this.degree);return ot.set(rt,nt),ot}return rt};var reedSolomonEncoder=ReedSolomonEncoder$1,version$4={},mode$1={},versionCheck={};versionCheck.isValid=function(o){return!isNaN(o)&&o>=1&&o<=40};var regex={};const numeric="[0-9]+",alphanumeric="[A-Z $%*+\\-./:]+";let kanji="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";kanji=kanji.replace(/u/g,"\\u");const byte="(?:(?![A-Z0-9 $%*+\\-./:]|"+kanji+`)(?:.|[\r +]))+`;regex.KANJI=new RegExp(kanji,"g");regex.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");regex.BYTE=new RegExp(byte,"g");regex.NUMERIC=new RegExp(numeric,"g");regex.ALPHANUMERIC=new RegExp(alphanumeric,"g");const TEST_KANJI=new RegExp("^"+kanji+"$"),TEST_NUMERIC=new RegExp("^"+numeric+"$"),TEST_ALPHANUMERIC=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");regex.testKanji=function(o){return TEST_KANJI.test(o)};regex.testNumeric=function(o){return TEST_NUMERIC.test(o)};regex.testAlphanumeric=function(o){return TEST_ALPHANUMERIC.test(o)};(function(et){const o=versionCheck,tt=regex;et.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},et.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},et.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},et.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},et.MIXED={bit:-1},et.getCharCountIndicator=function(ot,it){if(!ot.ccBits)throw new Error("Invalid mode: "+ot);if(!o.isValid(it))throw new Error("Invalid version: "+it);return it>=1&&it<10?ot.ccBits[0]:it<27?ot.ccBits[1]:ot.ccBits[2]},et.getBestModeForData=function(ot){return tt.testNumeric(ot)?et.NUMERIC:tt.testAlphanumeric(ot)?et.ALPHANUMERIC:tt.testKanji(ot)?et.KANJI:et.BYTE},et.toString=function(ot){if(ot&&ot.id)return ot.id;throw new Error("Invalid mode")},et.isValid=function(ot){return ot&&ot.bit&&ot.ccBits};function rt(nt){if(typeof nt!="string")throw new Error("Param is not a string");switch(nt.toLowerCase()){case"numeric":return et.NUMERIC;case"alphanumeric":return et.ALPHANUMERIC;case"kanji":return et.KANJI;case"byte":return et.BYTE;default:throw new Error("Unknown mode: "+nt)}}et.from=function(ot,it){if(et.isValid(ot))return ot;try{return rt(ot)}catch{return it}}})(mode$1);(function(et){const o=utils$2,tt=errorCorrectionCode,rt=errorCorrectionLevel,nt=mode$1,ot=versionCheck,it=7973,st=o.getBCHDigit(it);function at(ht,mt,ft){for(let pt=1;pt<=40;pt++)if(mt<=et.getCapacity(pt,ft,ht))return pt}function ct(ht,mt){return nt.getCharCountIndicator(ht,mt)+4}function lt(ht,mt){let ft=0;return ht.forEach(function(pt){const gt=ct(pt.mode,mt);ft+=gt+pt.getBitsLength()}),ft}function dt(ht,mt){for(let ft=1;ft<=40;ft++)if(lt(ht,ft)<=et.getCapacity(ft,mt,nt.MIXED))return ft}et.from=function(mt,ft){return ot.isValid(mt)?parseInt(mt,10):ft},et.getCapacity=function(mt,ft,pt){if(!ot.isValid(mt))throw new Error("Invalid QR Code version");typeof pt>"u"&&(pt=nt.BYTE);const gt=o.getSymbolTotalCodewords(mt),yt=tt.getTotalCodewordsCount(mt,ft),bt=(gt-yt)*8;if(pt===nt.MIXED)return bt;const xt=bt-ct(pt,mt);switch(pt){case nt.NUMERIC:return Math.floor(xt/10*3);case nt.ALPHANUMERIC:return Math.floor(xt/11*2);case nt.KANJI:return Math.floor(xt/13);case nt.BYTE:default:return Math.floor(xt/8)}},et.getBestVersionForData=function(mt,ft){let pt;const gt=rt.from(ft,rt.M);if(Array.isArray(mt)){if(mt.length>1)return dt(mt,gt);if(mt.length===0)return 1;pt=mt[0]}else pt=mt;return at(pt.mode,pt.getLength(),gt)},et.getEncodedBits=function(mt){if(!ot.isValid(mt)||mt<7)throw new Error("Invalid QR Code version");let ft=mt<<12;for(;o.getBCHDigit(ft)-st>=0;)ft^=it<=0;)nt^=G15<0&&(rt=this.data.substr(tt),nt=parseInt(rt,10),o.put(nt,ot*3+1))};var numericData=NumericData;const Mode$3=mode$1,ALPHA_NUM_CHARS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function AlphanumericData(et){this.mode=Mode$3.ALPHANUMERIC,this.data=et}AlphanumericData.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)};AlphanumericData.prototype.getLength=function(){return this.data.length};AlphanumericData.prototype.getBitsLength=function(){return AlphanumericData.getBitsLength(this.data.length)};AlphanumericData.prototype.write=function(o){let tt;for(tt=0;tt+2<=this.data.length;tt+=2){let rt=ALPHA_NUM_CHARS.indexOf(this.data[tt])*45;rt+=ALPHA_NUM_CHARS.indexOf(this.data[tt+1]),o.put(rt,11)}this.data.length%2&&o.put(ALPHA_NUM_CHARS.indexOf(this.data[tt]),6)};var alphanumericData=AlphanumericData;const Mode$2=mode$1;function ByteData(et){this.mode=Mode$2.BYTE,typeof et=="string"?this.data=new TextEncoder().encode(et):this.data=new Uint8Array(et)}ByteData.getBitsLength=function(o){return o*8};ByteData.prototype.getLength=function(){return this.data.length};ByteData.prototype.getBitsLength=function(){return ByteData.getBitsLength(this.data.length)};ByteData.prototype.write=function(et){for(let o=0,tt=this.data.length;o=33088&&tt<=40956)tt-=33088;else if(tt>=57408&&tt<=60351)tt-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+` +Make sure your charset is UTF-8`);tt=(tt>>>8&255)*192+(tt&255),et.put(tt,13)}};var kanjiData=KanjiData,dijkstra={exports:{}};(function(et){var o={single_source_shortest_paths:function(tt,rt,nt){var ot={},it={};it[rt]=0;var st=o.PriorityQueue.make();st.push(rt,0);for(var at,ct,lt,dt,ht,mt,ft,pt,gt;!st.empty();){at=st.pop(),ct=at.value,dt=at.cost,ht=tt[ct]||{};for(lt in ht)ht.hasOwnProperty(lt)&&(mt=ht[lt],ft=dt+mt,pt=it[lt],gt=typeof it[lt]>"u",(gt||pt>ft)&&(it[lt]=ft,st.push(lt,ft),ot[lt]=ct))}if(typeof nt<"u"&&typeof it[nt]>"u"){var yt=["Could not find a path from ",rt," to ",nt,"."].join("");throw new Error(yt)}return ot},extract_shortest_path_from_predecessor_list:function(tt,rt){for(var nt=[],ot=rt;ot;)nt.push(ot),tt[ot],ot=tt[ot];return nt.reverse(),nt},find_path:function(tt,rt,nt){var ot=o.single_source_shortest_paths(tt,rt,nt);return o.extract_shortest_path_from_predecessor_list(ot,nt)},PriorityQueue:{make:function(tt){var rt=o.PriorityQueue,nt={},ot;tt=tt||{};for(ot in rt)rt.hasOwnProperty(ot)&&(nt[ot]=rt[ot]);return nt.queue=[],nt.sorter=tt.sorter||rt.default_sorter,nt},default_sorter:function(tt,rt){return tt.cost-rt.cost},push:function(tt,rt){var nt={value:tt,cost:rt};this.queue.push(nt),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};et.exports=o})(dijkstra);var dijkstraExports=dijkstra.exports;(function(et){const o=mode$1,tt=numericData,rt=alphanumericData,nt=byteData,ot=kanjiData,it=regex,st=utils$2,at=dijkstraExports;function ct(yt){return unescape(encodeURIComponent(yt)).length}function lt(yt,bt,xt){const vt=[];let Et;for(;(Et=yt.exec(xt))!==null;)vt.push({data:Et[0],index:Et.index,mode:bt,length:Et[0].length});return vt}function dt(yt){const bt=lt(it.NUMERIC,o.NUMERIC,yt),xt=lt(it.ALPHANUMERIC,o.ALPHANUMERIC,yt);let vt,Et;return st.isKanjiModeEnabled()?(vt=lt(it.BYTE,o.BYTE,yt),Et=lt(it.KANJI,o.KANJI,yt)):(vt=lt(it.BYTE_KANJI,o.BYTE,yt),Et=[]),bt.concat(xt,vt,Et).sort(function(St,At){return St.index-At.index}).map(function(St){return{data:St.data,mode:St.mode,length:St.length}})}function ht(yt,bt){switch(bt){case o.NUMERIC:return tt.getBitsLength(yt);case o.ALPHANUMERIC:return rt.getBitsLength(yt);case o.KANJI:return ot.getBitsLength(yt);case o.BYTE:return nt.getBitsLength(yt)}}function mt(yt){return yt.reduce(function(bt,xt){const vt=bt.length-1>=0?bt[bt.length-1]:null;return vt&&vt.mode===xt.mode?(bt[bt.length-1].data+=xt.data,bt):(bt.push(xt),bt)},[])}function ft(yt){const bt=[];for(let xt=0;xt=0&&st<=6&&(at===0||at===6)||at>=0&&at<=6&&(st===0||st===6)||st>=2&&st<=4&&at>=2&&at<=4?et.set(ot+st,it+at,!0,!0):et.set(ot+st,it+at,!1,!0))}}function setupTimingPattern(et){const o=et.size;for(let tt=8;tt>st&1)===1,et.set(nt,ot,it,!0),et.set(ot,nt,it,!0)}function setupFormatInfo(et,o,tt){const rt=et.size,nt=FormatInfo.getEncodedBits(o,tt);let ot,it;for(ot=0;ot<15;ot++)it=(nt>>ot&1)===1,ot<6?et.set(ot,8,it,!0):ot<8?et.set(ot+1,8,it,!0):et.set(rt-15+ot,8,it,!0),ot<8?et.set(8,rt-ot-1,it,!0):ot<9?et.set(8,15-ot-1+1,it,!0):et.set(8,15-ot-1,it,!0);et.set(rt-8,8,1,!0)}function setupData(et,o){const tt=et.size;let rt=-1,nt=tt-1,ot=7,it=0;for(let st=tt-1;st>0;st-=2)for(st===6&&st--;;){for(let at=0;at<2;at++)if(!et.isReserved(nt,st-at)){let ct=!1;it>>ot&1)===1),et.set(nt,st-at,ct),ot--,ot===-1&&(it++,ot=7)}if(nt+=rt,nt<0||tt<=nt){nt-=rt,rt=-rt;break}}}function createData(et,o,tt){const rt=new BitBuffer;tt.forEach(function(at){rt.put(at.mode.bit,4),rt.put(at.getLength(),Mode.getCharCountIndicator(at.mode,et)),at.write(rt)});const nt=Utils$1.getSymbolTotalCodewords(et),ot=ECCode.getTotalCodewordsCount(et,o),it=(nt-ot)*8;for(rt.getLengthInBits()+4<=it&&rt.put(0,4);rt.getLengthInBits()%8!==0;)rt.putBit(0);const st=(it-rt.getLengthInBits())/8;for(let at=0;at=7&&setupVersionInfo(at,o),setupData(at,it),isNaN(rt)&&(rt=MaskPattern.getBestMask(at,setupFormatInfo.bind(null,at,tt))),MaskPattern.applyMask(rt,at),setupFormatInfo(at,tt,rt),{modules:at,version:o,errorCorrectionLevel:tt,maskPattern:rt,segments:nt}}qrcode.create=function(o,tt){if(typeof o>"u"||o==="")throw new Error("No input text");let rt=ECLevel.M,nt,ot;return typeof tt<"u"&&(rt=ECLevel.from(tt.errorCorrectionLevel,ECLevel.M),nt=Version$1.from(tt.version),ot=MaskPattern.from(tt.maskPattern),tt.toSJISFunc&&Utils$1.setToSJISFunction(tt.toSJISFunc)),createSymbol(o,nt,rt,ot)};var canvas={},utils$1={};(function(et){function o(tt){if(typeof tt=="number"&&(tt=tt.toString()),typeof tt!="string")throw new Error("Color should be defined as hex string");let rt=tt.slice().replace("#","").split("");if(rt.length<3||rt.length===5||rt.length>8)throw new Error("Invalid hex color: "+tt);(rt.length===3||rt.length===4)&&(rt=Array.prototype.concat.apply([],rt.map(function(ot){return[ot,ot]}))),rt.length===6&&rt.push("F","F");const nt=parseInt(rt.join(""),16);return{r:nt>>24&255,g:nt>>16&255,b:nt>>8&255,a:nt&255,hex:"#"+rt.slice(0,6).join("")}}et.getOptions=function(rt){rt||(rt={}),rt.color||(rt.color={});const nt=typeof rt.margin>"u"||rt.margin===null||rt.margin<0?4:rt.margin,ot=rt.width&&rt.width>=21?rt.width:void 0,it=rt.scale||4;return{width:ot,scale:ot?4:it,margin:nt,color:{dark:o(rt.color.dark||"#000000ff"),light:o(rt.color.light||"#ffffffff")},type:rt.type,rendererOpts:rt.rendererOpts||{}}},et.getScale=function(rt,nt){return nt.width&&nt.width>=rt+nt.margin*2?nt.width/(rt+nt.margin*2):nt.scale},et.getImageWidth=function(rt,nt){const ot=et.getScale(rt,nt);return Math.floor((rt+nt.margin*2)*ot)},et.qrToImageData=function(rt,nt,ot){const it=nt.modules.size,st=nt.modules.data,at=et.getScale(it,ot),ct=Math.floor((it+ot.margin*2)*at),lt=ot.margin*at,dt=[ot.color.light,ot.color.dark];for(let ht=0;ht=lt&&mt>=lt&&ht"u"&&(!it||!it.getContext)&&(at=it,it=void 0),it||(ct=rt()),at=o.getOptions(at);const lt=o.getImageWidth(ot.modules.size,at),dt=ct.getContext("2d"),ht=dt.createImageData(lt,lt);return o.qrToImageData(ht.data,ot,at),tt(dt,ct,lt),dt.putImageData(ht,0,0),ct},et.renderToDataURL=function(ot,it,st){let at=st;typeof at>"u"&&(!it||!it.getContext)&&(at=it,it=void 0),at||(at={});const ct=et.render(ot,it,at),lt=at.type||"image/png",dt=at.rendererOpts||{};return ct.toDataURL(lt,dt.quality)}})(canvas);var svgTag={};const Utils=utils$1;function getColorAttrib(et,o){const tt=et.a/255,rt=o+'="'+et.hex+'"';return tt<1?rt+" "+o+'-opacity="'+tt.toFixed(2).slice(1)+'"':rt}function svgCmd(et,o,tt){let rt=et+o;return typeof tt<"u"&&(rt+=" "+tt),rt}function qrToPath(et,o,tt){let rt="",nt=0,ot=!1,it=0;for(let st=0;st0&&at>0&&et[st-1]||(rt+=ot?svgCmd("M",at+tt,.5+ct+tt):svgCmd("m",nt,0),nt=0,ot=!1),at+1':"",ct="',lt='viewBox="0 0 '+st+" "+st+'"',ht=''+at+ct+` +`;return typeof rt=="function"&&rt(null,ht),ht};const canPromise=canPromise$1,QRCode$2=qrcode,CanvasRenderer=canvas,SvgRenderer=svgTag;function renderCanvas(et,o,tt,rt,nt){const ot=[].slice.call(arguments,1),it=ot.length,st=typeof ot[it-1]=="function";if(!st&&!canPromise())throw new Error("Callback required as last argument");if(st){if(it<2)throw new Error("Too few arguments provided");it===2?(nt=tt,tt=o,o=rt=void 0):it===3&&(o.getContext&&typeof nt>"u"?(nt=rt,rt=void 0):(nt=rt,rt=tt,tt=o,o=void 0))}else{if(it<1)throw new Error("Too few arguments provided");return it===1?(tt=o,o=rt=void 0):it===2&&!o.getContext&&(rt=tt,tt=o,o=void 0),new Promise(function(at,ct){try{const lt=QRCode$2.create(tt,rt);at(et(lt,o,rt))}catch(lt){ct(lt)}})}try{const at=QRCode$2.create(tt,rt);nt(null,et(at,o,rt))}catch(at){nt(at)}}browser$1.create=QRCode$2.create;browser$1.toCanvas=renderCanvas.bind(null,CanvasRenderer.render);browser$1.toDataURL=renderCanvas.bind(null,CanvasRenderer.renderToDataURL);browser$1.toString=renderCanvas.bind(null,function(et,o,tt){return SvgRenderer.render(et,tt)});var PRE_ENTER=0,ENTERING=1,ENTERED=2,PRE_EXIT=3,EXITING=4,EXITED=5,UNMOUNTED=6,STATES=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],startOrEnd=function(o){return o?UNMOUNTED:EXITED},updateState=function(o,tt,rt,nt,ot){clearTimeout(nt.current),tt(o),rt.current=o,ot&&ot({state:STATES[o]})},useTransition=function(o){var tt=o===void 0?{}:o,rt=tt.enter,nt=rt===void 0?!0:rt,ot=tt.exit,it=ot===void 0?!0:ot,st=tt.preEnter,at=tt.preExit,ct=tt.timeout,lt=tt.initialEntered,dt=tt.mountOnEnter,ht=tt.unmountOnExit,mt=tt.onChange,ft=reactExports.useState(lt?ENTERED:startOrEnd(dt)),pt=ft[0],gt=ft[1],yt=reactExports.useRef(pt),bt=reactExports.useRef(),xt,vt;typeof ct=="object"?(xt=ct.enter,vt=ct.exit):xt=vt=ct;var Et=reactExports.useCallback(function(){var St;switch(yt.current){case ENTERING:case PRE_ENTER:St=ENTERED;break;case EXITING:case PRE_EXIT:St=startOrEnd(ht);break}St!==void 0&&updateState(St,gt,yt,bt,mt)},[mt,ht]),Ct=reactExports.useCallback(function(St){var At=function It(Ot){switch(updateState(Ot,gt,yt,bt,mt),Ot){case ENTERING:xt>=0&&(bt.current=setTimeout(Et,xt));break;case EXITING:vt>=0&&(bt.current=setTimeout(Et,vt));break;case PRE_ENTER:case PRE_EXIT:bt.current=setTimeout(function(){return It(Ot+1)},0);break}},kt=yt.current<=ENTERED;typeof St!="boolean"&&(St=!kt),St?kt||At(nt?st?PRE_ENTER:ENTERING:ENTERED):kt&&At(it?at?PRE_EXIT:EXITING:startOrEnd(ht))},[Et,mt,nt,it,st,at,xt,vt,ht]);return reactExports.useEffect(function(){return function(){return clearTimeout(bt.current)}},[]),[STATES[pt],Ct,Et]};const defaultConnectors=({app:et,walletConnectProjectId:o,coinbaseWalletPreference:tt})=>{const rt=et.name&&et.icon&&et.description&&et.url,nt=!(typeof window>"u")&&(window==null?void 0:window.parent)!==window,ot=[];return nt&&ot.push(safe({allowedDomains:[/gnosis-safe.io$/,/app.safe.global$/]})),ot.push(injected({target:"metaMask"}),coinbaseWallet({appName:et.name,appLogoUrl:et.icon,overrideIsMetaMask:!1,preference:tt})),o&&ot.push(walletConnect({showQrModal:!1,projectId:o,metadata:rt?{name:et.name,description:et.description,url:et.url,icons:[et.icon]}:void 0})),ot};let globalAppName,globalAppIcon;const getAppName=()=>globalAppName,getAppIcon=()=>globalAppIcon,defaultConfig=({appName:et="ConnectKit",appIcon:o,appDescription:tt,appUrl:rt,walletConnectProjectId:nt,coinbaseWalletPreference:ot,chains:it=[mainnet,polygon,optimism,arbitrum],client:st,...at})=>{var ct,lt;globalAppName=et,o&&(globalAppIcon=o);const dt=(ct=at==null?void 0:at.transports)!==null&&ct!==void 0?ct:Object.fromEntries(it.map(ft=>[ft.id,http()])),ht=(lt=at==null?void 0:at.connectors)!==null&<!==void 0?lt:defaultConnectors({app:{name:et,icon:o,description:tt,url:rt},walletConnectProjectId:nt,coinbaseWalletPreference:ot});return{...at,chains:it,connectors:ht,transports:dt}},isWalletInstalled=et=>{if(typeof window>"u")return!1;const{ethereum:o}=window;return!!(o!=null&&o[`is${et}`]||o!=null&&o.providers&&(o!=null&&o.providers.find(tt=>tt==null?void 0:tt[`is${et}`])))},isFamily=()=>isWalletInstalled("Family"),isRainbow=()=>isWalletInstalled("Rainbow"),isZerion=()=>isWalletInstalled("Zerion"),Mock=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)"},children:[jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M20.5611 8.12948C21.0082 7.90729 21.5007 7.79167 22 7.79167C22.4993 7.79167 22.9919 7.90729 23.439 8.12948L23.4408 8.1304L33.0387 12.9293C33.577 13.197 34.031 13.61 34.3478 14.121C34.6649 14.6323 34.833 15.2218 34.8333 15.8234V27.2595C34.833 27.8611 34.6649 28.4511 34.3478 28.9624C34.031 29.4733 33.578 29.8858 33.0398 30.1535L23.4411 34.9528C22.9919 35.1775 22.4963 35.2947 21.994 35.2947C21.4918 35.2947 20.9964 35.1777 20.5472 34.9529L10.9475 30.1531L10.9452 30.1519C10.4071 29.8808 9.95535 29.4646 9.6411 28.9504C9.32739 28.437 9.16312 27.8464 9.16673 27.2448L9.16675 27.2417L10.0004 27.2475H9.16673V27.2448V15.8239C9.16705 15.2223 9.33518 14.6322 9.65222 14.121C9.96906 13.61 10.4221 13.1976 10.9604 12.9298L20.5592 8.1304L20.5611 8.12948ZM21.3031 9.62267L11.8706 14.3389L22 19.4036L32.1294 14.3389L22.697 9.62267C22.4806 9.51531 22.2416 9.45905 22 9.45905C21.7585 9.45905 21.5194 9.51534 21.3031 9.62267ZM10.8341 15.8241C10.8341 15.7785 10.8362 15.733 10.8401 15.6878L21.1663 20.8509V33.3983L11.6955 28.6629C11.4352 28.5315 11.2159 28.3297 11.0638 28.0809C10.9116 27.8318 10.8321 27.5452 10.8341 27.2533L10.8341 27.2475V15.8241ZM22.8337 33.3923L32.2967 28.6608C32.5576 28.5312 32.7772 28.3313 32.9308 28.0836C33.0844 27.836 33.1658 27.5504 33.166 27.259V15.8243C33.1659 15.7786 33.1639 15.7331 33.1599 15.6878L22.8337 20.8509V33.3923Z",fill:"url(#paint0_linear_3546_7073)"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M10.8341 15.8241C10.8341 15.7785 10.8362 15.733 10.8401 15.6878L21.1663 20.8509V33.3983L11.6955 28.6629C11.4352 28.5315 11.2159 28.3297 11.0638 28.0809C10.9116 27.8318 10.8321 27.5452 10.8341 27.2533L10.8341 27.2475V15.8241Z",fill:"url(#paint1_linear_3546_7073)",fillOpacity:"0.3"}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_3546_7073",x1:"22",y1:"7.79167",x2:"22",y2:"35.2947",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"white"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"white",stopOpacity:"0.7"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint1_linear_3546_7073",x1:"22",y1:"7.79167",x2:"22",y2:"35.2947",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"white"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"white",stopOpacity:"0.7"})]})]})]}),Injected=({...et})=>jsxRuntimeExports.jsx("svg",{...et,width:"32",height:"32",viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M15.6505 3.64041C15.6501 3.64062 15.6497 3.64083 15.6493 3.64103L6.05165 8.43985L16.2501 13.5391L26.4484 8.43987L16.8508 3.64103C16.8504 3.64083 16.85 3.64063 16.8496 3.64043C16.6632 3.54806 16.458 3.5 16.25 3.5C16.042 3.5 15.8369 3.54806 15.6505 3.64041ZM28 10.4592L17.5001 15.7091L17.5 28.5205L27.248 23.6465L27.2508 23.6452C27.4757 23.5334 27.665 23.3611 27.7973 23.1477C27.9297 22.9342 27.9999 22.6881 28 22.4369V10.4592ZM15 28.527L15.0001 15.7091L4.50006 10.4591V22.4333C4.49831 22.6849 4.56687 22.9319 4.69807 23.1466C4.82896 23.3608 5.01696 23.5342 5.24095 23.6475C5.24148 23.6477 5.242 23.648 5.24253 23.6483L15 28.527ZM14.5207 31.0824L4.12104 25.8826L4.11759 25.8809C3.47681 25.558 2.93902 25.0625 2.56486 24.4502C2.19154 23.8394 1.99597 23.1365 2.00006 22.4207V10.0486C2.00044 9.33234 2.20062 8.62972 2.5781 8.021C2.95529 7.41274 3.49457 6.92167 4.13537 6.60291C4.13585 6.60267 4.13633 6.60243 4.13681 6.60219L14.534 1.40359L14.5368 1.40221C15.0692 1.13767 15.6556 1 16.25 1C16.8445 1 17.4309 1.13767 17.9633 1.40221L17.966 1.40358L28.3633 6.60219C28.3638 6.60245 28.3643 6.6027 28.3648 6.60295C29.0055 6.92171 29.5448 7.41276 29.922 8.021C30.2994 8.62973 30.4996 9.33168 30.5 10.0479V22.4376C30.4996 23.1538 30.2994 23.8565 29.922 24.4652C29.5448 25.0734 29.0056 25.5644 28.365 25.8831C28.3644 25.8834 28.3638 25.8837 28.3633 25.884L17.9664 31.0824C17.9663 31.0825 17.9665 31.0824 17.9664 31.0824C17.4316 31.3499 16.8415 31.4894 16.2435 31.4894C15.6455 31.4894 15.0554 31.3499 14.5207 31.0824C14.5205 31.0824 14.5208 31.0825 14.5207 31.0824Z",fill:"#CCCCCC"})}),WalletConnect=({background:et=!1,...o})=>jsxRuntimeExports.jsx("svg",{...o,width:"32",height:"32",viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:et?{background:"var(--ck-brand-walletConnect)"}:void 0,children:jsxRuntimeExports.jsx("path",{d:"M9.58818 11.8556C13.1293 8.31442 18.8706 8.31442 22.4117 11.8556L22.8379 12.2818C23.015 12.4588 23.015 12.7459 22.8379 12.9229L21.3801 14.3808C21.2915 14.4693 21.148 14.4693 21.0595 14.3808L20.473 13.7943C18.0026 11.3239 13.9973 11.3239 11.5269 13.7943L10.8989 14.4223C10.8104 14.5109 10.6668 14.5109 10.5783 14.4223L9.12041 12.9645C8.94336 12.7875 8.94336 12.5004 9.12041 12.3234L9.58818 11.8556ZM25.4268 14.8706L26.7243 16.1682C26.9013 16.3452 26.9013 16.6323 26.7243 16.8093L20.8737 22.6599C20.6966 22.8371 20.4096 22.8371 20.2325 22.6599L16.0802 18.5076C16.0359 18.4634 15.9641 18.4634 15.9199 18.5076L11.7675 22.6599C11.5905 22.8371 11.3034 22.8371 11.1264 22.66C11.1264 22.66 11.1264 22.6599 11.1264 22.6599L5.27561 16.8092C5.09856 16.6322 5.09856 16.3451 5.27561 16.168L6.57313 14.8706C6.75019 14.6934 7.03726 14.6934 7.21431 14.8706L11.3668 19.023C11.411 19.0672 11.4828 19.0672 11.5271 19.023L15.6793 14.8706C15.8563 14.6934 16.1434 14.6934 16.3205 14.8706L20.473 19.023C20.5172 19.0672 20.589 19.0672 20.6332 19.023L24.7856 14.8706C24.9627 14.6935 25.2498 14.6935 25.4268 14.8706Z",fill:et?"white":"var(--ck-brand-walletConnect)"})}),MetaMask=({background:et=!1,...o})=>jsxRuntimeExports.jsxs("svg",{...o,style:et?{background:"linear-gradient(0deg, var(--ck-brand-metamask-12), var(--ck-brand-metamask-11))",borderRadius:"27.5%"}:void 0,width:"32",height:"32",viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{d:"M27.2684 4.03027L17.5018 11.2841L19.3079 7.00442L27.2684 4.03027Z",fill:"var(--ck-brand-metamask-02)",stroke:"var(--ck-brand-metamask-02)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M4.7218 4.03027L14.4099 11.3528L12.6921 7.00442L4.7218 4.03027Z",fill:"var(--ck-brand-metamask-08)",stroke:"var(--ck-brand-metamask-08)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M23.7544 20.8438L21.1532 24.8289L26.7187 26.3602L28.3187 20.9321L23.7544 20.8438Z",fill:"var(--ck-brand-metamask-08)",stroke:"var(--ck-brand-metamask-08)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M3.69104 20.9321L5.28117 26.3602L10.8467 24.8289L8.24551 20.8438L3.69104 20.9321Z",fill:"var(--ck-brand-metamask-08)",stroke:"var(--ck-brand-metamask-08)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M10.5327 14.1108L8.98181 16.4568L14.5081 16.7022L14.3117 10.7637L10.5327 14.1108Z",fill:"var(--ck-brand-metamask-08)",stroke:"var(--ck-brand-metamask-08)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M21.4576 14.1111L17.6295 10.6953L17.5018 16.7025L23.0182 16.4571L21.4576 14.1111Z",fill:"var(--ck-brand-metamask-08)",stroke:"var(--ck-brand-metamask-08)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M10.8469 24.8292L14.1647 23.2096L11.2984 20.9717L10.8469 24.8292Z",fill:"var(--ck-brand-metamask-08)",stroke:"var(--ck-brand-metamask-08)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M17.8257 23.2096L21.1531 24.8292L20.6918 20.9717L17.8257 23.2096Z",fill:"var(--ck-brand-metamask-08)",stroke:"var(--ck-brand-metamask-08)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M21.1531 24.8296L17.8257 23.21L18.0906 25.3793L18.0612 26.2921L21.1531 24.8296Z",fill:"var(--ck-brand-metamask-06)",stroke:"var(--ck-brand-metamask-06)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M10.8469 24.8296L13.9388 26.2921L13.9192 25.3793L14.1647 23.21L10.8469 24.8296Z",fill:"var(--ck-brand-metamask-06)",stroke:"var(--ck-brand-metamask-06)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M13.9877 19.5389L11.2196 18.7242L13.1729 17.8311L13.9877 19.5389Z",fill:"var(--ck-brand-metamask-09)",stroke:"var(--ck-brand-metamask-09)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M18.0023 19.5389L18.8171 17.8311L20.7802 18.7242L18.0023 19.5389Z",fill:"var(--ck-brand-metamask-09)",stroke:"var(--ck-brand-metamask-09)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M10.8468 24.8289L11.3179 20.8438L8.24561 20.9321L10.8468 24.8289Z",fill:"var(--ck-brand-metamask-03)",stroke:"var(--ck-brand-metamask-03)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M20.6821 20.8438L21.1532 24.8289L23.7544 20.9321L20.6821 20.8438Z",fill:"var(--ck-brand-metamask-03)",stroke:"var(--ck-brand-metamask-03)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M23.0182 16.4565L17.5018 16.7019L18.0122 19.5387L18.827 17.8308L20.7902 18.7239L23.0182 16.4565Z",fill:"var(--ck-brand-metamask-03)",stroke:"var(--ck-brand-metamask-03)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M11.2198 18.7239L13.1829 17.8308L13.9878 19.5387L14.5081 16.7019L8.98181 16.4565L11.2198 18.7239Z",fill:"var(--ck-brand-metamask-03)",stroke:"var(--ck-brand-metamask-03)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M8.98181 16.4565L11.2983 20.9718L11.2198 18.7239L8.98181 16.4565Z",fill:"var(--ck-brand-metamask-10)",stroke:"var(--ck-brand-metamask-10)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M20.7901 18.7239L20.6919 20.9718L23.0181 16.4565L20.7901 18.7239Z",fill:"var(--ck-brand-metamask-10)",stroke:"var(--ck-brand-metamask-10)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M14.508 16.7021L13.9878 19.5389L14.6356 22.886L14.7828 18.4788L14.508 16.7021Z",fill:"var(--ck-brand-metamask-10)",stroke:"var(--ck-brand-metamask-10)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M17.5017 16.7021L17.2367 18.4689L17.3545 22.886L18.0121 19.5389L17.5017 16.7021Z",fill:"var(--ck-brand-metamask-10)",stroke:"var(--ck-brand-metamask-10)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M18.0121 19.5388L17.3545 22.886L17.8257 23.2099L20.6918 20.972L20.79 18.7241L18.0121 19.5388Z",fill:"var(--ck-brand-metamask-01)",stroke:"var(--ck-brand-metamask-01)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M11.2196 18.7241L11.2981 20.972L14.1644 23.2099L14.6355 22.886L13.9877 19.5388L11.2196 18.7241Z",fill:"var(--ck-brand-metamask-01)",stroke:"var(--ck-brand-metamask-01)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M18.0615 26.2917L18.0908 25.3788L17.8455 25.1628H14.145L13.9192 25.3788L13.9388 26.2917L10.8469 24.8291L11.9267 25.7126L14.1155 27.234H17.875L20.0736 25.7126L21.1533 24.8291L18.0615 26.2917Z",fill:"var(--ck-brand-metamask-07)",stroke:"var(--ck-brand-metamask-07)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M17.8258 23.2096L17.3546 22.8857H14.6357L14.1646 23.2096L13.9191 25.379L14.1449 25.163H17.8454L18.0907 25.379L17.8258 23.2096Z",fill:"var(--ck-brand-metamask-04)",stroke:"var(--ck-brand-metamask-04)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M27.6806 11.7552L28.5149 7.75041L27.2683 4.03027L17.8257 11.0387L21.4575 14.1109L26.591 15.6128L27.7296 14.2876L27.2389 13.9342L28.0241 13.2178L27.4156 12.7465L28.2007 12.1478L27.6806 11.7552Z",fill:"var(--ck-brand-metamask-05)",stroke:"var(--ck-brand-metamask-05)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M3.48486 7.75041L4.3192 11.7552L3.78916 12.1478L4.57441 12.7465L3.97566 13.2178L4.7609 13.9342L4.27012 14.2876L5.39892 15.6128L10.5325 14.1109L14.1644 11.0387L4.72164 4.03027L3.48486 7.75041Z",fill:"var(--ck-brand-metamask-05)",stroke:"var(--ck-brand-metamask-05)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M26.591 15.6122L21.4575 14.1104L23.0181 16.4564L20.6919 20.9716L23.7544 20.9323H28.3186L26.591 15.6122Z",fill:"var(--ck-brand-metamask-01)",stroke:"var(--ck-brand-metamask-01)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M10.5326 14.1104L5.39897 15.6122L3.69104 20.9323H8.24551L11.2982 20.9716L8.98168 16.4564L10.5326 14.1104Z",fill:"var(--ck-brand-metamask-01)",stroke:"var(--ck-brand-metamask-01)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M17.5018 16.7018L17.8258 11.0381L19.3177 7.00391H12.6921L14.1645 11.0381L14.5081 16.7018L14.6258 18.4883L14.6356 22.8856H17.3546L17.3742 18.4883L17.5018 16.7018Z",fill:"var(--ck-brand-metamask-01)",stroke:"var(--ck-brand-metamask-01)",strokeWidth:"0.269931",strokeLinecap:"round",strokeLinejoin:"round"})]}),Coinbase=({background:et=!1,...o})=>jsxRuntimeExports.jsxs("svg",{...o,width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("circle",{cx:"10",cy:"10",r:"10",fill:"var(--ck-brand-coinbaseWallet)"}),et&&jsxRuntimeExports.jsx("rect",{rx:"27%",width:"20",height:"20",fill:"var(--ck-brand-coinbaseWallet)"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M10.0001 17C13.8661 17 17.0001 13.866 17.0001 10C17.0001 6.13401 13.8661 3 10.0001 3C6.13413 3 3.00012 6.13401 3.00012 10C3.00012 13.866 6.13413 17 10.0001 17ZM8.25012 7.71429C7.95427 7.71429 7.71441 7.95414 7.71441 8.25V11.75C7.71441 12.0459 7.95427 12.2857 8.25012 12.2857H11.7501C12.046 12.2857 12.2858 12.0459 12.2858 11.75V8.25C12.2858 7.95414 12.046 7.71429 11.7501 7.71429H8.25012Z",fill:"white"})]}),Family=({...et})=>jsxRuntimeExports.jsx("svg",{...et,width:"120",height:"120",viewBox:"0 0 120 120",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{backgroundSize:"100% 100%",backgroundImage:'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAAC0CAYAAAA9zQYyAAABQGlDQ1BzUDNDAAB4nGNgYHyQk5xbzKLAwJCbV1IU5O6kEBEZpcD+iIGZQYSBk4GPQTYxubjAN9gthAEIihPLi5NLinIYUMC3awyMIPqybkZiXopc+xz3pvOzD4rlWyascy2VY8APuFJSi5OB9B8gVkkuKCphYGAEuoZBqbykAMR2AbJFkjMSU4DsCCBbpwjoQCC7BSSeDmHPALGTIOw1IHZRSJAzkH0AyFZIR2InIbFzc0qToW4AuZ4nNS80GEhzALEMQzFDAIMxgzMONWxgNc5AaMCgCAov9HAoTjM2gujicWJgYL33//9nVQYG9skMDH8n/P//e+H////8GBiYZzEwHBBB6G++z8Bgux/EQoh5AfkbzYHBtBUhpmHBwCDIxcBwoqIgsSgRLMQMxExpmQwMn5YzMPBGMjAIXwDqiQYAOQZcLsEClb4AAGmfSURBVHgB1b0J1G3HVR6497n3/98o6Q0anubBludJeAiTbYwd2gGC6UACBFZY7gVNB3CaJEB3VhbQhNW9OtDQkAYSIOkEGhJCGJrEBGzJkrEsT7Jky5JszXrSexqf3qw3/v891TXsvWvvferce/8nyabrvfPfc+rUqdq166u9d+06pwrP+/CHA3AI8RQRmqFxbyRliVdpcSQ9jj27IASwdAVHVxi7l65hcZAn6NlFdOOce4vCgB5Fc5iXdiN1abSFP1/2PrRoUtiYR/Oy9C9Tr7EwNVc4pwojTDFxC0CMI2nH8hwlhX4D5ZOvWwzy9cHlS8FlzhfwZNlyDN2pPlSXwT0VAtd7yTL8+SDuHOvCzzKdyOButIeuj6HfpTXtu8Ew3WD6NpjnALnFuI1IPB9GK0n5ZiCM9H4GyTJhLqAX1GHZMoJK70Etp0tK4nlhLqBfQF08CFnAgPrN8SHMz0N1YmjluYGwNKDnSeV5DEOnttHnpZ7fKBDyuWJWUHnKqWLUsgyaJ4WbjT2nDv56TCWL6gaw0vklrAv/vpD2mNcWrTpAI00+H9G0G5XWU/1gs8fBSCM1gMq/Y/d9BzD3WiqUpS4zQakyBkDQ6k7HQ5uZi4CgQepphJE66DiuC9PM57lcpsU1auA6Ul1Q1S399o6mF1qXFDq5NbyHqi7QoBmZ5wp8wdn+3G6o6qifRV0vQ3QtbxGwPUbT+RSXeEj/NiUyqQwP5BaIOw8Gl94HAwTKS0viXkk1fejeru02k2+jrNb1gE7d4GA7YwtEYYEtHyhN0HWh6/Q7AQV4bmidPwzDaF00rbpdGnHQqI+vh26LoPjNdQCi3XeAlL7zcaA6g5PYCDBqMup70xahvpK2DkMACmjVvc4904EFApL08dJgAAxVUX3OTEIlFcYYigooPi9fZ0nPtCj6fKPr+2MSD+fUARzNDBCJ0yBR9ZT6qjKC8jRImcxfvuf4b84pLXBdsG1bG94pLSL00i0taHpdP4rv6XnoOiut1aDSaCyYI3AV7aM29KAyc1QwNqSyZ5gHdEcM7kbyaAXfmOYg5vaF2MrQxCzFGFZ3Oj9dH98xPc263t0YQKAdPCA0CHxn1CDo+Z4ysSQvrovTPjkksHCdoLYDtOpCaY3AAZgvYBjABFShWdGfjs7VKcepugSiS3dK/6vt80HHUnVfalA4b2CHDROCG1uDmM87dd4Cgy5HiG1I2OB6uwEC9VhOhxosytZrSSAg2nU9dZ2wRT+MaB+mXwdtd7pD6qJA3ENtQCOxAYZ2d6M+Y3w2dQEL9rntQXXSAGOaO2f+zcACGZVwMRJZ5QtULxE+/OvKHAvTFhMs7bZx5XyOVNZg7kAxT0nkTkmNVNFunoRz6rZXKi4xxvR2YhoDm5ntJRxxroJhBMQtIHe+vj6e8muBTMwKJgFqg/eUV0/8aNWnWRfn/QBV/gDUrh2w0Un9PZMv063axEtfXxehn/JhgdNzHRoDQM2fWiU12Hb3OMyV0K3KeDAbadUA8AQsIDqVRqS1VndOOoCuWCBmIavgdE0MI/D2JCl61eAi7RSYWVWO1Rddp9QN7evQAnk5tJyRUgemknQ6rgMfyozyoNHqfTDo1PWAtkQWuhttxveB6lDqpWtQz7XG0HTqw8fNFF3mOWU+5eKcRNYSG6AN6qk2wNHZKWJPkgqQHstSFZxUpvOJZhTlNaHryQig828AwBFzoFQ0MQ8ziDOYMTGhJ6akhq+gnjGoYWjD8YBEQK0GFbrjAYyD2AAhd6KSFQNZQBCcOMDaTj1wfahjgjU5pB7U2B1UbcPqfCDJuC6qzYxWTPGR3xPTBqm9dD1R6gLAHdO2SSDaU6MJX/u+CA3XMWdES0edk6UzUr14nNDxs/QrfnPlANBSnmkKCsNTQ6gGk+r1A3uR47ykggrmibrWcRbQLOGGErEVqkRT6jjm2qtG5/MJAXwGwajApunhB0QODFrTtECd03VWwmk+1QqEobnBEjrTXkDOkjkBYUIgSHGmkyIaST/wCuCQnk4ETW2TBOSBSei1UkMDcJlFkBBPu0mhnwA6I3BO0nlMs574SrydoRt7Qe0A2VRRYDbjKIVRI6kpvpgcaJWjrkCnC8Wh50I3rkhhdT1RQJ5AZaIBNjZUdqOHDtSub2xEB+5YTpSQM2ApUk0PaA0wEF3Du/qBBcBE1Vnbn1wXAKtxuNzg6qCBrTtlp0FO5Zl0YMHMdeBfDUoteSe+ftxhVVov3TWPQNOv24bbIZ33SaOU81mU4h1pmBkdPEBE6rg6yLgIQAb1fvAbPF0UN5hY0b3GxI+AWYOXwTzRYCYglHN7TzPQgDoUM0QTUCUrSzEl4bCaGTOodhoDPEvr9Gwo5kp+tsOB71ZLpPpb6DYN7+qLyBpJaRwYDqiCrouugx8HxLqzNJ5BBbnutMYT4iUoCYNkBhWTCJrmoBU0heaJ/Or2BlUbMjWAgdww9aCAWOoQUnukMgjY8VgHEBM3g5qvCcAz6vxsZg0EkBIOmsfW5OCEKpGW2PMkM/fwdD51gJ4OAA71GfRmS2oAa9MOJxpIMkOpeJZiufGKqVFUNWSmiS2HKObKhJiuxw8AUMtnerDS5U2nOh6gdMD1YL5hFZYChfpbxwDa/scMBLYnRf1C6aCdgF55CAhMpmWx2vBm4Ad2LMNAnrTa1LW/RkVQvz0SqEmbzLDSOyOAI4E4CyqlTGYAYusz9tiG7uhX28/efQsNoFsJ7aTVIjNDwAkV2CsUxyCepgEIn9MzU8VII6mBTZxu0Mm4LxZgFk9HH9hOLoydEUNnGeCJjpAlQxo4zrB6C/TslkhodLYmWM1R60qgRjAdskq5CuiuYkB0pAZzoQVIqiHVAXPdZoE7axBg8AAraFDTL41ATVsyLRMPaAJz4k+HOJDURZr7+tiKsJZhM7AnwTIjzZN+14nvqdz19BsHjetprBH6iq0krWO8ES5OUouzAut7MQxs78qbagaAIV7hSR2+FwuDSBJPiTHTzsalgqY0us73FSgK07vCQG0OKsIDeQuyT0M1fC82clFjEwZ1aphQ8u9j3myKGFCr+gFJBRiRVtV0AiPhJtToDPTKJwvu5KGRupBUyx0T2EYO1VSCamumDjkDZUqxlA7VG1AHuEPtqr0YRiKHInSqhq0dtQ7WM+VO42DtlCylCdgzoT+QidFl4dLFmGw/0zQ3BvqNQM64i/HrDNqgXsrCOkcR9GA4uPc7FKiH73JQZtq3DNBQXQrMGsgGxJHQBOQVD/RScJVwWCUgWEEjhBYGBlHB1b5ij0Yqm+w1sTeBwIDk4bAN4AdTnZNqbFMycLWZNAUwEk1AQLDNT5PNL1PtSH+oSPbozUgDyYAqJliPfzU41sksYcnNklGm+509WQFNNjSoekDxykwRlLSm9KFAll18bIYBtbuRNsjjGDVucQIl//ZdHiCugRWWeZzUB4lc122OzMnqj0elVVEBHxRd1YbGxswSWneOPrRknjgJzQBeSQXEXlriC4jzgWAGi2xf8UBjU6zohaurcPnmzXDhpk2wfTrN6VJYiww4urYGz545HY8z8FQ8nl9fJ3VTGmad6ElgTnlP2FOAIICBUAEFaAFQzQ0w9r4e3IrXgyVYKEp4c6J902a4YssW2BXrcIGifT0mObJ2Fg6ePQvPpuP0aTg163MjBCqnF7o7GkwFMg0YLKTaMZCEZ5+8FUwMYgxBBniTGDPpap0Sz/PAkbr6aqR9T+T3ZYnvkfYdK6uwQoPztShNj6yvwcHI70OR/wfi71oocnKSNVDRmKklspuuLzRnV12H1L4I1P0K3mKesZoQLRAxwQCgvl0Itl49COKNIBLhBM5tJ+2Lbb+z9zUXScUgJRBHBqxgjVtByEcBeKxsVwBfGFmBsDsy7y07dsDrLjgfrti61fiijXoBG1Lc/pOn4LaDB+ELR4/CExHoE6h2bx6ksInCg8v0r3MAgDqZoDutsZs7HhBSJ8y9IsDO1RV4285d8MZI+1WRdmjQPhYeO3kSPnv4MNx97Dg8d/ZMAW/uOB3Z0oX2DBJkSVht7p5MFxYG0oaBtARWLcJ1wcD+4BA73Ap89a6d8NadO+G6bduk8y0KqaxHnj8Bdx45DPcePw6HI8iZ71nDTAqPOnLfFewEKLosZDv6LCIBtmfXjwCbQd0pHgplJJmDaT9Kt+MjHwk8KzaQ0NAYAPJvNicSgK1kLkeXpfCKiqu2NKu3ItleFpn4zgsvhOu3b4ctkwm8kHB6NovgOJLB/cCJE1k6BG50UDNxoQ5okMSz7rzae6HtzokAuaS7LoL37ZH2V5+3HbZON/w1mwlnorS668hR+EwE94PPP0/mRPWArIdgBl3F2xGMXz6HUA2PjqU0qAF3KGB/VaT5a3ftjkDeAdsi7QHOPSS+fz7Sfnuk/eHIdx6j5MkUoj0da3Tocx233vO9XsxGGUuE6n/n+vo3FLOpvDMCWrtl6mDASWMA671g4HYKzPE+S+gVksgrnQI0VKYmc+JvXroHXhGBPO06eDFDqmgCx588+SQ8dupUUUuIakDGDAABM1uKqEAsPmg2LWg0tCNKte+96kp4RQRFt6REWzakBrvv+PPwB/v3Z9Ok0A7i1eBJojqrCKJ1St1BNA2bUEDSOMTEF0VT4u9ccTm8MWrDTS8y35O34gtHj8EHn34q0r5WXHohmYAgIE6/ZxuA1qBOgF4nQK+HOljWM6UMaDZD+Bp33Xxz0CaHnhmc52NOYNbSeVWBd8VdywCQ7Ll3XXQRvOfii7JkaIWNSosxSCVb+2PPHYQ/fvIJksQo7wME9aAfQ0xATUJAsTETs1L811+4G755z55RbfJi0v6JSPtHDhwgW5VnRosZUj02QTSOJyKra3LzrcZn3x35/k2XXAI7VlfgpaT9yNnE9+ci7c/KmCWZSwLoBFqwYD4bO0MaNM76XtLMwIGaB8TpnREqS795mTvurltuCaJuQzBvvlW7y87wMWjT+aoyMzKQs6nRxQFGBfOUpNv2CIIkHb4q2msvBkOXZfDnjhyB33p0b2Za1j7Kfg5gvTnFi6EnWbJ+jwDu4G9dfjm8ddcu+HLSfmek/T/t2x8HjzOlaQqoxdMR9Dsiyk/bFzAngfM9V14B74yA/nLRnvL89KFD8B8j7Wtk+qUB4zowgIskzucB5HyNJHO6z+aKMT+CMrNC48MHA2iwgz8D6K4TG9hIZgEzCLg3sX0NNOqMBe6Oqu6HrrsWLo+j/40GPSgcY+BY4LTPxFH5P7/vfng+AmNKkpols6TDAuKJPFsAcX40MX7k5S+Di6IHwOcbXkKaOSTT41cfeih6SNbFF6xfudQ0VDdnAcN5UYj841dcD5cpvnvazoXmscGuj9sXTb5/8eBDcCJ1yA5zR0yS+GwC9qzPQD4DUCV1qCA+21vTQ3zxLVDT0XkwyygZ3bsWQC4eBOuLJjuT/bJTSsv2cpIS26YT+B8jIOaBOcw5ACzzwxLpfdqLIxj/yateCTsjLezDLrOWoUz6xCN1wNUcTxM+8cGdEcwfePnLDZiXpWEjNM9Lm9x/P3jttdF2n+aIRHv2HvFv5j/Vg/hfbP0p/Nj1L4dLI99btL0QmmHJuOS+/PFXviK6AKcZC0lIVCFZvDlm4goAzNt/+gDCKGITsymY2Vk5x6HbLoOYZv8Q0cyUsSuLz6eB3paKPWwaH/yxCIjdDhAA4yB8oWEsz+TT/tFIy7YotbJ/FoqfXA9icx1K14etUdP8wHXXRdpXR8v5ctCdQgLlD0RQbyVbMQsNHnhD0pQdTV4V03FTbKvUEa9wbkRd1osdxvJMwuSHIh+3RH5mUCczKJDQwzp/IJNYIRiBarCovEwcPE6rVG4k4BlCfmlHu4D8Sy/sh8xqi1Tf9111VXTUb5HWCvqAL++RQmrg74r2JKT3B/o+D/hEYkDxj2fAxOM7or1/6ZbN0lhfrqMfof2yrVvgu6++Kr8TAQQMkWpQ/L1pliIB5TuvuCLWdcuXnfYW3SlcRXzPcQqU5lVWsO/PdAp7nZPMgxluCnV4pG1JgIGETrf1K5R62rcQRUzNPE1+xB7ee8nF0c+5SzLVFQwNTmuwvxghjFy/OQ7s3hcHeOkLizRb1ZG0Tu8cYF80y7suvhjeSIPXVj4vEomjYYz2115wAXxDpC3RWKamifaYgGl/T/RkfG30j4/l81LS7vPX52+LfH9XpCthIwuTAFkay3Q8VN8/v5ZbDmhaDC1wdwMgq0FhzdD2EHnHFqDOygHbL2UgtXtlJYOCy9Ijz6B+5RysGmkBeyMNEUae4eu3RffbxXGKOvFWXm/MXoEeLki077lk8Py5gOFcaB4rj8+/Mfrvz4/2cT8rHbC8OlDAvCvOuL7z4osG+W2E9hdCcyten39LpP3S1U3lDUEynXhsVj+WAPNujFgIjEXKK3umDCaR3zdBaAE7hQ6UkR7Um1dQ3+LStk5ShcmX+LejykvA4AoxOMNYhdGCXqQ6Abtn6Q3LHbAgPvnA33fl5TCLo+9AhfDvt0Xa03sNPh9Ysuxl6Fg2bav8RNu3RA2TrvI3lUR3mtj45ssugy1q5u/FouNc+Qzu/LyIif82mnKJ1uyfCEraOiBrSZzGb4IxJZH1dQG2KlQjXq7pqvYO/Uph8QTwb5J2aaYnzf69Kc5E+RoGOg/+gJGggM00eft7meAZy9evjur7+jjb10dQJ2CvR4l37bbtMf78QVqfz5crjJX/hl074cpol84izcl0Sr9Xb9sGN+zeJWm/krTPK+/1ke/plYdEM7/fzC9KCZC1V0OeVBIZrEbnIINCbTvbN++GtrQBNhFUZqSi37CfwTuiAz+5YzJTcQnGkgTmY9DjvfSmZzY6uHRF5uPN0aY7G8GcfaKR9q+O6ppnE33ar/QB7vyrI5+TPbq2Pst1+Np43QLyV5pWH59ej/jr0aRLUrr40QO9C88vMhG20L71yVhMQeNUBzOZrxN7/Egvol+2oXMhGVTllcH0rsCbd9XB1DKAA1eWGRx6JKrE6MySdm+hNCPlJkm3ParB9HLQjmjbXRslNkC7cb5SoQWQFF5NLxYl2tNk1us03+ErS/uA38Eerzv/fNgZ+Z60S5bSYSg8BWuUZwuT4OI6j3C9iqjpHfyk8QNW8Zu+8k3S+YZoamzuJpaZDqCtwd4ouAFGvR+BEjMjFqVtSY80A/raHTvh9NpaNjW2OvtT/4LLw9/zYUEfW5i2Va4+ki39mgt2RNrX4U27d2fJt0g6Amyc5jAvrQYqzOlMzgmQbOmviTRnKd0HSay/jClvWllvhuDVu+1kzDdyQ//1lCGpB21upJ6WiHt7GmEzfaqiwgBo91h9T38q5cOoaYJDcoNKp6vg6bkhejwSU18f7U//OuY8UMwDzyIwLpMWRtLo+K+6KJlM6/CGSPsi8J4rzfk6WN7XT9nASqAlAueb3HjrNAaQdesIECZbusWYRBwvrJgcPBhEhwh1qW1oLUoLcPpsbqR3Oa7Zus2+orlMMOIYqKcOogwdfHPgs2ZzREVpid2i6Yrt2+DKaGpcFgcqPixdh69QuChO/FwaeZ7q4MMLpd0IHGXmedNg9Hn368PLIs83T8qSDcnlmIM1ksupLgRdMu2hQ2wsY8CJWnlnFcCfvDCxxXZOg5Mr4/RsNufnSEU5H6slMasPrmyowPb0ttKaHsGnrYehfLz7/a98BWyaTJqS8K9K8OSn8+Si++HXvUZo1/LmnGhXHb8lCJfOM7QvjQ0cC0gfdtx19BgNxIORXg0cm3P5rhBqvQfvcmAjgzCH2rKEVcgumEs2bR6kNwM2fQ5O/XFd+grQfA9hYBer7IRWbUMbApwo8WYIh0u3DT+d+qsEZg7ebEjh4q1bBvc3Srsx/RAA8RyedXlou9nPMbBQ27N5c563KFI6qDqotwiDbetyUgnUpE45A6uiw8iKlvy5ePksP3+wG4BeVezzSygepIqmltC00tql5xNDiQNry+LQeQ7UFXeKAYeGQUu8ZVTruaSFBenH6FgE2IV0NDr9WN4BRm4w/9Hauj5/LZUlPQmqHXFwuN6XGc8cJ5KvpA668jqP0OZANTmCRwC6HqJBXpbVKgPR4ktMZsfO6LIbY0aABpBhhOkuk7JiZTud1BXbWTSqpeq0iJBmXxsN55J2o+mXSQtz0hqgIcylKbQyGbFpwlhGMJBBtU2gzNjmla7y6wdxcIjsqXEfwQawcxojKqR+A4X606QqDyxYaPlXypzX880zVfHgT96NdG5wtRJllmVogkrw5/Ix74gEIddKEyXWQqg2dtBV9OmXCBtI+pKl3UhoDZxxUVqvQkbas4X3VnwrTQrJbzyjl9nSnbqVSC2B1zSEUZpraVO9ZpgRYnrWAvVqOQRqqMtQycIuDTUwhmvd+42QNBfjjGlpHNTPeomsymxJa/ldwgTxfWHs2WUat5UNwNDEOJfgeYwNXrQGS0IDQ2OJCmi54mmw5myNSD/5S3bCDkthvY43Y80WhgYAemZX1uXwRJjtD/ggiSrrytFUJS9Ntdb3g3zsicqfajSo7AgnWjakUV9OOiMo6Y3OjgtOKyiEaknuA7rGsDcd6apcHwZAddoE5jy7LMq9jdx8BNtpuYFawqiBfwFmq6eH8WLzvfTuD+Mnf4zc1wWBAjWG4C/Ubwh9EEB7kMivNkEALLAlU6xfIMfrQ2fOwrygwWKkMcVBsCCE0KDNSxmVN5Fd74V2A+j7Uvw825oBho1ygorXtGObJtN/VL76PuCweB1QlTsgtQHkwQCYCup7MJqMXzBbpKX0SQAYdGauc3BpMAyzPr6+Jt9FzqROdUGg1rs9GZshGHwyn6ZjBGu+lAWoSwHF7KjL2aaIQIXuP3lCAGEc8uAq54HrCmaws1aQ4FoX1X2fDUtIkZbqIS2dg6s8qvOA7lmwwJdrBa65aVs0jKQfpNW9YSRt0M+4zqo7aRPgUPntaWNBpNtM918tBExnVcW0tG+i8eDpM/myeMxC9p7NNNbQdSLXiX2Y2loHVwt+URTM7J9soQCgtkwL8PCxYzZ3lrrQICLYiqP8aUgc5rCTKMF3UXAA1M/qcnF4v2VqoEqLwdanNXtViXb5jkk8Fy9pcTytpFEAb3ouNPhCOy8BH47w3AHID/SDa191a3BtOmX9gX0nnidMlQ8VeACY41AJR6jxY9u7pTynLL7NGryZWDRiP73SVwqoawLnRbiB4xAeTUtYETe0lOW6hFYtVY8HJ0m1JNeSkxvJ8XyYt6LBgEpJHANULdl0owebdlAejv9ii8hGPSUtzEkHVnJL3Rp5SRZhPEsxl9x90xah/SxHDPgPDUHUCEWDB7jr0GGpOO/XUsZpYCS0frfHrO+dC6x77ph3OXSFmkcI5uWU+hJRaeWT6zP40tGjlWBVcZM5MyOoHti6Vs9YOmqcgF3HaSkL4xJSD/JETTcaEjXQwdWlBdRBy4/ELUqLjfLcuQGzT9voOIYVaNvItEGjOAN0V2xwYNHtxGj05Dx8/Hgcd52Bmiw4XLmX0EKbxRrYHYQxTquKgj3MwuEApJbLikS3PP1UW2L6YlABERxjW+USsz1t6PI22l9JNX101H99fOvFG7nm3wD23V2+9s/jgrRjecNIOWP0wkjeisd8H4iPqPjX7Bz+NrWFFgAtkOnnTMBKiw4f3L+/rBFNpq3BWAB5+V+RaPvpYGYo1Hc5Br0xhCaIZcX5YFe+LEtsdfCnjz1e1mv2EgOlzLoCaF/j+De4Hu4ldx+cNACwkhpUgxIgOK2Ol3vQAAo4oIzdw0baMPIcNs7DAqAvQ4dLq4OPF0VsUNEGS4ARgOs2ChbUrUOeDWDGYQkjH3v6aUCqgDYtZgrIjDcWnB6bPgxXS5TBoAO3KhChuurqCv8F1M+cOg23PPkUfOtVV7KWg3pSOaMlMmgm4zDeMFeBeHRgFm8eiAPUX/uvN8Itd98Ljzz9bHmJnAYdQHUCfW5Y0GKVC75OX4GAjgGI6pdGl3yetNLVl1wE3/yWr4L3//V3wJ6dO5qg5mphcKBs1FU/Y9pUxfPGR3oskU4/8sST0YlwHLZu2SQTI7LhKNTtLVodRM65/VT81NOq24l3nLITLOU9Dl54G4mxefPytIfKpIM/2/84vPuyS2HTpLG6KDa4xyBtiASHU0D9S8/pdk2ndzyyF3783/4ePPzMgbL1wuoq1YfBqlbsDB7AwXSa5cKLhWzceCqsMSztUF3n866k2H/4KPzGh2+Gm+66B37m7/4teMdrXmUpZyk6B+iDENrxnkYvqz74+OMZK2kfFiD8yC6yAAN7uXo6lM0DNk0Kxm3H6omEtAUwsi8aRUqXtdgrqvKn5t0EbjvwLHzi2WfhGy+9rPoudal8GhYzh/2ixdNimSRpCPgp7dNHjsBP/s5/gMfi6HnTls3QTTrgr9eFKUEDur3Y4cbDQMYtkR4b58uHgmVU1ygS0KwBR+Ixz8LF2ZS9Bw/Bz/z7P4Y/+MkPwIXnn2coCiOdOYTlu62ZA9BgJto+9tRTcMfBg9CtTq0NjTwwrGt56y9jqmljcaf5YTYNkiZBNhXQVLIAuSxAy4tts0rJ2wuThJ5EUP/SPXfDDbt25w9PTd6qsAANldaQ0uLvbIlrVaf08zt/eVtssCOwGsE8XZlGQE/iDVkCR9nwQWyxcnPcLvurGgyUFS9kKwoAMMsApO/30nINa2uwL0rrf/Whm+Gn/vb7hnVWPAdoyqMBDUGZE14ia1v+udOn4dfv/SL0Xfr6e5K1esDi/O1J89e9cJwLD6qQLQJMVZqk8HSebPAyJEAFcJbUNKuTpTP9TiKAJtMJPB5nDX/v4YfgR1/zWjOy1p0GWtKAJQHdN+mGnXLA2Q994V6YblqBlc2bIh0rmR7eT4VHzWIfkqQmWQ3a1Pr/Q/DbaeQ4GvnJFhRpu7wcn+od22wWB+y5k5+FW+970OQnPGAB4u61QmgkYsmsaWP6/t9H98IXo2t38+bV3DbscgoaxIRP3oexVtjZlp4W0CaH2BlhUEGZfqSK9iSlda8pNkiXiVxJ77hGSfDvHnwQrty2Hb7tqqsNogNn7mgzQlqBGHUicNJApU/k7z9yDFY2rWa7eZpWbsoSgF5L5IKdk1zAremDNsMcKXNDeInSChFOl5PlXPmFtF5cR1I7DeLTNlhpQ6J4/vjhozUrJYb1Ng/6RGNA32e6/edP3u34l3Eg+Cv33AMrqyswjeOrpM2hKwLH+J8DezawmhoIRuhUPljMmlFbq8FEMoeqzvI0JZQtEpAkXsZzUh1RVCdCp2m9iPUz8M/uvANu2L0brti2XTJHpdKQKiGMUi1rOr+Xzq4XiPaJHapLpkZaS3lazA1WU9zri7M+iATQqkyX5XnDHaf1vgNAm4e1OkPI6mLQp9WFjKBd6hwqoHl5NqzGdH5c9u7uijadRFCtr88smMGaFyw4vAbVNDNtehZVDgXmJ54/AT/56U+RwEuAnkRaJlmjyN7lAOKA6D0tMAR0K24KDZ7lc2r0uksnmvqwlObBGm+VkBmWiY5Xqz2cOXMWvufmm+DfvvNdcP35F9AmkZYo6fTEiWDfQm2/3O2AzDSD9Ppim+XdmEKdgSrbKBd7LZUle3SEYkblvLyNpKSSLns0YCsNbjytL9NlgQElNQOnjHOwbBQPdQHxkjDfibwJNOZB40vWRQlQwljZNVp2/3XWAS/X9cSJk/C9N90EZ2K61diRVnhsk9sIaG9G/R50FTS8G5h8Fui0g6Y5hc7c1IMk0lu5PtTVOHPvpzbraEQik6E/nRbTI1XgWLTb/v7Hb4UHjx6pPVcfjpONCaAB4b5Ckm9Z4zcDOm+yQwxjpuV9s9PCuVi2HS4b8WBNg/W8z3sFduZ+jW/FdYP82mnxHNI6OmIdNK25LnIfch3T/bQ7a+nENW1S8XkgNumsKefaQeJY7atGD475DH7pXJTggcOH4e/d9JG8WedqBHI6knTuJp3gSBcZNB3KzNCf/8EgroYpqFGwF0b1RR0U/SNTkYhkhvB+00XChdz5yzYDsBIonwDPnj0N33fLzfBPb/gq+JtXX2PVujNDRFqHBoCVamtpZt2oxT/Oe/uhbFzJEkBLAlMO+g7TkK7YkKI6rWHkBtKCq5BPjzpLvbBmbT9eLVb+kOTgvbtzW3WlA4ArqmVe6JccXbOZKqA7v3HfPvi5z34Wjsfx1OYo2FbjuCZJ5zJQ74rggerVYJdw0fb1qyiRcoxB3wkVhqfMS6cxABrXtQdVYHPv7aUiJbfiwpvStG5B5um1s/Czd3wWnj55Er7r5dfDedGW0iZIAMs548NWNKBOr86RmUEHsIQOxcyozvsuL2ySpTiZF1rFNqXPWMAN3NtI2kacviQuS4fmMb0AHRU/gDs6zR1QR2cV7sHMJsigo3s6sJobYi/H4+jZM/DnceLkf7/jzuzx2kxATho7gVkPTGWvcuqsUi7jF2AgtT1PNG3NhWYM0whY+VyjP5SlDMoItPai6oHA7P7tphORGskaOLO2Dr9y793wx48+Aj/+hhvgXXmd48qcAahYuIVKQ3A0GymtGhDZrMh7pPO0Kt3vOqG9NCC9P0CACE1mgJK6MB40gWGDaeflrdIiEYNQec03i2sVqRN38tyMUicu9L6OVDc2LTy4USdDa1boLD7zzDPwC5+7Ex46djSCeKVI5vg7mRavBsrYpjzBZoN0Iqz1GJC3iJfQeJdDp8fGRVCMqB8nltlEFv/lHY+ySHXeeWVSV2fn7eGeOnUK/sFtH4M3X3gRfHeU1u+4LC0yPjHdrSWB5VqBWDc0qywg27MyivbHBm1ysJkSiO7CgaDz9CDrGvdAXaOLgzlpfZqxMJJ3BXX1bBThwa634oPONjPUmThklU6SmkVgUHQEHQfz+1paV+NjTz4Bf/rww3BrnAVcjUJsS5TKCcjpSJIZp8WrUex3EiAde6CoDEQZ2LIlUDRkQ8DAkK0pND/B4i/BRb2PqMNSKGWJaGbeOJ8M7OzIR7OBZ1p+ay322LsOH4Q7Pvks7Nq0Cb7lqmuixL4Krt+xE7bweyCKaiEFhxI7aNpp8ANYJDX7oYsqq1+r16lV8lMj2spR+lbdze+8+EVpF8VBlYrlHBWJhSPsnWHPQpXQJR3PFmY3a+Jbj9U+cNXrnYT2gQVJAvEjcYLkxsf2ws37H4f90S2XgLs1zgGsxl82MVaS63SiwUzg7IY7+labWZXnGTF2j8LiHde70rih2TDV7uGepCdoGHCFoR1lR5t2pj3Bk786VnatW4Nj62vwOw98CX73/i/Ba3buhn90w1vgDbsvqiNrxUwPbFR08UieX/EKaNcRoW+L6QWroDoGCkAss+iLHlAdRvcwGArPSh89q0yKuWkBqixqgUp5BWyfIdrJHu0oF9GgCNVTRav29B2aF314QoNp4l8Wavprnk8+9QT89r33wL0HD8GZfj0DN5sWUwZx8WQkTxeqyZMwUDGoOiWohgzDSoYhL8zkBJ2bdzncyGIYjLejlCIOfCWpAar3gPPN7xbQQjRp0iNJ6TWoWy3vXtkEb9+zB959xVVw+bbzYOvU7ketgc2VNUKVkYEgHpcisrC6nGQQRINazZScB6qBUjD15iv28zINoOJ1lNYYAezNABbYtmrtvJstQhJX92jdgUHbp2xeUHygjh+g0q5DaERw3F+79DJ444UXw31Ru378ySfh9gPPwoEzp2ETSeTslovnub3JfVqkcjUltMYx5xCknaB5rhpd45TOp55BzaCYY0ZlWlwEqC48oJdlggKNPE47amUvCMCrdu2CvxHt57dGBq120/rJTbDMNLadizNMR6RBBw9AFHjp+WK/seYJkl0gaVwYr9A3KKZVeDv5RtLOS18lGLi6IzC1JZq0ZrruCuDZwigdPNW9LLnVXGc5VPzojqabPGmArdE2fsvFe+Ctl+yBY2tn4IuHDsGH9u+HLx47UvaLx/IFk3QiZRoZ/57vwFxRb+uKhaBxOORgc1CIMGSp//5uUJBIarAtpVpCppbjvws3b4YfuO56+Gu7L8r3+c0q8I/6iwaILT1l4oBGSQPnuwGG0Kt8mxnwCAohoKU1UqfR/dkIEh8C2nuhLRPqPTRpAXU60g3iuAikPVhSS2yFeadJwWreZN50ltRgAayBDfqaeMUvqp2/ugm+bs+l8DUR3HceOgD/5oEH4bkIcp223XnRMQGbKVuxHmqcxvih7RMoX4KjtAC9DxCKqYE4LE5G3iqa7dfEsbQo33dffS18xxVX5+18jUTW57XWVkUH27HBVaA0ElKjkfM+qA7lXtDGvN1mLSuHLpjy0XGnIdeqUBkJvt04Lc5J65WgScPI5tC18iquVQSe8QVaSCYR0NkJCmJN0/8cwChvXo+QvSkyEI0Rb4ua9g07d8EfRz/0H+57nFZUqsANHQg2mnWngpDOMVRXKig8tviSzo0fuiWZwT3APbxcl0LQi3+XSa5U/HNe9Fz85KtfBW+Jg76UfBbA+D39wSG430ERWrqWjRXJBYRgjewuI0kkMNh69I1M2xgdioA5WG4+Pf+uLdvWm7UcKhMABCXycr1ko1qVToPSXgbAI4JEYYmAVuLLuiwwCJtjO3/ftdfB1du3wa8/9CAcm/W84WWdETb2L/+xqo5BDXpQDvP5JyYHKoNbZ8T3cCQbrBlAVYzCk/IhQBxa74l+yZ97zevg2q3bq2sogJHQ5hdqJtzJW0HUpLRbJ35osaeNnletzVIJQEkr1zkVHca8Gr0HTg8uEN1G1CxoLq4o6t+guF7Kqnv1odDGg+L8YlJP2qthjgXNE1ASWl3Ly0hhKGR6dfH2iy6BK7Zug5+OHpEDZ8/mWWQ2c7Rg5NP0spVwQN8DaJsc4kWisQ+03HZa2rLNxSYGQEOKq/cJlE0UmNXx2Uuib/J/ffUb4OqtWwXM/QiY5V3cMGS0x1MLQ0H21sU8wma3ox4to3JXFcb1ogvZzRbAlaFB6wE8L8zrjc30uDBv3dSIxUmHZD4hMUrkS1fbMGutbC90xQ5HrPxXgsT4oYPjf2WjlMPP8cJDoO6njUx//g1vhH941+fhUHTN5o29lamErYqhh7Adh4jJYdxc5bmpj5BfY0JY6YagdpNlVQcsjOoL88npeX5k3v/5ujfl7SqCA7Ps5qWYKcwYntbrUM+Hn2WhSCdWbahsONMiHM8vOoogx0Wy8q9EQP4rAGBxE2rHEMFdUvNsXK5zN7/niI8elHRW9yQdHR1Ld/plMi7dvAV+IYL6A5//HDyfHOFsCmqLAEBwlalDmnFW5UubaPeyEr4pzH2XgxM2l8BqPUeABQJzGgD+WJzW3hPB3Dsga6kMYNWbzm8ecaH1y7NRWkJDxbKWLEkqB6xAyA6+vkqA+XyBNuJH9eNI/EbyCPayaht1M3tVwlDFSGU64g00KyhtElyxaCV15k8Q2ZGD2NRKg/KA8cotW+GHr3sZ/MJDD2QTlN/HblW9OFpxXvVH443JYfdVrg/o32GoAxEkRCbpnDYRev+VV8G74qh3RvyVjx6DVW0M5EWgboGMn5FBEBKQlaRm+rVG4YmXOmaszn+v4kYDLhGvicZzzMPFockbQcxBJYmLAGqMfZBMDuyabjvdETS4fZPoTkpkiCFhNn2C2jbfFN16Xzp+DP746afyhBroBQO5h5hCQMZvdWIsGHb4ybHpUjzGsXviECKi6POmWRkEfssll8rdwYaNAYy7bOA6WzJ47PCAkO3o8oEsyzOa9JFrkPNiawcY2GV/BUMFNO+HbU3A6glRTwhgqKPzx6lKW0q2MJwTGITgzBBqQ7HulPmhxeh/d821cMtzB+Bw3xfes7YIunbBncHgeuzeYFs3YRS0TArbOwYVTPZzP4vM6OEfvex62B0d7t7UGAAbykyWH1mbQzEPYHhuAzUUSSFtS/M1H2VNiI4kujs6d+jnx9K37p1zWlycdkA/A6Q8i4Zm7uz10zTWUF4ocOgd7+e1j1l2IKhz/RuP7ZMV+J+vfxX0eQfZWRlrkVoWM4qaUVNWh3fYanH5nXrjXJ4USVWnseug0Kk9ILdJktDRvnjz+RfAW3fstBUMbXNDshgisxmkh/ruyT/80g37rrCtU8oFWXjKLBHN5gtONh+oPj3kay2LPAtBO283nFY3Zn15B3X7gDSRekYzQ8kxPRWKlS8esADtpgijF8N0rOwkwvHzzXHi5TXbt8M9J54v73uI6w0sr5qmQgAzsYI4tKFReTcqb9BkI7OFRtgr1RbKyjzrsxm8N/ofJzQL6D9Pp6SGgWBya7d/UCUX26kt1QXELK2okYMbrVRgFy8I22KoO3cj4AbMkRczLbbSq9E+irnU0W8gs4C4xun5fWQ2O8AKFD43g/URAHuQ61WuUnHyNT/3XSjaOEpR+PZLL4e77v9iERSqg5VHEDS6ZfYwODMDcWCC1IkVIcy95Ic1XoM5AMggsDCgz+bGZdF2/oY4EBQprA5tZoxJZ31vDNj6XkuSAgNUg5pEmbz8wxKM/LPS4AttaNUxXtKgy7Fl6rZiQAfVGUVrsqKiNmKbuZoxEzCZqnWcA6g5AU0WtinlW/4LfcEB1inzBOqv3r0bLlxZhYNRAOYPQeT9GX7jztY7SAGqrEZbdbBsUGq5UkvgTqYGSee377oQtqaPIIP+LB2Mm24emD0zlr2WjpDaU+xFqIMOusZO2dHs1tMLRstX41jvdapzmOdHDnTn89Jj49rRhnw+llbFo7qHavwQlLEs0hnB2MEBqubTkhX8NcC4hg1Drcn5azxcsLIC3xy9HrM05upDNbnE1aILC0uLkMUv+EOVxmikcwDRDInYtHliNPT/mz17bCXCEMQtZkAjDnWcEqymyugliGtoMTPUr5zSm2qctndpPTGtc4ChzD7XtO5ap0V3L5/yC0n0joShHVUm5rrUtX7eVJONfZQMYSg8WjS2Qu8S6OWY33HRRfBvHtsLOOlLpx18V1d/gzIFw5zy7KZBriba3PDACvKbattnQG+NRL32vAvs5Ik2ORxj5klnVRTRB1Vz+oQaBB3NGKRGS+9Dd0oJyeCKPkmCMnUcnA0HG7B9XfHzQ9hY1rggr/rKXnnpCrlRsIKgY3OEHhETjNfm8HlqQamiF5LiyAoj0lyPn14dsXJB1ObHI3Y6Ze4FJbwG5bNpOBKmJoE/x0Ym6CrN3o1I1FVxNihIPAzUmSbOMyHYrEcFjA4BGpJf1KlSxYoZuQzj1cAqybsRCb1IDPm0sGR6nXaZMlxDy/MdGmbkAS91Ho378kxXPUHs6XBFDMqcd3+cTPMrOLCkwuuiR+y2o4dpJ1l6E3IseHzqXwplYqUlnRq1rMCriM5xaZnWKH6v2LRlkFayCENmhJFffW56Png6hs9l6sh2lKqoypeGxkGvL14P+hpPNXTpAG06TJpavPyMpZVztGXk5yhikNbRUYuiiSKPA9brA8mgvt6RASSozgADb9QYqNHdGhM62toRgUeRaUq8P3woC0R24dVdrtCqaHFV4qBcvh68D+0TDRpGIbMuHl4k9OVbNksluIB+RDpr4C8bWkJs8LwaELHZUdIRc9jNhUoasBpOL3KEKqnH+AKN61Zj4pxrXPD8vLRyHqrJkZtYOX+T1yC9KoryDVa5F7ind50BO7fJAMwAoxLcn7faJwV245mBJ52nwWGfPWRBFv0Z9GgYCscxwSFbUjCDEGqeY8xmKc1M6DMxPVyc3qijAoNmDljmhEa+LWAjjEvqUQZifTFJv/OLyn6uJgY/UtaHkI/vEIcEtK49sQDj4mtR5TaSFlx6+hAY5X4BhJga7JqmRkWZfOqaoIQl4lokzrsXGkcK50+nWRim9+YnQZfB4MGBK9CU5ezp5tt23r2XgRPql9wazGn5liyho4djhQcZyPdcviPXY20ZYAhkfz54hiUzYm04ig+6p2p9T/H5o1pwlQdoistip4Zx0Zry7lRaiVwi30Vp+TrU2V3UqMlx/N5KAQfS8g252syjFhe57VqdGRptRTxsC5eaxC+DwaRO0xp7PUvoOEwPk6pNQGEPsfqdEcwYQYfhV9+ukUKw0XI7aNWhP3+d36vDkBeD66YEp5tjQK51ACijfiA7ml1UoZohQNKqq2BnCnLDIwgUhm6JWgM0XgJHNbq0tefAIh1l0/K9IR0y1ymDXPvqKPtyzFOsobImAwGjBnGohGgrpkFpO4L6mrkGbW6ox4omD7Q8c5AbgiHU7WMLEY0bKgF2j5VQGhCDpdB/5lIWlOmFKHaMn+2HKzxocI+B2l+3znXP9irMlJdmvzITOkA9oWDcc7TgjEiNrvCFyK+DDt0qWHsVYKPkF5LW10yn82AucXnhHiGYOhaPAVDlxy8pM3o6GnSxJ4iYyLf1uzatxWf8uadUSg42Xg8INajX88tsALw9CHIOiA47wfGMsBhq2hRGJlawimNNpDpnYiszAhw4c8YkEGKCajMVWsxyVLTvIaiJhMqknBetDT1w2ynJVDJQkhTppKP3GNEDiIjttN5EW1EESxB1pJKKJXkD2NyKUmZXy0NVvhaX4r7p1HVQC3CoorraYbIZxhMrPDBcFEYb4dyCl7VHzq4De8sEzgFk3ZQCZWw8PcRoCnZQOC8IKIPKS1aLzoBK65uNVUKDG7AthwZFamwFlxiH9Jm2V9PdbC+iXo6KXXUpiQyqUibO5FDpLSEAyki2BIrbTzcTQlMkqLSoOWI6VWjGiVyiupTlFwIYkwP7KsgJ1IHfhR5r9OB+/fmisKDNdLGHzpxWu1yR10xWuwrVtSht28hEheZOsnriodanfjdYrtU9Sv+lo0dMVnodZzHtGrgQ6a3vIQw6pCETxqQ3DwRbElmBAt15Dp27bnFtDAXYiBnrdSNpTc92PdSnTzT2TmLnx6r6KnzH+h2UpMX6bjQzUh1sGnAeVZiBUVgGqBqwpDElmvujA3U69j7/PN1U5QGBG5mkOsAFw6Kg+Ffip/OaDsTBbXnt6CfN2MGjJ07YfCihMRPVvSwV6X6v2xOHNAVdOLTpzUlY+nTki+bGk7fu6Gl97Xs9joEWYOAC8gTMedTcHEsrrYbDDu4DWwyo0BBoYRleST4zF0zd9Bp3TSqDJUeK16BDm2asKuZAe53CHYcO5gUdDVhHtLjGoKePabSbBhGAsfGQDhrg+suHE7N1uOfIEXj1BTtECxtCAYxTnEEN/p76Ne6eMKTDS+rgpHIYvHlGQ/tOZcrJ6btCSUu3tAsLtaoOtaEZ52bGT2hScWj7hC5Hp9Vli6Zr8AD1M4VAZegkBvblDbwAMksK4qeHJhINPz24AgxNFVS0oQK/l3ooJObzew4fhsNnz8KmrZuBNWt5rBpgGi8BxgMX01x9NP/wZwdYkwfu/RDcrCpmoKRnbnrqCXgNAZrHKkiNItovDCnBFsGacfNqY55RElmtcWdEBADZ01Dqgwi23+iPZw0LJI3vqeKCd5qESGqmnZt3GD47SKsBBLXs/NupXsCjcn43lDulAnrvf0EJiwDW5Ajgx2IVzKF2QvMsBzXs+C/7HiNw86KanJXqlNJulqGhD4M4lX2lqV7YIU2NDiY9q3mkrZH/095H4ejaWT0e81ga/Dqa7L0W4+YF5eEQWxoa3+Pxd/z6+73WN4PdyDH2zaD/1m/ed4MbyXtuWqx1oLoGXy64Dx8kfn4QLUhAbbE/KNCKpFYdUoSbki0n19fhpiefzPtKopiHXusODYzABSr6NHC6eRXRBXCGrDL11g98JFto/+mTcOszT1WhCCPA5huuUF7rwRhG0Eg7Qi9wBVlKo3rfOfub6yc/SGDgOJQ0uLGjewFxG8nTHVy3vGKS1EXFq06Kgii0nX6kzduMBSudhwJSNLKAVwnS3K2IhA8/sR/2nnietmmuryWIpA6s+RXQCUDBla1De0sKHYEAowYl1M+XMO9PWDYj/92HH4L3XnZlZig6LonPODgGhhEilJrT9yWJZm4AA+QUiV1tSLZ/6/d7WnzoOo/3ngF/5oSXKq0OIhz0tWJa8YagVHXoARqRumCBGwKMaktUJWozE8DKFv54KE1x/+lje8uGUoQdmfhqcMJYCsr90vrca6nN6wcdklWPTCWhmB2JyNsPHoBPH3g2rxfM9rNIaEUTzFFVnhCDaWyrQjZ/RGNojsoBYNUE1MkHwTlaOhSfscUwn5ZPfdpRhqq0rV+X1uSlz/vWbWI+zRnJjc4C2vCzYqZkyd8aNuqi95fMbFM0yJyWO2575hm47dmnodu8iSQ0vaNNhRQPFZg6t+RaK4jJYfg1gvD6fmopzXx7lmzo1OOmUwiTKfzE7Z+EE2trw3EZDPHVbDgP7jGafLwTCbwCaVZVtF5FGIC8cZAnwHzLR6bAeNpuGN+65vRj9xalbeVtxGCNs68AKPOLhJBrYBh0QNUuGGyctB3/hNq+HbTJOnDqJPzs7Z/JGOmmK1kAajpaUleEk2nnNiQkK1NhegI9UMBKSRRgM4PSlrfRcbIyhSdOn4JfufcusZs6B2JU+TAjhIeoDo4Plr/eQtGVr7OBZD8SEbxoIxoQdEbtobI/669dtEXHDY+WPe7Tdy9aWvYu1WsHXKyTKKCAzfaoB4n8jhyadYM4Hr9ilQUTdaTrP3r0Edh76gR0ar9v+QwuI0pnVvFl5R2aejJm01/jtsMBeOuLSkGii+7S343l4vKHmph73GQ2hX5lFX4v2tJvu/ASeM/lVxq1xhNXKBnTj1J180JL60s+Ipn1OtGd6kUMZLAMFB2KhgeguFPobaQdBGKw7f0ATZni00JFy2ASpzZcHXgQHUGLTRDzA5VNwO7VIDbrkNdGcKibTQsoVHKR6sCSmf1I+vjQY4/Br3/x3gjm1bKpUPZwdCJsRKhKmSisq6apIxrrgBLAezkaDVSXX2UGQ2OmiRidXXeTDOrUA0/F6J/49Cfg8RPHW9pwKLFR52aZGRo3jJRGVQctIsTe6ZR/uhPpXJct6KoYaal4oz+7kYq8GGlV2XPpoLQTdHXRYpK0ledHp+IavOSIlsWH/ly1H4N5oorg86dPPg8/dfunIyYCdKvTMiCcVI9T0BkCmEkfng6pn9LBaOhcHUYuGDRob6OKZ/EfiUxmx2Ql2kfxOBxm8Hdu/At4MlZIqx7+1W0EXB+0jJMylQQPY3Tq4XSngQE0cKV7WHdq4nhxebmGx5EDGgduIP2yaXFeeqRBlJEWYNLXDtM4Wk3ueBoabOZ26kCKGxxT+n306BH4rg9/CA716xkXk2Q7J9OUJbRkCCQwa+sHVRY06Bs0v7s2NrLEMZPSuZ9w6RQSsdiiidBJlNCT1Uh8VC9PnTkD33PTX8ADRw4bKe3bwHTAxZ1R6OXReaGHpVpn3/vN0SVeJJh0xG5wjs5nbQ1F1YFR27rdaFpYKm3XTAsL6bA0DydcbBsBS22aWGHzQgRGsKaHP/ghxpluvwmBin8fPHwI3v+RG+GJU6cyFiarqxkbWUJrDcT0UaMHwhpAo0NhbXsfOhgBSTNoCY1Qu49Bo5bSkfhNqzDdvAqPxQr93QjqG/ftNSqJe3h+NNjyvStJ3Ejuvr7WYBYA53g1KGJpTGqbvR9GbWu1bI5W3Fj6jabFJdP6vMlkEoaWZwIOTZb6+ijV3fFRL//FfGfvRnDto9stS2k6WBN//Mn98L0f/gvYf+Y0TDYXLGTNnSSz0Aa1XRAHps4A7GBp8KEbfbCRUQUMqQP5pY8tOyWBaDfRrGJSr9y0CZ6brcP/8LFb4Ne+8Hk4G8/FAwJOUsOQeSKFg13ERjO6dLBOJFzQnc1LbLpn1sDDZQ5YMl1JixtIu3y+7WPgmlMdeCipARaqPxeUAJUsuO20kEpt+y9jG//AzTfCkX4WBdommCYMrK5kTGAyNzplP3tBKQV6c8QR3cCo9XIggneBYagP1BdPyug7u8LVtkeBE2WTFYtbhhFHjF6P5sc/v+sO+I8P3g8/+7avha+77AroqGdWVUOg1nWDOZpDh86ty6HB5cAMUD69yq3gRs7NkSnfaxHCBBpCUf1dIm2rks20dN2P01FeUIK6vFlHz6e6zpQrb0HAxq/xXiggJwR8dN9j8HOf+VR+BWKyGoG8aSUem/J4aiKejfoWpOSM5aW4YsLWOQ5U9ytGHJCVN8h89R0aFZFzLDM5qKa+q1slqNnxOmLNg5KQPB6g7K0C7Mejn/oHPvpheMeey+F7rn813HDRHtgeGSBVRD26tcQNANJqhdzhnBRj0KBqZE5jnsd2nq3zVhos3JlLqUeKxDeeW3qTG2jYA1TvvHmMykd3Wq0Ng9WGuh8PqkTnZ9bX4RNPPA6/f/+X4PY4A7geTc4E4mxukmROE27JA8ZChds56GxVG/G7JxnHlD40qleJK2G6kEdoMxGzQ14thboXAYRqKrD663jbsSlotdrHnjo7uwY3P/0k3BR79cvPuwDefeXV8O6rXgYv27ELNiW1BNbkgAXnOSgpHJRak0EQn2dSOjvBYEAwYMNyGkLS15dsFvVAk3fAdiO00vYqQlqcwMvCINU12WhZCyW7OQBPJmVtZmy6eqp/TTXo5MTZs7Dv2BH4yGOPwI3xeOLkiTj7F8dOEbwrEcRddgqsFqkcvRri0UD13jNrfmTgwiivREjC/GA3DZITBPvmfbkZ2Mxwb3MHrqn+4lg5+vOCgdk/XRo6/eu7AvY+MmEWzx+Obr2H4szib3/xbrjhwovh+197A3zd5VfDhgMDtkPTgXiWMDhJXc0SVVVss83HLsIqAixuAZ1WnczLW+LJYrB9oHzRXn4Lv+sH4gG8vc0dQX+VrUNo0Hd3lML/4vbb4AsHnoX1DsskSQTylFy1xWU7zWDOQJ6wZGZzIYCxjzletw2otmkxZKSNllpOV2cU5BoHta9fW2C1a/QX0HmwqOhR7qjLz9sE33jJ5fDeK6+BV+68EFYi+oMzM4x6GqW1SmLjV9amBzOqQ/uc/CyHQhyLDHMeWFLM40bSpj9iR6ajr5n02ZAmEzTxJdS6Iw68HABK0IfBcCCH1128B371ve+D+w8diJ6MffDnUcMenK1VIOf3NJyfGSwPeE2QodStLbwRjcjB7LEy/AwBbLycC3KJokBblWC9nVxCZdM/Mt0C8FfX2CO9btrD11xyKXzbZVfCe/ZcASsR7bNQN5rx1VwUcppOgVkDubMvJaEGt3CW69nBUDb5EUZonNM1wsj91j0Yzwtxflpt6HLaPCDsgPe8yRvk9sSLvD8gVp88DYbFdlb28wDkQVEY/yST8IaLL4W3xPb7wJveDB9/5in4w8cfgTuPxrmGSXm/pJPBH4A2NcoMZeE5GlSXOkg6biO91MPgdQAbP1w5qRVK9zbnvKwWybXKb/TdOkjanjiVlOE1286Dn3j5q+DtaR/DvgBY9jNUDB0DdvAHdyQjkbvqjyXah+48MqMKp3NupYrooIgiO4LUDdTdSldJg4oDnq817xeWlmhGereG+V2NDRnz8DYPdrJo6OUII7+ozBJjosRjJZqT74neqvdefgV8/MAz8MsP3RfnHU4W5QCVd0QARTZ+0X16pXgglPjnJEm5njZvclwYkYvcTSEM5IecZYEXKpMTE/JK6D384wjkb4/ejQumq4PdZf1Os5l/oTYoV00kCJEpzB645kDZyQTgfG1n30QikEEq/VMGEIqXUtdQCcAKtIIdFzfCRsKZZtsG0iJotMueNyqS6ShNljpzqLzocCAg+BwaUhpIe7KXk/dM4SPt9Z02rH/Lrt3wh08+Dr+59xE4lRJNwCjCIZi5HIc3w3AcxjfCYLHGEQib3o6NpQ3Mjp6uQxWA9rAj2lX/5JWvgW+95LKs/WYklc0Os6HSMSotGnGmsomU5kQJVIYydjWDU2C7us6lU77BcUP9emnirwchuLS+Zv63kRYdkynfMGhN3TtJCqIaFFKy4A+wgqRXxfAneEyxFNMVUG+N5sj7r7oO9mzaAv9blNbHs9dlonSLpxABYBykLBs8R1ph2krQAngrs0DgZmmuP60qpwhld6weLp6swK+//k3w6u3nZxNDwByUuaHALYAOlo4x2iSQe66+OwwCYuOX5tyQGQq2dTqcwxVY4t5G0uPwXFwX6l4mrZEWgpIlLKor+upileX5Ym3UOrbmZ3QI6sSbHTOlHWbBPvM3on39qvPPgx+9+/PwRHTzsWjX4GTpjKrTDYVUW6gN6IM6tWAOL4sQYKBua9paQ/SFJWamrSo2bYbfueGtAzDro2+B2REcWoeW6MGWbSkFhxtqhczNAGbRlnlYNJxZNpxD2mX6COLwRnNixj9cz/0rBgOtDwp8dF/zno8kmVvteu2W7fCrr78BLkoLmye1TFPLlhrukFWGLzo8jXw05z4HvJxjsyDX0quSUNb73Rzjf/N1b4IrN2+pYO7L0fcwvmWyVn3QALWTBmJzEyDlKwZsdEiSyhKvegO6f8OY8TsvVdp5sRr/ui9WBw4qa0vlxgNk02YDPMt173ivN1RddyBed8e1W7fBb0dPyBagtaB94wEqqylsrP+DqjDwywz+0IlEPyB4VW2lYFCMKVtUhNkMfj7azFdu3poBvM5gdpI5gxvqN7cayPPUod9mOf121FA4QLEmHWGABu6aGMwnYKDOFx0vVdrR9GDrxSc8bezrzQffTrzywqS5lTUdJr6haVP7roXazuuUJv1etmkr/PT1r8wCToN6gF0vPNER3sKnGmS2306ZI5HtbIdlWrlVtkhOYP5AHBi8e/fFUjEBtTv0xucMYgE4wGAHWi+5tdS4dss2KHYYGrFleRHUOJElFplMga6VoMCRAxZc4waePae8pV+GKoFd29kxMXVaSp037HG8Np2l0YFyeyAd6lltcmTJDOVYU3HfEv3W358+x5uVcVXGClHklbwZ3Noq1Yo1wuLXrRoZFdwSBUEbBMVESlskvyqqme+Mg4Je+ZhbPV8kQG+vPWKD+pUSdT5E0jt27C43mvyocAiidSiepjnrErX+2QYrFlzDBp49p7xFyhH9pUe6p+jJUCU9R31TFDYiSPQBVUiYNoDKd/DtF6yEZxD3wQqx74mAvnrTpgzoIJMMWDMUTJ1baAPaZ4g1PkiN1G8oPSrQILCLhP5InMK+cLqpAlnZzTPFjL53IFUMazKTy1MdQXeOH7z0Srgu2ut17epGPQjwQYMXB4leYNhoo5xLIypa1Xsdhluo40udE2+u2bwZvvviy9rjGA9saJsecg8aZkivzA5lelwQvV3/8NqXw2w2K4PEXm0wDgCGD9KrYNgsI6BfOChEWCClGOBU2z5K59dt2w7v2nWRVJQrpE0LPb3N6o7pbOBZ953BoRti12QVfvaKl0cpsBlkyznJQzMrEB898AMMnbLncsBLnD6AbnypR4BBXYJOE5l01epm+PHLrxWBMwsLvEtt7EBotQmDnto15w9qvBSPr9mxC752x84ipUN1OdbC69ziMkFjdKojszkRQrNSOgbliTrNyv7mZDt/Z5w4SSKhNdhoTW97Bo2FIKWWIPtGh+oDTRL7TVvPh//76lfBfzj8LNx04hjsWz9b3u7Ls2MBZEbFuQXqYBEWE8IsWCaElzAtAAE5WAQy4Gn/m0k8rooA/przt8P7d10KO+Lkx3oYd5kOMDZGQgDxG3DQryuke6mMVKX8Bkc8X8UJfOtFe+AThw/n5eOwo0y4QxIOB+MBqPc8G6QZr/zc54Khbiwl9yRmlJIU6R2NZOj3a+tw9XQFfv+Nb4Wt3VTUTFY7oLwZWiipopbqlGgHRfqrCfP5fGfvySCqYRsvwo+wgXnOeVTz1CUcVsV3xrFyWhdhIWGNfILVYPyrJSW3j0jSoDxNUCXuouB5qj+p4+8Lk+Rc6cpMXvo906/D++74FDwXZuo7w5RJZ8c22mMl5gcOC6fQ3tZtNDiZGhTz8vbIM3jHzj2wXfX+BGRjZsBiMGsKsEWCAk2vHkg/HVeqr9O1MgseKrCNlFV5oqNBbrtxCzSJs7QMgmOvATnXqdETmnkpAseEQQvQRlsqU3AWbHuMgVnzReKUlEZVJn9bkLUoS+oE8FCmx7/9kj3wm0/ui2OuXjZ6KjPPAIOGyVEIi4Te+PvQwVLcYnQVA8U266O58b7o2WBm8K+RyP1iMAdXDEtkRY6pL4M6v/mbpA5JZ1ZzvDa2dHpfgKOhiXdsly8NqYGH86VqcHUz5PT1HsC8hGCcA2G8OBEi+lcG51B/Nfh9xwOY3y6jpgfWNpAxFYH6XdHL8hv79kKYTgkYtOmm+WKBrkE34niY/4I/jkVaSBbDvoft0R56RRwQ9r2VBMbPOXi6hnmN0orLL3sqUAeSCtnzgUpCsHRmvsASQQM2OECrziQrbbFBD3Pq1ei4SBfVC1HycvJETK1BXvPAHCyvjaTW5wADIeTzHGsDqQO0EwTVBjKvEEr7vHr7edGWn8Dx7MIjW7qR2+CrtDmFjgO6qU6D+Q2kQ9ldl97ZSB/RejDLyDfUAYNm9Fw1PacOjCEtLVhjZQYqUwOUyTFWPak6g1gBTfZHYWIoE2PChXHpls/RpjP14/yDep46CpepAb3MABpcegYT09gSMqZdXB4Lg2okLXD0hlB6MmYSmfem83bAx44fIQnd1Rfecl4NaQIwt/GW+wSLM/FiRzhTAH11nOI2zApgZv9aDGMA9rA4GFCH2nNR1T+Fju7rdanB9fJWXKtAb37kaIMspWoV6JlWkbzBdQamP9g00ik4bbD1NnnoOLD5mijX0Xr1nO+AXGed91weUcCRa22embKo8Ku3xDmDo4cgKCeDBTAuTwRoQOveYIxUzlSLEBCq2NzI/s0tWw2TmPktuwwABlJkmdACtcRRRjMGOsWZX9daZsDM0b5RqQDhSHDEBKspWCoNaO+H4OOj19KbeaeaQOc94JeOYI0UhvwN7tx3njAn26WDaiCNIoMLrFJ618pqeVUiqK2RWw1l7A4vnapEGF1ON5DI45f5pXrefqSMEqgvXl09J6ZslHEe1PnHixWwDNUiTpsdxmsBMBRPrV/uREoG1AxV52U54B7XhLEnRkwxnT6UTmBkSytoHjQawJM/qFIYz/6cQO2e58O/sZeO5BHLApEJocDv2QudWN8S1PSa5or3pjhCxXyzxc7uBPJyrKrF/7Q0mFvbcwweh9yJmdZBIwZlZzfuWZ0+LKw18NZb1Q1wpKTUoDyv6MCaXKIRejVJ0UKj7jDObhupxvBeWKqvzA1Olw9IDa5T9aqtpjxRQgdrU+ZvS4OKFmpgdLENHdwTvSabDupd2HhUKhLmM/lcwqCXslSkc98pQ+MZnJPvWJwHRl+LFm1g0rPkZomu81BSHdTzHNcaW7SUSIvoMHLOEWO832ibeDDjgnTmmhHu7o7lsSi0AY3zSQmtk/j/bD9rpB420jyh84IDc3TOWKIFiEWNEFS+Bgyq4wiY6ab3agwGfT5/cB1jhLCxDjdicQyfUXTASF6Lgi5Paz7vixYJje2815K5YXo4M9S3nrseabDFEpoNdG1jtDgXw4H03Rice+861zAA7ghKrb1VG0LuKZu49y0W6jNmyarQaDDNrgatetCk+ajBF8bqBjC0+VWn4nGBLr8fo2MD8YvShpEbWpjla1eZo2trdqKLnsqbHcHGQ3sZA+/t0Ht1NVqLXxx//OTz0AxBnhyZcXzhodnwPl4B0WNiEHDeTRATysgSVRizbzApADAwL4LuFOpmcOmXeXndegpgYOJwXPNZeHFDZrcXKmhZe/DMaStZ+I5vUNSN5+6rVza6QYlS1EhmY8THNPcdP9rOQUmkpY6wgbTqWDRRwA0pC3QjyAtLT508XgYbxPBOV1uZMNLowXaUfM+lL8sKQ/2MyjEGNV0ufw8uDVIGCh97jx2SF7DkRSx+bn6zgarOSxsUb5nuFPaePAGAOK6FdMVb9+W6ZLrxL1YG+aLs9bH35EkzA6zbFlzcgkzPOXhADDp+UGCAAoDT62vwU7feCCfXzgy3yZhTzkCdAhg/awZyB+Ir77GCmz9h8p2Ega3rwLQbIEPpdGcj7b92+62wlhaQx9oRDajn0B/ghYPZ8ELFGbrdM3x95+GDwMtL4AtoeH6y8xH+nK+1NMJB4gLq07MZ3HX4kH3DDU2yHIQBYdigoxKW1TLMl8IAI+q1IcH4uP/wAbj38LPw2LGjAzBji3bXQoYOBOvShBYT7XOeZgQHCFQNRuf8WuYjRw7C3QefhYcjMMxWH1jrr/mnJ7n80W/wCHMOUOVKBR1f7z16GI6tr6sNmywP2sbDfNB3vicbZvq8JK1ycgt6u7wA40effdqCYQTUfC70BYB5HVR7DFoEekmsJzs8OBnY6Z3pvBfIU/vyB50373vEbJFhwI2OfvrtB4UrglogpjgvffVvUHXQr7wybXonsdueeAzOhBnc/PhDeaOeCdo3DXGMPGyTvGzABfn5cvnddW0q/dmTT+S94dHZIsVERpMPjuXr7rU/wZL80c6CNbzcslsTrff8n5/cF3vd2YpzsKAGaDBzpCcNJK0CA0uZQXq0z0rHAQUKtRfPegTDBx9/OK9r/JEnH8/7gzDQtQoXm9rTzWVjI16VG3D00VJ1tI0tDYm1ofSmPGlG7EQ0kW6NnTEtKP6XTz2e66K3zht83ADDjq95tdEwT8Nwh2Sa0V2fipL5o88+WRbEz4viE44oB6HTjyLVKTZoqoPCUVGO4FBd+w6DGQuY01cHaW+NTx08INKtpeI1R7TP1khhPtVpggWtJtnYs3T4vqhpYgmdAHHo7Jm8nvEzZ07BbU/vL4DohuobdB1QsUafa3taHbpqZnbP5cv30cWL1ugK3QnQ9xx6FvadeD7TfuDMGfjoE3ulM2pQG23uCYPaDmGePeeO0MjDXxvtAlbz3fLMk/BYHBAWCd3ROtKVIShMrlxo2tjGBOBBoQY16tZxD+pfUzhmwhKg03Zuv/3og1Fa9Haf584x2BXjpzmFIegOxSgNfKQ8AG0dfZnc0FNq+D945AHaT3ElRk7gDx59ANIaHQO6u6G0KwXU8oNli6mLodPfV52iU3XWHUoDuWweG+BPEu0rtNNYPP7r44/k+1NVP94vUH8W5VsQG829TPDmpD40r/QncumYRWz80eN7C16mE6h7lcMAoCBqDsCqe0c0nXeLKWZydbzKHMBK6UjgZw8fhk8ceNbaoyo76bnpYTWAMJILQQZY5gA7AOMgj9JJLrdTQAb1fRv9fjRK589GKVf2AynA+Pyh5+DmaHrkNJ0FtedfRx0MGuuj67FBa5UjbwJ4a85rEk37Sjw+9fST8JkDz5TOmGmfwO3x+rZYp6kCvv7WUuMBHQIzL5VdE9y9sCCNViWylU2ngKzOb33mqYiRg2WV/7RVCdvRhhEOc9Bo7EYYWTlp/AEDcAXsBOZJ2rh+WnYJ/cUv3Q1HkirvhpIGPXMBmpLLd0gtfX16VCdMYl6DEWGw/Vhi7snZGvzS3Z+j7cZou960oGC8+fN33Zk/4vS2aBMcmpOuIoM06K7pOW0nC5hBgRpq2Qmsa5G2n7/r9kxrJ7SXHVp/8Qt3wrGzpwX8GtiirbpGh/L8bPEch+0DFgbVvFC8zr9Q6DgUafs/vvSFrA0TXspq/938Rm0V7KJ0M7haUHBq0qJQIqXGbAfljesjqO8/cQx+66H7TQ9t2XVjzNJBC785nXNIIsLAK8DH7z98P+w9cTyrvdQJ80HnT0Vb+l/fd4+R5gLmDoZmEMAArEYC6mvFtk5dexOpc+VqcP72/V+CJ6LPP29sSkJkQttR74t26Z/sfUjS+kN3Ri/0/CBca00+b74Oy3UAMB4Wz7e0PevvP/IQ7Dt1qmw0lPZi6SZ1E07B05BAnNfoKtTldEe7HxLDVeaoDHSyfdjLUTeuX4V/F23pv4heD89QM2iBBjhgSAo6svw9n0fnmUkdKn1C/2f7HoV/dd+9tO902egmdcQJb0UWj9+4/4vRJNkvdqsxQbBhRvE5qVyhFRtp6DrofEKVnppfbGLw70eeeBx+6767YbJphWznKe3YOy3aJpog/9e9d8EHH3ukLBvAtndXXXrieXD0MG+D8x0HjXZ0fAcwGiXzvquSeaqOD0Us/OsoSDK/eb/vSfFwaKnG66Ogxp2AvB2Ylo6XVA30LqrYwwDGrgl8nW3CCnIGNw8MJxMyPSLBSSX+7BfugPuPHxEpzcAYmCKKud0yAFdpWGoaNY1qMIWlQdPx8LEj8M8+91k4neIJEJM8mJ3IICXFpy+R/6fPfBIeOHJ4KOXAaprW3uVeeosUVucizdSzvizmVwLzQ0ePwM/dcXve4zGbSStTorsjTVNAjvH3FyLfvxTt1Ck9K/ynQ0tQGTAC2MEjtoFrTCN18GCUtcNKVzvjo8ePwk9/7jMZE4nG6YRox44GhYwnICHJjKo49HjTeGWCO/CR0kVrJtJrOK3qRbr1qvuu7vF9pO/h73/qY/DUqeeNlOPKD4DtQO1tuGYcOHBpqaSkUwLzf3/bR+F4nA6ZrGySBU462ksvg2JSpF3aATVtpfBDH/8oPBif0w017WwjzgOzsSvBSmNtVmg7mQ8GQzqePPk8/Eik/XC0n7u8sWWL9kmW0NN4HItt+IGYfv/zxwywWl4Q7QnhJs3XwQK8C/Y+P5eWJBC6QbUvnT8daX//rTfDmSTwWCtOaTBoGlrkp+BPRFhLOjfi8Jq777ZmqTeSsMTJJzLKuDIfNvI6ZbQc2PraOqyfPQuzeKydOg07I/H/z9e/G1523gV1ERq1ao9fxXKMFEt9Za6W7hpszOj90V7+7ls+BIfixEnatndKG0VOaC89pDLSAoJ9JGx97Wykfy3vTb5ndTP8+298D1y6bbssnCOL6GClmd/h0DSHEdqZnZn+INURAE2hStEnjh+Dv3fLTXAg0lRoX420k4RTtCfez/pZoZtov2LTFvj1r3sXXHXe+WZpW1lkJkBzNasgRDqWV9w1B9zaPEudKAmDf/DJKNDiZFvexD7SzzvNdnkTe16irQ5OMsidLc2Se8BMB+rJjh/+4f8F5gXUDzHruDx1DaxeiSiAahvFcDLODP3Row/BVdu2wSsuuADqrBAMTQgYSl4ttb1fU2zkzrrlsrqNx3+JNvMPfvwWeD7Fpf2naQ/qTjZT76qGEW3TSWHHYqf8k0cehiu2b4NX7txR6Waed65DUaWEXufZYfWuTZiJphlrPT6yfx/8yMf/Eg5HbZGBvKlIuMmAdiKEAA4EiuRp+qM4lnlZBPT1519glKqx7xVfEYbnk86acVrbshZc0b8x/qZo7//EZ2+DgyxEEqBXqqmU7WfXuIXvAjBiXrUUKtBUI8wF9NiDgzgEh2eTRNs6DP61KEFujJWcxd/E3G3J3tNMhSG4NXM7BQ593emBlDIzjsXG/K0Hvgi/GAdJZ7ATIBdATCoglC9LQN0RE2mvw1NR69y0b1/+oPOa886D80Zo9+aQNkUMQBqAnlJ8+j0ZJdov3fU5+OV774aTKT7SvbKpRXsnTKu0E7CJiLUofv/8sUdz21x7/vmwPdEOli5PoxEg6toM7qE9eH0+8v1f3veFyPfPw6mYMG9kT6ZQcZFW2mUDUGIceheYs6PngTlHDUyOFEbeAA+ik/oq+vvyxXf169BC1oEWcEzmx/paND3Ws/nBZsjVm7fAT7z+q+Cdey6PDOkG664xGU1KcAh+bYOeiRLhtmefjgOjO2FvtN+K5yKZGKt5AiK7ubqJME73fl7ZMn9aH9X3bD3RT+bTWqrHGlweaf+ZN78Fvv7Sy/KAzK8IZNQ22DpgY9aQ9yzqch49fPqZZ+CffvqTcSr+tKO9uOk6nioeoT0RMiPaZ5n2tczzRPsroqT+4de8Hr7h0itz6WZrEGi76wy9CmsT/qXzNAP4mQNPwy/f8zl44Pnj0RNDAmS1emTy/t9KIxpTg8EdQIHcSWeDg3mA1jf79rIvZhlT/rDR2NIAvKQBr4Bd1rxbz4ydra1npiZw9BEcIca9bfdF8J3XvBzefdmVsGU6ta84wpCxqOpiJEk8PxE7zs3RNfSf47Tqrc8+lScdpnkWjcAgdudEADEaAtAq831enDuDOY0Loh3bn020z+CrL74Y3nfttfBNV12Vpd5gSVq0tOuLTL+yoY9Ge/fWOPv3+w8+CHcefC6q47Qh/JRUdOmIxW/bKdpHVKTQXkGd6M/AjnXoYn1eu2MnfMe1L4f3XH41bIt80qtc8a8Onu9a2xyPPLk9Avl3H7ov0n6gDFizRF6VafmJTHNP8kNDMAOYUT8BGnXB8r1hI9B9vPaeeyrt/EAIlVXaCB8MDivajJSmDhFohfZAA60C7JlIugRqZvY1ccD1jXuugG+/5jp4ZWR2KrQlJTSDS90C3HP4UDZl/mTvI/DM6VNlKpt8s8zQjtR0deRzvii4EJ4BrUUSaBFKBsdaAkcBxSw2YqpLH+m/aus2eOell8L7XnYdvCl2UNmPRPjW6JBQAH3Xc8/Bjfsehz999FF4+vQpmiyZin9cBq5Tol1UNEiDq2ar3CJQ8+ZNBdhr0jHT0sepPa7del7eb/19174MXnXBTuClxlvaUWMuCbG7Dz0Ht0Zf/QejAHni9IncCQvPiwDp2MRIbsWueGOA5ityfmn/9XTSVds5l58L6gSnAuKgpAEUya35mqHKgJYIboMgzW1upLWg7ar9UJpfJHZGcr6OrAQkSd0rEySBOAFhRkdibmJ4ktipEc6PDfrmCy+Ga7afBxdG9X5+sh+JgLWYz/FoXx6MnpO9cTbyzgiIw2tnyjsBNEvJEw1ZKrB7iyRbp2xOgkRFXf6rUVjq03OnTEeiN0vsdalHn4AdwZHqd0Es780XXQTXRFt195bNcEGincpKtuzRqJ0OnY60R8/F5yPtB8+cNTOs2Q+eNEukP7vjplUqi5mhGzV3HKwLs7DJpMxD9twk/s4GtJf6JNp3Rtpft+vC7InavXlzHCes5vXnUogp8uD4udjpHovmxF1RixyJnRrFB86TJVM5Ty5QZD851lFlBm1nB4DJdg7GxKjnDDcWQlxngKGSzYCGVhizo/meA3WGtTJDyAdW05NbLzO2nxWJvb4uUruAYpalSU8bsvRkk4vIMHqvU7OTXQX0ZCqDJlZx7O+UKVbdc1HLzGDrzp0V2Kb2wE6dcVb2CyHaWRsF3gXJ85JUbWrUTDcN7jKQJ9OqSQztRL+g2dPebjutZRI9zPvAZghpzcT7zHfZnaov30XrsZIMygotQhdpDn6Hp+NOyG0y6Spw2dRA6/bRAG4OBFth5N507gMNR7CVZ6yuS/dJdMoH4lyBQFvzpsqnDYUmHc009qUh+8QIZuiMVCRtbxF6JWmG6gZI4qK8utoViUHqLcejArLoTPVrEUKVq4BG6qBZgmA5WFp2swn00zhJQ2BIC75nLUQ7pga/vpfy+Ajtk05evUUBwRzaofFrQgC2eVghs/RLwOr7JB2TCRP5nrXKtPB9VjsrjPGdaJeX8h3txa9M8ZjukX0iLjkE4xoCBWapTwPMWgCN1ruEja0+ajLkxkKoi9xpUEvXjrf7AuJU2QQOJID0XWZiVqWRKazaZTMZ9qAAGCM0k9LV/bxRqWQUkNMLUwbAlXFo6qUrF4oECUGtA106dx7ERTDk1wQS7dRJQ+pM3AFZktPoVvY/UdKg0K20hjmQ7HwE80qlp320UQvRTdonpNozj0t5YdIX2jXfaYJM+J6Obg7tJIUHmlAdAzCjm53WUrpVJTkfB3MK87ek8NcmKS/oSAAQBhCoZRVwECAH0AwuwM62VPo0ui9xxUwJ4vrLwHKjKv0yS/W9FjUIZI8NmCXPcSbYZpjaQAXVaMvQnssk2vtUZho4VrNKz6AuTTv7wVu0E78r7Ypo075YtaVI6hbtSUqHzHfueL3srxdqHTiPIu6HtJP/3ggWJzw8sOvzmnjbHrgAtPPCdID4RZlpTwjSICr34I7AX6RRYQOafJH91KoiWVqTfZx/J50CBVTGUnrJ34AUrY2pQbsIzD54aZCL6/NC7kHVveTYZ6lXBiwh84D3Aay0g6IfLO2IDiScxA1ccQHtWvAgOl5pkms65HwTnV2QjhkE1OD4DoYW4bumXUtZHSevH+pnoKaFeo4D3jfqOicsb3IMCiJQA3diRQ1J7jwY6INdEQgnWU2D8BZFMiCbLZSH2WAueJsDrOo1IKZ8jIRGWwd5RpUpZCqpyvqWO1w2RZj4yQjtQeUFA1ygq8eARlyedqx2jOOXTT+gXQ1YBdx0rbvfwFyaR7t0QAAZ+Ml9UJ1X5aE6wQsFcwpTjbVmUBWVtHwyCupQJFpKlE0KxewQSJqTVOPGR8pUhFooDGBJgR1UicP54RDQAIBO5QV9XzO2PmJPVQ+sp1ReNjPSNfnaNY8g1A1FSL1L5waiGX2h2KAdXN0U0M11bYpyqfilaWfNwlqS8hCNw3wXcwWE/wGHgsTSrujmarBEVmlqvQCqr/nFBXMKZuNNqxhrvj5/c88wiWznTHxhEtLgShqXMFyaVzFZSYKgGbsMHU6CMYil8QXElZm2fjpXMqW4oQgkgW1+BmgyL6h+tSOivDq3iOZKru2QfM31CqoDapkRTI4cF1Q+NTGbbTJ2z0IGlKSu6ZaiGSzfmc+8KLmhnUAr5ikDGXGw4ZW0G8LAyGydt/hsTI5Bp9C/oma5cCApCwLKoOINgVoqAJJkhjpBg1WKo86EH2MbW2qAhglYiTRSgJlHlqq6Jyn0IxIbGBcQNANMvVnDBKKd0RKU1gJdd8VHLY1atNdzpElBHKWdfwLUzgdEOypeMFSlGZE1iGpXqhwaLWlpr+RZMGvaUfO9EV/4AnYFWBU/aBPEAZDBXfPvtJVoNKAd+fsGQGJCYG5nSwHNLKKuYHBbSxUQ8iruOOyGo3S5E7TMMw/XnmB/VTkCwlDjURAkibI2MqzO/3WdYJB3m3aFTAI5eoDDCO0WiyBodPtTiMQOoaLJPSwQDUMyxWxxJGnazMcgDhtSjsqjVNcxhdvNlbcURmN66+XwROtrf48yKPdUkRrY8uYUWN3AmBB7SW9xQYl0e4wCQV0oqSESQz/fArDPSC/sAa7uwRPD0ockMxfm9iscFINQeRkqregb3nQAtHVo0WzOcQjaUhFgyVnpINoNwGEIalO+ohNgfudjfqqOizAHS63rFib9L92bbjhTbLSWAU8thIWCrHOlgco2HD2jwQ1BD+Ra4qIWjIY2dUuBxdI9TKvlgDEQdJ1QgxqgaigCJPuv2YaeR7uyK5envUkwKAMGzFggKBAx7SLRg8qXaCeAByZg0Mw4LLFFO0e0OiBWSBth2IBUE2emTBymyxL6XAMDV65BEVh7jICaEykholV6uV0NKA2yprRoE1V/Rhg693F/Txfd6pRMuxoUV6nlM2gV0Cj9y017TqsEi87pXPhO+bQ6oBE+nP9GwLxEOHdAc8HB1boBbNR+WZYaGvgi/eYxcsT+QEePv4HtpMsyzXhwwNPuAMIheDJeGO3nQrce0M2lXZMHG6AdWvSPgNikASvUBnmeO5hTeGGA1gRsANg5WtMtEgSy0h/uOei7MsK4SoTlgTAmIXS80zZMrpSQcNGhnVkz9L8ItGs6WjT6eJ++QTt7c2paR7sZM+j7uDHacUFHWJTWPRZgfpiWdzKU/5Ey1e9D13rj0FdJUjo4aT2UDjZvW+nyE9QFC4eQB5RolEGllU3DlqhRNOtn1L3RJW7RyyVUQABomloZpx1REXj8pX0HjmbK19RaiAaemBnQ7Mod3ENFM+eNdWyQ2cltizUH7o+opLmlGW2nMGmpDYxbF4c0W9IVzTgfdy6PeWmnzDh9Ax0T6qyXTQtgO4GvVKD0qK8BqQJg03K5YGuueA4amrVMUPR48FJa3Umw0iVxaqTcphkkt1J2nbVUpKoGwDbNFG/GMTDkfYnoVL1KJ9kQzahyD5UHmndgylQ059lcrM/pduBidVr0g/OC9ADu+RbNiJYOVQ+NBXR8ZozKfcp78HJSMxNNqAuDwrWKtuLINYh6CtXzXnqbwlpVtfc4b1XVQXLfKXW95tLMZ452uRPCKF0wXqsB7fYe/yyg2WQ3ntaoJcUaQ3urvceq0alpbj3YxAU0y8ts87NvhWYayvuF29Cjpere2mroxjPB3RiIrbFnwOqnpbiyGGBNurmMFg2A42lg7Bl4cWmXPM+R9nk81+rPP78M7Yjzr1+E8P8B0szv+tLrxRwAAAAASUVORK5CYII=")'}}),Trust=({theme:et="light",...o})=>jsxRuntimeExports.jsxs("svg",{...o,width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("rect",{width:"44",height:"44",fill:et==="light"?"var(--ck-brand-trust-02)":"var(--ck-brand-trust-02b)"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M33.0246 11.8662C33.4096 11.8662 33.774 12.0243 34.0421 12.2925C34.3102 12.5675 34.4615 12.9387 34.4546 13.3168C34.3859 17.4143 34.2277 20.5493 33.9321 23.0312C33.6433 25.5131 33.2102 27.3556 32.5571 28.8475C32.1171 29.8443 31.574 30.6693 30.9346 31.3706C30.0752 32.2987 29.0921 32.9725 28.0196 33.6119C27.561 33.8861 27.0843 34.1568 26.5842 34.4408C25.5172 35.0468 24.3441 35.713 23.0146 36.6025C22.5333 36.9256 21.9077 36.9256 21.4265 36.6025C20.0766 35.7026 18.8879 35.0281 17.8112 34.4173C17.5718 34.2815 17.3379 34.1488 17.109 34.0175C15.8509 33.2887 14.7165 32.5943 13.7265 31.5906C13.0665 30.9306 12.4959 30.1262 12.0421 29.1706C11.4234 27.8918 11.004 26.345 10.6946 24.3443C10.2821 21.67 10.0759 18.1706 10.0002 13.3168C9.99336 12.9387 10.1377 12.5675 10.4059 12.2925C10.674 12.0243 11.0452 11.8662 11.4302 11.8662H12.0215C13.8433 11.8731 17.8652 11.6943 21.344 8.98559C21.8596 8.58683 22.5815 8.58683 23.0971 8.98559C26.5759 11.6943 30.5977 11.8731 32.4265 11.8662H33.0246ZM29.8277 27.9331C30.2746 27.0118 30.6459 25.74 30.9277 23.9112C31.2646 21.725 31.4709 18.755 31.5671 14.7125C29.4221 14.6506 25.7371 14.2381 22.224 11.8731C18.7109 14.2312 15.0259 14.6437 12.8877 14.7125C12.9633 18.0537 13.1146 20.6525 13.3552 22.6943C13.6302 25.0181 14.0221 26.5925 14.5102 27.6993C14.8333 28.435 15.1909 28.9643 15.6171 29.4318C16.1877 30.0575 16.9096 30.5731 17.8927 31.1643C18.3005 31.409 18.7502 31.6635 19.2396 31.9406C20.1116 32.4341 21.1099 32.9991 22.224 33.7081C23.3175 33.0107 24.3014 32.4515 25.1633 31.9616C25.4231 31.8139 25.6717 31.6725 25.909 31.5356C27.119 30.8412 28.0127 30.2637 28.6796 29.59C29.1265 29.1293 29.4909 28.6275 29.8277 27.9331Z",fill:et==="light"?"var(--ck-brand-trust-01)":"var(--ck-brand-trust-01b)"})]}),Argent=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"32",height:"32",viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("rect",{width:"32",height:"32",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M18.3242 7.63647H13.6516C13.4955 7.63647 13.3704 7.76611 13.367 7.92726C13.2726 12.4568 10.9768 16.7559 7.02532 19.8009C6.89986 19.8976 6.87128 20.0792 6.963 20.21L9.69685 24.112C9.78986 24.2448 9.97107 24.2747 10.0986 24.1772C12.5694 22.2856 14.5567 20.0038 15.9879 17.4746C17.4191 20.0038 19.4065 22.2856 21.8773 24.1772C22.0047 24.2747 22.186 24.2448 22.2791 24.112L25.013 20.21C25.1045 20.0792 25.0759 19.8976 24.9506 19.8009C20.999 16.7559 18.7033 12.4568 18.609 7.92726C18.6056 7.76611 18.4803 7.63647 18.3242 7.63647Z",fill:"var(--ck-brand-argent)"})]}),ImToken=({...et})=>jsxRuntimeExports.jsx("svg",{...et,width:"32",height:"32",viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:`linear-gradient( + 180deg, + var(--ck-brand-imtoken-01) 0%, + var(--ck-brand-imtoken-02) 100% + )`},children:jsxRuntimeExports.jsx("path",{d:"M26.8543 9.96509C27.5498 19.3857 21.4942 23.8384 16.0655 24.3132C11.0184 24.7546 6.26765 21.6534 5.85087 16.8885C5.50707 12.952 7.94004 11.2761 9.8516 11.109C11.8177 10.9367 13.4698 12.2925 13.6132 13.9342C13.7512 15.5125 12.7664 16.2308 12.0815 16.2906C11.5398 16.3381 10.8584 16.0093 10.7968 15.3032C10.7441 14.6965 10.9744 14.6138 10.9182 13.9693C10.8179 12.8219 9.81731 12.6882 9.26951 12.7357C8.60654 12.7937 7.40368 13.5675 7.5725 15.4949C7.7422 17.439 9.60628 18.9751 12.0498 18.7614C14.6868 18.531 16.5227 16.4779 16.6608 13.5983C16.6595 13.4458 16.6916 13.2948 16.7548 13.156L16.7557 13.1525C16.7841 13.0922 16.8174 13.0342 16.8551 12.9793C16.9113 12.8949 16.9835 12.8016 17.0767 12.6997C17.0775 12.697 17.0775 12.697 17.0793 12.697C17.147 12.6205 17.2288 12.5379 17.3211 12.4491C18.473 11.3623 22.6214 8.79916 26.5448 9.61074C26.6277 9.62851 26.7026 9.67262 26.7584 9.73649C26.8142 9.80035 26.8478 9.88054 26.8543 9.96509",fill:"white"})}),Frame=({...et})=>jsxRuntimeExports.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("rect",{width:"32",height:"32",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M24.9055 15.8824V8.30065C24.9055 7.63399 24.3583 7.08497 23.6938 7.08497H16.1238C16.0456 7.08497 15.9805 7.05882 15.9153 7.00654L15.0033 6.0915C14.9511 6.03922 14.873 6 14.7948 6H7.21173C6.54723 6 6 6.53595 6 7.21569V14.7974C6 14.8758 6.02606 14.9412 6.07818 15.0065L6.99023 15.9216C7.04235 15.9739 7.08143 16.0523 7.08143 16.1307V23.7124C7.08143 24.3791 7.62866 24.9281 8.29316 24.9281H15.8762C15.9544 24.9281 16.0195 24.9542 16.0847 25.0065L16.9967 25.9216C17.0489 25.9739 17.127 26 17.2052 26H24.7883C25.4528 26 26 25.4641 26 24.7843V17.2026C26 17.1242 25.9739 17.0588 25.9218 16.9935L25.0098 16.0784C24.9446 16.0261 24.9055 15.9608 24.9055 15.8824ZM19.759 19.9346H12.241C12.1498 19.9346 12.0717 19.8562 12.0717 19.7647V12.2353C12.0717 12.1438 12.1498 12.0654 12.241 12.0654H19.759C19.8502 12.0654 19.9283 12.1438 19.9283 12.2353V19.7647C19.9414 19.8562 19.8632 19.9346 19.759 19.9346Z",fill:"#00D2BE"})]}),Rainbow=({round:et=!1,...o})=>jsxRuntimeExports.jsx("svg",{...o,width:"120",height:"120",viewBox:"0 0 120 120",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{backgroundSize:"100% 100%",backgroundImage:`url("${et?"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgdmlld0JveD0iMCAwIDEyMCAxMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF84XzU1NCkiPgo8bWFzayBpZD0ibWFzazBfOF81NTQiIHN0eWxlPSJtYXNrLXR5cGU6YWxwaGEiIG1hc2tVbml0cz0idXNlclNwYWNlT25Vc2UiIHg9IjAiIHk9IjAiIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIj4KPGNpcmNsZSBjeD0iNjAiIGN5PSI2MCIgcj0iNjAiIGZpbGw9IiNEOUQ5RDkiLz4KPC9tYXNrPgo8ZyBtYXNrPSJ1cmwoI21hc2swXzhfNTU0KSI+CjxyZWN0IHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiBmaWxsPSJ1cmwoI3BhaW50MF9saW5lYXJfOF81NTQpIi8+CjwvZz4KPHBhdGggZD0iTTI2LjY2NjcgNDEuNjY2N0gzMS42NjY3QzU3LjQ0IDQxLjY2NjcgNzguMzMzMyA2Mi41NiA3OC4zMzMzIDg4LjMzMzNWOTMuMzMzM0g4OC4zMzMzQzkxLjA5NDggOTMuMzMzMyA5My4zMzMzIDkxLjA5NDcgOTMuMzMzMyA4OC4zMzMzQzkzLjMzMzMgNTQuMjc1OCA2NS43MjQyIDI2LjY2NjcgMzEuNjY2NyAyNi42NjY3QzI4LjkwNTIgMjYuNjY2NyAyNi42NjY3IDI4LjkwNTIgMjYuNjY2NyAzMS42NjY3VjQxLjY2NjdaIiBmaWxsPSJ1cmwoI3BhaW50MV9yYWRpYWxfOF81NTQpIi8+CjxwYXRoIGQ9Ik04MCA4OC4zMzMzSDkzLjMzMzNDOTMuMzMzMyA5MS4wOTQ4IDkxLjA5NDcgOTMuMzMzMyA4OC4zMzMzIDkzLjMzMzNIODBWODguMzMzM1oiIGZpbGw9InVybCgjcGFpbnQyX2xpbmVhcl84XzU1NCkiLz4KPHBhdGggZD0iTTMxLjY2NjcgMjYuNjY2N0wzMS42NjY3IDQwSDI2LjY2NjdMMjYuNjY2NyAzMS42NjY3QzI2LjY2NjcgMjguOTA1MiAyOC45MDUyIDI2LjY2NjcgMzEuNjY2NyAyNi42NjY3WiIgZmlsbD0idXJsKCNwYWludDNfbGluZWFyXzhfNTU0KSIvPgo8cGF0aCBkPSJNMjYuNjY2NiA0MEgzMS42NjY2QzU4LjM2MDQgNDAgODAgNjEuNjM5NiA4MCA4OC4zMzMzVjkzLjMzMzNINjVWODguMzMzM0M2NSA2OS45MjM4IDUwLjA3NjEgNTUgMzEuNjY2NiA1NUgyNi42NjY2VjQwWiIgZmlsbD0idXJsKCNwYWludDRfcmFkaWFsXzhfNTU0KSIvPgo8cGF0aCBkPSJNNjYuNjY2NiA4OC4zMzMzSDgwVjkzLjMzMzNINjYuNjY2NlY4OC4zMzMzWiIgZmlsbD0idXJsKCNwYWludDVfbGluZWFyXzhfNTU0KSIvPgo8cGF0aCBkPSJNMjYuNjY2NiA1My4zMzMzTDI2LjY2NjYgNDBMMzEuNjY2NiA0MEwzMS42NjY2IDUzLjMzMzNIMjYuNjY2NloiIGZpbGw9InVybCgjcGFpbnQ2X2xpbmVhcl84XzU1NCkiLz4KPHBhdGggZD0iTTI2LjY2NjYgNjEuNjY2N0MyNi42NjY2IDY0LjQyODEgMjguOTA1MiA2Ni42NjY3IDMxLjY2NjYgNjYuNjY2N0M0My42MzI4IDY2LjY2NjcgNTMuMzMzMyA3Ni4zNjcyIDUzLjMzMzMgODguMzMzM0M1My4zMzMzIDkxLjA5NDcgNTUuNTcxOSA5My4zMzMzIDU4LjMzMzMgOTMuMzMzM0g2Ni42NjY2Vjg4LjMzMzNDNjYuNjY2NiA2OS4wMDM0IDUwLjk5NjYgNTMuMzMzMyAzMS42NjY2IDUzLjMzMzNIMjYuNjY2NlY2MS42NjY3WiIgZmlsbD0idXJsKCNwYWludDdfcmFkaWFsXzhfNTU0KSIvPgo8cGF0aCBkPSJNNTMuMzMzMyA4OC4zMzMzSDY2LjY2NjZWOTMuMzMzM0g1OC4zMzMzQzU1LjU3MTkgOTMuMzMzMyA1My4zMzMzIDkxLjA5NDggNTMuMzMzMyA4OC4zMzMzWiIgZmlsbD0idXJsKCNwYWludDhfcmFkaWFsXzhfNTU0KSIvPgo8cGF0aCBkPSJNMzEuNjY2NiA2Ni42NjY3QzI4LjkwNTIgNjYuNjY2NyAyNi42NjY2IDY0LjQyODEgMjYuNjY2NiA2MS42NjY3TDI2LjY2NjYgNTMuMzMzM0wzMS42NjY2IDUzLjMzMzNMMzEuNjY2NiA2Ni42NjY3WiIgZmlsbD0idXJsKCNwYWludDlfcmFkaWFsXzhfNTU0KSIvPgo8L2c+CjxkZWZzPgo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfOF81NTQiIHgxPSI2MCIgeTE9IjAiIHgyPSI2MCIgeTI9IjEyMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgo8c3RvcCBzdG9wLWNvbG9yPSIjMTc0Mjk5Ii8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzAwMUU1OSIvPgo8L2xpbmVhckdyYWRpZW50Pgo8cmFkaWFsR3JhZGllbnQgaWQ9InBhaW50MV9yYWRpYWxfOF81NTQiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzEuNjY2NyA4OC4zMzMzKSByb3RhdGUoLTkwKSBzY2FsZSg2MS42NjY3KSI+CjxzdG9wIG9mZnNldD0iMC43NzAyNzciIHN0b3AtY29sb3I9IiNGRjQwMDAiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjODc1NEM5Ii8+CjwvcmFkaWFsR3JhZGllbnQ+CjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQyX2xpbmVhcl84XzU1NCIgeDE9Ijc5LjE2NjYiIHkxPSI5MC44MzMzIiB4Mj0iOTMuMzMzMyIgeTI9IjkwLjgzMzMiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0ZGNDAwMCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM4NzU0QzkiLz4KPC9saW5lYXJHcmFkaWVudD4KPGxpbmVhckdyYWRpZW50IGlkPSJwYWludDNfbGluZWFyXzhfNTU0IiB4MT0iMjkuMTY2NyIgeTE9IjI2LjY2NjciIHgyPSIyOS4xNjY3IiB5Mj0iNDAuODMzMyIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgo8c3RvcCBzdG9wLWNvbG9yPSIjODc1NEM5Ii8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI0ZGNDAwMCIvPgo8L2xpbmVhckdyYWRpZW50Pgo8cmFkaWFsR3JhZGllbnQgaWQ9InBhaW50NF9yYWRpYWxfOF81NTQiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzEuNjY2NiA4OC4zMzMzKSByb3RhdGUoLTkwKSBzY2FsZSg0OC4zMzMzKSI+CjxzdG9wIG9mZnNldD0iMC43MjM5MjkiIHN0b3AtY29sb3I9IiNGRkY3MDAiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjRkY5OTAxIi8+CjwvcmFkaWFsR3JhZGllbnQ+CjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQ1X2xpbmVhcl84XzU1NCIgeDE9IjY2LjY2NjYiIHkxPSI5MC44MzMzIiB4Mj0iODAiIHkyPSI5MC44MzMzIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+CjxzdG9wIHN0b3AtY29sb3I9IiNGRkY3MDAiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjRkY5OTAxIi8+CjwvbGluZWFyR3JhZGllbnQ+CjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQ2X2xpbmVhcl84XzU1NCIgeDE9IjI5LjE2NjYiIHkxPSI1My4zMzMzIiB4Mj0iMjkuMTY2NiIgeTI9IjQwIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+CjxzdG9wIHN0b3AtY29sb3I9IiNGRkY3MDAiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjRkY5OTAxIi8+CjwvbGluZWFyR3JhZGllbnQ+CjxyYWRpYWxHcmFkaWVudCBpZD0icGFpbnQ3X3JhZGlhbF84XzU1NCIgY3g9IjAiIGN5PSIwIiByPSIxIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgZ3JhZGllbnRUcmFuc2Zvcm09InRyYW5zbGF0ZSgzMS42NjY2IDg4LjMzMzMpIHJvdGF0ZSgtOTApIHNjYWxlKDM1KSI+CjxzdG9wIG9mZnNldD0iMC41OTUxMyIgc3RvcC1jb2xvcj0iIzAwQUFGRiIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMwMURBNDAiLz4KPC9yYWRpYWxHcmFkaWVudD4KPHJhZGlhbEdyYWRpZW50IGlkPSJwYWludDhfcmFkaWFsXzhfNTU0IiBjeD0iMCIgY3k9IjAiIHI9IjEiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiBncmFkaWVudFRyYW5zZm9ybT0idHJhbnNsYXRlKDUyLjUgOTAuODMzMykgc2NhbGUoMTQuMTY2NyAzNy43Nzc4KSI+CjxzdG9wIHN0b3AtY29sb3I9IiMwMEFBRkYiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjMDFEQTQwIi8+CjwvcmFkaWFsR3JhZGllbnQ+CjxyYWRpYWxHcmFkaWVudCBpZD0icGFpbnQ5X3JhZGlhbF84XzU1NCIgY3g9IjAiIGN5PSIwIiByPSIxIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgZ3JhZGllbnRUcmFuc2Zvcm09InRyYW5zbGF0ZSgyOS4xNjY2IDY3LjUpIHJvdGF0ZSgtOTApIHNjYWxlKDE0LjE2NjcgMjY4LjY0MikiPgo8c3RvcCBzdG9wLWNvbG9yPSIjMDBBQUZGIi8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzAxREE0MCIvPgo8L3JhZGlhbEdyYWRpZW50Pgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzhfNTU0Ij4KPHJlY3Qgd2lkdGg9IjEyMCIgaGVpZ2h0PSIxMjAiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==":"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgdmlld0JveD0iMCAwIDEyMCAxMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiBmaWxsPSJ1cmwoI3BhaW50MF9saW5lYXJfNjJfMzI5KSIvPgo8cGF0aCBkPSJNMjAgMzhIMjZDNTYuOTI3OSAzOCA4MiA2My4wNzIxIDgyIDk0VjEwMEg5NEM5Ny4zMTM3IDEwMCAxMDAgOTcuMzEzNyAxMDAgOTRDMTAwIDUzLjEzMDkgNjYuODY5MSAyMCAyNiAyMEMyMi42ODYzIDIwIDIwIDIyLjY4NjMgMjAgMjZWMzhaIiBmaWxsPSJ1cmwoI3BhaW50MV9yYWRpYWxfNjJfMzI5KSIvPgo8cGF0aCBkPSJNODQgOTRIMTAwQzEwMCA5Ny4zMTM3IDk3LjMxMzcgMTAwIDk0IDEwMEg4NFY5NFoiIGZpbGw9InVybCgjcGFpbnQyX2xpbmVhcl82Ml8zMjkpIi8+CjxwYXRoIGQ9Ik0yNiAyMEwyNiAzNkgyMEwyMCAyNkMyMCAyMi42ODYzIDIyLjY4NjMgMjAgMjYgMjBaIiBmaWxsPSJ1cmwoI3BhaW50M19saW5lYXJfNjJfMzI5KSIvPgo8cGF0aCBkPSJNMjAgMzZIMjZDNTguMDMyNSAzNiA4NCA2MS45Njc1IDg0IDk0VjEwMEg2NlY5NEM2NiA3MS45MDg2IDQ4LjA5MTQgNTQgMjYgNTRIMjBWMzZaIiBmaWxsPSJ1cmwoI3BhaW50NF9yYWRpYWxfNjJfMzI5KSIvPgo8cGF0aCBkPSJNNjggOTRIODRWMTAwSDY4Vjk0WiIgZmlsbD0idXJsKCNwYWludDVfbGluZWFyXzYyXzMyOSkiLz4KPHBhdGggZD0iTTIwIDUyTDIwIDM2TDI2IDM2TDI2IDUySDIwWiIgZmlsbD0idXJsKCNwYWludDZfbGluZWFyXzYyXzMyOSkiLz4KPHBhdGggZD0iTTIwIDYyQzIwIDY1LjMxMzcgMjIuNjg2MyA2OCAyNiA2OEM0MC4zNTk0IDY4IDUyIDc5LjY0MDYgNTIgOTRDNTIgOTcuMzEzNyA1NC42ODYzIDEwMCA1OCAxMDBINjhWOTRDNjggNzAuODA0IDQ5LjE5NiA1MiAyNiA1MkgyMFY2MloiIGZpbGw9InVybCgjcGFpbnQ3X3JhZGlhbF82Ml8zMjkpIi8+CjxwYXRoIGQ9Ik01MiA5NEg2OFYxMDBINThDNTQuNjg2MyAxMDAgNTIgOTcuMzEzNyA1MiA5NFoiIGZpbGw9InVybCgjcGFpbnQ4X3JhZGlhbF82Ml8zMjkpIi8+CjxwYXRoIGQ9Ik0yNiA2OEMyMi42ODYzIDY4IDIwIDY1LjMxMzcgMjAgNjJMMjAgNTJMMjYgNTJMMjYgNjhaIiBmaWxsPSJ1cmwoI3BhaW50OV9yYWRpYWxfNjJfMzI5KSIvPgo8ZGVmcz4KPGxpbmVhckdyYWRpZW50IGlkPSJwYWludDBfbGluZWFyXzYyXzMyOSIgeDE9IjYwIiB5MT0iMCIgeDI9IjYwIiB5Mj0iMTIwIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+CjxzdG9wIHN0b3AtY29sb3I9IiMxNzQyOTkiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjMDAxRTU5Ii8+CjwvbGluZWFyR3JhZGllbnQ+CjxyYWRpYWxHcmFkaWVudCBpZD0icGFpbnQxX3JhZGlhbF82Ml8zMjkiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjYgOTQpIHJvdGF0ZSgtOTApIHNjYWxlKDc0KSI+CjxzdG9wIG9mZnNldD0iMC43NzAyNzciIHN0b3AtY29sb3I9IiNGRjQwMDAiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjODc1NEM5Ii8+CjwvcmFkaWFsR3JhZGllbnQ+CjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQyX2xpbmVhcl82Ml8zMjkiIHgxPSI4MyIgeTE9Ijk3IiB4Mj0iMTAwIiB5Mj0iOTciIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0ZGNDAwMCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM4NzU0QzkiLz4KPC9saW5lYXJHcmFkaWVudD4KPGxpbmVhckdyYWRpZW50IGlkPSJwYWludDNfbGluZWFyXzYyXzMyOSIgeDE9IjIzIiB5MT0iMjAiIHgyPSIyMyIgeTI9IjM3IiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+CjxzdG9wIHN0b3AtY29sb3I9IiM4NzU0QzkiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjRkY0MDAwIi8+CjwvbGluZWFyR3JhZGllbnQ+CjxyYWRpYWxHcmFkaWVudCBpZD0icGFpbnQ0X3JhZGlhbF82Ml8zMjkiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjYgOTQpIHJvdGF0ZSgtOTApIHNjYWxlKDU4KSI+CjxzdG9wIG9mZnNldD0iMC43MjM5MjkiIHN0b3AtY29sb3I9IiNGRkY3MDAiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjRkY5OTAxIi8+CjwvcmFkaWFsR3JhZGllbnQ+CjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQ1X2xpbmVhcl82Ml8zMjkiIHgxPSI2OCIgeTE9Ijk3IiB4Mj0iODQiIHkyPSI5NyIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgo8c3RvcCBzdG9wLWNvbG9yPSIjRkZGNzAwIi8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI0ZGOTkwMSIvPgo8L2xpbmVhckdyYWRpZW50Pgo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50Nl9saW5lYXJfNjJfMzI5IiB4MT0iMjMiIHkxPSI1MiIgeDI9IjIzIiB5Mj0iMzYiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0ZGRjcwMCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNGRjk5MDEiLz4KPC9saW5lYXJHcmFkaWVudD4KPHJhZGlhbEdyYWRpZW50IGlkPSJwYWludDdfcmFkaWFsXzYyXzMyOSIgY3g9IjAiIGN5PSIwIiByPSIxIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgZ3JhZGllbnRUcmFuc2Zvcm09InRyYW5zbGF0ZSgyNiA5NCkgcm90YXRlKC05MCkgc2NhbGUoNDIpIj4KPHN0b3Agb2Zmc2V0PSIwLjU5NTEzIiBzdG9wLWNvbG9yPSIjMDBBQUZGIi8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzAxREE0MCIvPgo8L3JhZGlhbEdyYWRpZW50Pgo8cmFkaWFsR3JhZGllbnQgaWQ9InBhaW50OF9yYWRpYWxfNjJfMzI5IiBjeD0iMCIgY3k9IjAiIHI9IjEiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiBncmFkaWVudFRyYW5zZm9ybT0idHJhbnNsYXRlKDUxIDk3KSBzY2FsZSgxNyA0NS4zMzMzKSI+CjxzdG9wIHN0b3AtY29sb3I9IiMwMEFBRkYiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjMDFEQTQwIi8+CjwvcmFkaWFsR3JhZGllbnQ+CjxyYWRpYWxHcmFkaWVudCBpZD0icGFpbnQ5X3JhZGlhbF82Ml8zMjkiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjMgNjkpIHJvdGF0ZSgtOTApIHNjYWxlKDE3IDMyMi4zNykiPgo8c3RvcCBzdG9wLWNvbG9yPSIjMDBBQUZGIi8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzAxREE0MCIvPgo8L3JhZGlhbEdyYWRpZW50Pgo8L2RlZnM+Cjwvc3ZnPgo="}")`}}),Brave$1=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("rect",{rx:"27%",width:"88",height:"88",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M69.0892 28.2123L70.5781 24.5643L66.3594 20.1967C64.0763 17.9136 59.2123 19.2537 59.2123 19.2537L53.7031 13H34.2721L28.7381 19.2785C28.7381 19.2785 23.8741 17.9632 21.591 20.1967L17.3722 24.5395L18.8612 28.1875L17 33.5974L23.204 57.2472C24.4945 62.3097 25.3631 64.2702 29.011 66.8511L40.352 74.5441C41.4439 75.2142 42.784 76.3805 44 76.3805C45.216 76.3805 46.5561 75.2142 47.648 74.5441L58.989 66.8511C62.6369 64.2702 63.5055 62.3097 64.796 57.2472L71 33.5974L69.0892 28.2123Z",fill:"url(#paint0_linear_2183_5890)"}),jsxRuntimeExports.jsx("path",{d:"M57.6737 23.2739C57.6737 23.2739 64.796 31.8851 64.796 33.6967C64.796 35.5579 63.9026 36.0294 63.0092 36.9972L57.6737 42.705C57.1774 43.2013 56.1103 44.045 56.7307 45.5092C57.3511 46.9982 58.2197 48.8346 57.227 50.7206C56.2344 52.6314 54.4972 53.8971 53.3805 53.6985C51.7195 53.1594 50.1348 52.4088 48.6654 51.4651C47.7224 50.8447 44.6949 48.3382 44.6949 47.3704C44.6949 46.4026 47.8217 44.6406 48.4173 44.2932C48.9881 43.8961 51.6434 42.3575 51.693 41.7619C51.7427 41.1664 51.7427 41.0175 50.9485 39.5285C50.1544 38.0395 48.7647 36.0542 48.9632 34.7638C49.2114 33.4733 51.4449 32.7785 53.1075 32.1581L58.2445 30.2224C58.6415 30.0239 58.5423 29.8502 57.3511 29.7261C56.1599 29.6268 52.8097 29.1801 51.296 29.602C49.7822 30.0239 47.2509 30.6691 47.0028 31.0165C46.8042 31.364 46.6057 31.364 46.829 32.5551L48.2684 40.3722C48.3677 41.3649 48.5662 42.0349 47.5239 42.2831C46.432 42.5313 44.6204 42.9531 44 42.9531C43.3796 42.9531 41.5432 42.5313 40.4761 42.2831C39.409 42.0349 39.6075 41.3649 39.7316 40.3722C39.8309 39.3796 40.9228 33.7215 41.1461 32.5551C41.3943 31.364 41.171 31.364 40.9724 31.0165C40.7243 30.6691 38.1682 30.0239 36.6544 29.602C35.1654 29.1801 31.7904 29.6268 30.5993 29.7509C29.4081 29.8502 29.3088 29.9991 29.7059 30.2472L34.8428 32.1581C36.4807 32.7785 38.7638 33.4733 38.9871 34.7638C39.2353 36.079 37.8208 38.0395 37.0018 39.5285C36.1829 41.0175 36.2077 41.1664 36.2574 41.7619C36.307 42.3575 38.9871 43.8961 39.5331 44.2932C40.1287 44.6654 43.2555 46.4026 43.2555 47.3704C43.2555 48.3382 40.3024 50.8447 39.3097 51.4651C37.8404 52.4088 36.2557 53.1594 34.5947 53.6985C33.4779 53.8971 31.7408 52.6314 30.7233 50.7206C29.7307 48.8346 30.6241 46.9982 31.2197 45.5092C31.8401 44.0202 30.7978 43.2261 30.2767 42.705L24.9412 36.9972C24.0726 36.079 23.1792 35.5827 23.1792 33.7463C23.1792 31.9099 30.3015 23.3235 30.3015 23.3235L37.0763 24.4154C37.8704 24.4154 39.6324 23.7454 41.2454 23.1746C42.8585 22.6783 43.9752 22.6287 43.9752 22.6287C43.9752 22.6287 45.0671 22.6287 46.705 23.1746C48.3428 23.7206 50.08 24.4154 50.8741 24.4154C51.693 24.4154 57.6985 23.2491 57.6985 23.2491L57.6737 23.2739ZM52.3382 56.2298C52.7849 56.4779 52.512 57.0239 52.0901 57.3217L45.7868 62.2353C45.2904 62.7316 44.4963 63.4761 43.9752 63.4761C43.454 63.4761 42.6847 62.7316 42.1636 62.2353C40.0743 60.5717 37.9648 58.9337 35.8355 57.3217C35.4384 57.0239 35.1654 56.5028 35.5873 56.2298L39.3097 54.2445C40.7894 53.4618 42.3551 52.8539 43.9752 52.4329C44.3474 52.4329 46.705 53.2767 48.6158 54.2445L52.3382 56.2298Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M59.262 19.2785L53.7032 13H34.2721L28.7381 19.2785C28.7381 19.2785 23.8741 17.9632 21.591 20.1967C21.591 20.1967 28.0432 19.6259 30.2767 23.2491L37.126 24.4154C37.9201 24.4154 39.682 23.7454 41.2951 23.1746C42.9081 22.6783 44.0249 22.6287 44.0249 22.6287C44.0249 22.6287 45.1168 22.6287 46.7546 23.1746C48.3925 23.7206 50.1296 24.4154 50.9238 24.4154C51.7427 24.4154 57.7482 23.2491 57.7482 23.2491C59.9817 19.6259 66.4339 20.1967 66.4339 20.1967C64.1508 17.9136 59.2868 19.2537 59.2868 19.2537",fill:"url(#paint1_linear_2183_5890)"}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_2183_5890",x1:"17",y1:"45.3241",x2:"71",y2:"45.3241",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{offset:"0.4",stopColor:"#FF5500"}),jsxRuntimeExports.jsx("stop",{offset:"0.6",stopColor:"#FF2000"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint1_linear_2183_5890",x1:"22.4879",y1:"18.8219",x2:"66.4339",y2:"18.8219",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#FF452A"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"#FF2000"})]})]})]}),Crypto=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"white"},children:[jsxRuntimeExports.jsx("mask",{id:"mask0_2091_4394",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"13",y:"9",width:"62",height:"71",children:jsxRuntimeExports.jsx("path",{d:"M44 9L13 26.75V62.25L44 80L75 62.25V26.75L44 9ZM31.7577 24.3492H56.1513L59.0935 36.684H28.9307L31.7577 24.3492ZM41.5613 61.2993L36.2955 66.161H31.8427L20.6924 46.9369L28.8701 40.9079L36.0953 45.4627V53.6578L41.5552 58.8504V61.2993H41.5613ZM37.9759 53.1584L38.7888 45.4326L36.1256 38.5432H51.9229L49.3204 45.4326L50.0787 53.1283L44 53.1584H37.9759ZM56.2059 66.1069H51.8076L46.5419 61.2993V58.8564L52.0018 53.6638V45.4627L59.1421 40.8537L67.2955 46.9369L56.2059 66.1069Z",fill:"#002D74"})}),jsxRuntimeExports.jsxs("g",{mask:"url(#mask0_2091_4394)",children:[jsxRuntimeExports.jsx("rect",{y:"8",width:"44",height:"72",fill:"url(#paint0_linear_2091_4394)"}),jsxRuntimeExports.jsx("rect",{x:"88",y:"80",width:"44",height:"72",transform:"rotate(-180 88 80)",fill:"url(#paint1_linear_2091_4394)"})]}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_2091_4394",x1:"22",y1:"8",x2:"22",y2:"80",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#010935"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"#142C70"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint1_linear_2091_4394",x1:"110",y1:"80",x2:"110",y2:"152",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#010935"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"#142C70"})]})]})]}),Ledger=({...et})=>jsxRuntimeExports.jsx("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"black"},children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M37.2106 16H16V29.4577H19.2182V19.2182L37.2106 19.1011V16ZM37.3568 33.4073V54.6179H50.8146V51.3997H40.575L40.458 33.4073H37.3568ZM16 72.1714H37.2106V69.0703L19.2182 68.9533V58.7137H16V72.1714ZM50.9609 16H72.1714V29.4577H68.9533V19.2182L50.9609 19.1011V16ZM72.1714 72.1714H50.9609V69.0703L68.9533 68.9533V58.7137H72.1714V72.1714Z",fill:"white"})}),Steak=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"600",height:"600",viewBox:"0 0 600 600",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"black"},children:[jsxRuntimeExports.jsx("path",{d:"M470.747 209.191C462.305 192.354 448.646 178.695 431.808 170.253C413.337 161 389.233 161 341.006 161C331.236 161 307.916 161 300 161C292.084 161 268.728 161 258.994 161C210.856 161 186.662 161 168.191 170.253C151.354 178.69 137.7 192.35 129.27 209.191C119.999 227.662 120 251.767 120 299.976C120 348.185 119.999 372.308 129.27 390.778C137.7 407.619 151.354 421.279 168.191 429.716C186.662 438.97 210.784 438.97 258.994 438.97C268.764 438.97 292.084 438.97 300 438.97C307.916 438.97 331.272 438.97 341.006 438.97C389.144 438.97 413.337 438.97 431.808 429.716C448.646 421.274 462.305 407.616 470.747 390.778C480 372.308 480 348.203 480 299.976C480 251.749 480 227.662 470.747 209.191Z",fill:"#FFCEAA"}),jsxRuntimeExports.jsx("path",{d:"M218.557 350.342C216.323 345.957 212.922 342.274 208.729 339.698C204.536 337.121 199.713 335.752 194.791 335.741H166.747C163.876 335.755 161.041 336.37 158.422 337.548C155.804 338.725 153.462 340.439 151.547 342.577C149.632 344.716 148.186 347.232 147.303 349.964C146.42 352.696 146.12 355.582 146.422 358.437C147.385 367.476 148.954 374.34 151.575 379.564C157.629 391.573 167.378 401.323 179.388 407.377C188.195 411.798 201.674 413.26 222.444 413.742C225.415 413.812 228.353 413.109 230.97 411.702C233.587 410.295 235.793 408.232 237.373 405.715C238.953 403.199 239.852 400.315 239.982 397.346C240.113 394.378 239.47 391.427 238.116 388.781L218.557 350.342Z",fill:"#FF3B9A"}),jsxRuntimeExports.jsx("path",{d:"M180.618 312.563C189.852 312.562 198.95 310.335 207.14 306.071C215.33 301.806 222.371 295.63 227.668 288.066L254.856 249.253C259.761 242.25 262.839 234.134 263.81 225.64C264.782 217.146 263.616 208.545 260.419 200.616V200.384C258.913 196.555 256.409 193.2 253.167 190.666C249.925 188.133 246.064 186.514 241.985 185.978C209.732 186.085 190.726 186.887 179.405 192.575C167.37 198.586 157.611 208.339 151.592 220.37C146.725 230.247 145.227 258.007 144.87 280.507C144.797 284.698 145.56 288.862 147.114 292.754C148.668 296.647 150.983 300.191 153.923 303.179C156.863 306.167 160.369 308.539 164.236 310.156C168.103 311.774 172.254 312.604 176.445 312.599L180.618 312.563Z",fill:"#FF3B9A"}),jsxRuntimeExports.jsx("path",{d:"M449.702 220.356C443.655 208.365 433.909 198.639 421.906 192.614C409.89 186.588 389.262 186.053 353.337 186C304.664 186 289.528 242 279.134 256.834L248.556 300.497C243.645 307.51 240.729 315.725 240.12 324.266C239.511 332.806 241.231 341.352 245.098 348.991L267.758 393.813C270.842 399.931 275.578 405.063 281.43 408.627C287.282 412.191 294.016 414.045 300.867 413.978H301.49C309.495 413.978 334.171 413.978 342.283 413.978C385.072 413.978 408.713 413.977 421.906 407.381C433.914 401.331 443.66 391.58 449.702 379.568C456.317 366.374 456.316 342.787 456.316 299.944C456.316 257.101 456.317 233.621 449.702 220.356Z",fill:"#FF3B9A"})]}),Unstoppable=({...et})=>jsxRuntimeExports.jsx("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"linear-gradient(180deg, #FED812 0%, #FFAF00 100%)"},children:jsxRuntimeExports.jsx("path",{d:"M47.4 43.7163C47.4 45.6251 45.8781 47.1714 44.0001 47.1714C42.1219 47.1714 40.6 45.6251 40.6 43.7163L40.6 -7H27L27 43.7163C27 53.2612 34.6106 61 44.0001 61C53.3882 61 61 53.2612 61 43.7163V-7H47.4V43.7163Z",fill:"#1F2129"})}),ONTO=({...et})=>jsxRuntimeExports.jsx("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"white"},children:jsxRuntimeExports.jsx("path",{d:"M20 16L28.675 24.677C32.1885 21.8644 36.4154 20.0873 40.8816 19.545C45.348 19.0026 49.8769 19.7164 53.9604 21.6063C58.0438 23.4963 61.5207 26.4876 64.0005 30.2447C66.4804 34.0019 67.8653 38.3763 68 42.8772V43.5854V72L59.3367 63.3231C55.8263 66.1389 51.6014 67.9196 47.1361 68.4655C42.6708 69.0112 38.1419 68.3007 34.0577 66.4135C29.9734 64.5262 26.4956 61.537 24.0144 57.7813C21.5333 54.0255 20.1472 49.6521 20.0115 45.1515V44.4433L20 16ZM25.931 30.3311V44.4146C25.9323 47.7294 26.8335 50.9817 28.5384 53.8236C30.2432 56.6655 32.6875 58.9902 35.6101 60.5497C38.5328 62.1089 41.8238 62.8439 45.1313 62.6764C48.439 62.5087 51.639 61.4445 54.3894 59.5978L54.8611 59.2754L27.0873 31.4884L25.931 30.3311ZM33.6223 28.4022L33.1505 28.7304L60.9186 56.5117L62.069 57.6632V43.5854C62.0683 40.2717 61.1679 37.0204 59.464 34.179C57.7603 31.3377 55.3171 29.0132 52.3957 27.4539C49.4742 25.8946 46.1844 25.1592 42.8777 25.3262C39.5712 25.4933 36.372 26.5565 33.6223 28.4022Z",fill:"#23262F"})}),Slope=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"#6C67F1"},children:[jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M50.6667 24.3696L34.8872 40.1864L24.0001 37.7402L37.3334 24.3696L48.4438 13.3798C49.268 12.5646 50.6667 13.1484 50.6667 14.3077V24.3696ZM37.3339 51.0358L50.6672 37.74V24.3694L35.2001 39.8737L37.3339 51.0358Z",fill:"url(#paint0_linear_2593_6077)"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M37.3337 64.2947V50.9617L50.667 37.6284L55.7849 45.8435L55.9822 45.6463L64 50.9616L39.5582 75.2343C38.7347 76.0521 37.3336 75.4687 37.3336 74.3082V64.2949L37.3337 64.2947Z",fill:"url(#paint1_linear_2593_6077)"}),jsxRuntimeExports.jsx("path",{d:"M24 37.7405H32.573C35.202 37.7405 37.3333 39.8718 37.3333 42.5009V51.0359H28.7602C26.1313 51.0359 24 48.9046 24 46.2757V37.7405Z",fill:"#F1F0FF"}),jsxRuntimeExports.jsx("path",{d:"M50.6667 37.7405H59.2398C61.8688 37.7405 64 39.8718 64 42.5009V51.0359H55.4271C52.798 51.0359 50.6667 48.9046 50.6667 46.2757V37.7405Z",fill:"#F1F0FF"}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_2593_6077",x1:"37.3336",y1:"13",x2:"37.3336",y2:"51.0358",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#A8ADFF"}),jsxRuntimeExports.jsx("stop",{offset:"0.648556",stopColor:"white"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint1_linear_2593_6077",x1:"50.6668",y1:"37.6284",x2:"50.6668",y2:"75.616",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{offset:"0.260784",stopColor:"#B6BAFF"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"#E4E2FF"})]})]})]}),Safe=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"var(--ck-brand-safe)"},children:[jsxRuntimeExports.jsx("path",{d:"M68.7186 44H62.6472C60.8339 44 59.3646 45.4686 59.3646 47.281V56.0888C59.3646 57.9012 57.8952 59.3697 56.0819 59.3697H31.9278C30.1145 59.3697 28.6452 60.8383 28.6452 62.6507V68.719C28.6452 70.5314 30.1145 72 31.9278 72H57.48C59.2933 72 60.7417 70.5314 60.7417 68.719V63.8504C60.7417 62.038 62.2111 60.7524 64.0244 60.7524H68.7174C70.5307 60.7524 72 59.2838 72 57.4714V47.2429C72 45.4305 70.5307 44 68.7174 44H68.7186Z",fill:"#121312"}),jsxRuntimeExports.jsx("path",{d:"M28.6406 31.9308C28.6406 30.1162 30.1104 28.6458 31.9243 28.6458H56.0712C57.8851 28.6458 59.3548 27.1754 59.3548 25.3608V19.285C59.3548 17.4704 57.8851 16 56.0712 16H30.5245C28.7107 16 27.2409 17.4704 27.2409 19.285V23.9666C27.2409 25.7813 25.7711 27.2516 23.9572 27.2516H19.2837C17.4698 27.2516 16 28.722 16 30.5366V40.7888C16 42.6034 17.4759 44 19.2898 44H25.3631C27.177 44 28.6468 42.5296 28.6468 40.715L28.6406 31.932V31.9308Z",fill:"#121312"}),jsxRuntimeExports.jsx("path",{d:"M41.1004 37.6774H46.8995C48.7894 37.6774 50.3226 39.2117 50.3226 41.1004V46.8995C50.3226 48.7894 48.7882 50.3225 46.8995 50.3225H41.1004C39.2106 50.3225 37.6774 48.7882 37.6774 46.8995V41.1004C37.6774 39.2105 39.2118 37.6774 41.1004 37.6774V37.6774Z",fill:"#121312"})]}),Frontier=({...et})=>jsxRuntimeExports.jsx("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"#CC703C"},children:jsxRuntimeExports.jsx("path",{d:"M63.6429 20L63.3645 20.7254L62.4521 23.0445L61.8461 24.5395C57.2427 35.7491 53.6629 41.0688 49.8557 41.0688C48.8938 41.0936 47.9371 40.9212 47.0465 40.5625C46.156 40.2038 45.3512 39.6667 44.6834 38.9852L44.1979 38.5518C42.9885 37.4538 42.4799 37.1831 41.3154 37.1832C40.7094 37.1832 39.6238 37.9435 38.2521 39.7303C36.4147 42.2912 34.8522 45.0327 33.59 47.9106L33.4353 48.2482L49.7645 48.2483L47.7312 52.4075H32.4845L32.4843 69.44L28 69.44L28.0001 20L63.6429 20ZM57.2889 24.1518L32.4843 24.1518L32.4843 40.6262C35.4564 35.5545 38.2816 33.0086 41.32 33.0086C42.3421 32.9765 43.3595 33.1534 44.3082 33.5284C45.2569 33.9034 46.1159 34.468 46.8311 35.1865L47.3323 35.6335C48.4611 36.6585 48.8956 36.8941 49.8604 36.8941C50.9211 36.8957 53.7433 32.4855 57.2889 24.1518Z",fill:"white"})}),Zerion=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"linear-gradient(120.22deg, #2962EF 0%, #255CE5 100%)"},children:[jsxRuntimeExports.jsx("path",{d:"M19.0864 22C17.5783 22 16.9973 23.8648 18.2628 24.6438L49.9199 43.732C50.709 44.2178 51.7614 44.0258 52.3048 43.2969L66.2236 25.024C67.17 23.7545 66.2138 22 64.5757 22H19.0864Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M68.8425 66C70.3503 66 70.9466 64.1252 69.6814 63.3464L38.015 44.2605C37.2259 43.7748 36.1989 43.991 35.6558 44.7198L21.7099 62.9891C20.7639 64.2582 21.7499 66 23.3877 66H68.8425Z",fill:"white"})]}),Phantom=({background:et=!1,...o})=>jsxRuntimeExports.jsx("svg",{...o,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:et?{background:"#AB9FF2"}:void 0,children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M37.7425 57.0705C34.1942 62.3362 28.2483 69 20.3366 69C16.5965 69 13.0001 67.5093 13 61.0322C12.9997 44.5362 36.2555 19.0003 57.8334 19C70.1084 18.9998 75 27.2474 75 36.6136C75 48.6357 66.9442 62.3824 58.9368 62.3824C56.3955 62.3824 55.1487 61.031 55.1487 58.888C55.1487 58.3288 55.2442 57.7228 55.4365 57.0705C52.7029 61.5902 47.4285 65.7849 42.4896 65.7849C38.8933 65.7849 37.0713 63.5944 37.0713 60.5187C37.0713 59.4003 37.311 58.2357 37.7425 57.0705ZM53.7586 31.6834C51.8054 31.6868 50.4738 33.2938 50.478 35.5864C50.4822 37.879 51.8198 39.5273 53.7729 39.5241C55.6789 39.5208 57.0099 37.8679 57.0058 35.5752C57.0016 33.2827 55.6646 31.6802 53.7586 31.6834ZM64.1193 31.6725C62.1661 31.6759 60.8345 33.2829 60.8387 35.5755C60.8429 37.868 62.1798 39.5164 64.1336 39.5131C66.0396 39.5099 67.3706 37.8569 67.3664 35.5643C67.3622 33.2718 66.0253 31.6693 64.1193 31.6725Z",fill:et?"#ffffff":"currentColor"})}),PlaceHolder=()=>jsxRuntimeExports.jsx("div",{style:{width:80,height:80,background:"#555"}}),Dawn=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"88px",height:"88px",viewBox:"0 0 192 192",version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",children:[jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{x1:"50%",y1:"0%",x2:"50%",y2:"100%",id:"linearGradient-1",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#151515",offset:"0%"}),jsxRuntimeExports.jsx("stop",{stopColor:"#232323",offset:"100%"})]}),jsxRuntimeExports.jsx("rect",{rx:"27%",id:"path-2",x:"0",y:"0",width:"192",height:"192"}),jsxRuntimeExports.jsxs("linearGradient",{x1:"50%",y1:"0%",x2:"50%",y2:"99.7051532%",id:"linearGradient-3",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#F3DC83",offset:"0%"}),jsxRuntimeExports.jsx("stop",{stopColor:"#F9EEC8",offset:"100%"})]})]}),jsxRuntimeExports.jsx("g",{id:"Icons---Pixel-Fitted",stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:jsxRuntimeExports.jsxs("g",{id:"Group",children:[jsxRuntimeExports.jsxs("g",{id:"Rectangle",children:[jsxRuntimeExports.jsx("use",{fill:"#232323",xlinkHref:"#path-2"}),jsxRuntimeExports.jsx("use",{fill:"url(#linearGradient-1)",xlinkHref:"#path-2"})]}),jsxRuntimeExports.jsx("path",{d:"M123.748399,157.001808 C115.293464,160.853955 105.89735,163 96,163 C86.1026503,163 76.7065363,160.853955 68.2516012,157.001808 Z M146.526595,140.002206 C144.677242,142.123986 142.696426,144.128189 140.59684,146.002121 L51.4031598,146.002121 C49.3035743,144.128189 47.3227581,142.123986 45.4734054,140.002206 Z M157.337411,122.999613 C155.955969,126.133404 154.34141,129.141319 152.515704,132.001388 L39.484296,132.001388 C37.6585895,129.141319 36.0440306,126.133404 34.662589,122.999613 Z M96,29 C133.003078,29 163,58.9969218 163,96 C163,103.706309 161.69895,111.108742 159.304524,117.999626 L32.6954763,117.999626 C30.3010496,111.108742 29,103.706309 29,96 C29,58.9969218 58.9969218,29 96,29 Z",id:"Combined-Shape",fill:"url(#linearGradient-3)"})]})})]}),InfinityWallet=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,version:"1.1",id:"e551690a-81c0-4880-9b93-334a37ce6796",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 1025 1025",children:[jsxRuntimeExports.jsx("style",{type:"text/css",children:` + .infinityWallet-st0{fill:url(#ID_InfinityWallet_1);} + .infinityWallet-st1{fill:url(#ID_InfinityWallet_2);} + .infinityWallet-st2{opacity:0.49;fill:url(#ID_InfinityWallet_3);enable-background:new;} + .infinityWallet-st3{opacity:0.49;fill:url(#ID_InfinityWallet_4);enable-background:new;} + .infinityWallet-st4{opacity:0.49;fill:url(#ID_InfinityWallet_5);enable-background:new;} + .infinityWallet-st5{fill:url(#ID_InfinityWallet_6);} + .infinityWallet-st6{opacity:0.49;fill:url(#ID_InfinityWallet_7);enable-background:new;} + .infinityWallet-st7{opacity:0.49;fill:url(#ID_InfinityWallet_8);enable-background:new;} + .infinityWallet-st8{opacity:0.49;fill:url(#ID_InfinityWallet_9);enable-background:new;} + `}),jsxRuntimeExports.jsxs("linearGradient",{id:"ID_InfinityWallet_1",gradientUnits:"userSpaceOnUse",x1:"512.5",y1:"1056.1801",x2:"512.5",y2:"317.03",gradientTransform:"matrix(1 0 0 -1 0 1260)",children:[jsxRuntimeExports.jsx("stop",{offset:"0",style:{stopColor:"#1D2643"}}),jsxRuntimeExports.jsx("stop",{offset:"1",style:{stopColor:"#12142C"}})]}),jsxRuntimeExports.jsx("path",{className:"infinityWallet-st0",d:`M130,0H895c71.8,0,130,58.2,130,130V895c0,71.8-58.2,130-130,130H130C58.2,1025,0,966.8,0,895V130 + C0,58.2,58.2,0,130,0z`}),jsxRuntimeExports.jsxs("g",{children:[jsxRuntimeExports.jsxs("g",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"ID_InfinityWallet_2",gradientUnits:"userSpaceOnUse",x1:"326.0557",y1:"-1280.3162",x2:"326.0557",y2:"-296.3967",gradientTransform:"matrix(1 0 0 1 0 1474)",children:[jsxRuntimeExports.jsx("stop",{offset:"1.000000e-02",style:{stopColor:"#00BFE1"}}),jsxRuntimeExports.jsx("stop",{offset:"0.97",style:{stopColor:"#2738AB"}})]}),jsxRuntimeExports.jsx("path",{className:"infinityWallet-st1",d:`M550.9,380.8c-0.7-2-2.4-3.4-4.4-3.9c-2.3-0.6-4.7,0-6.4,1.7l-13.4,13.4l-2.2,2.2L418.3,288.5 + c-40.2-40-105.2-40-145.4,0L121.7,439.9c-40,40.5-40,105.6,0,146.1l151.4,150.5c40.2,40,105.1,40,145.3,0l34.4-34.4 + c4.5-4.5,9.9-10.7,12.9-18.7c4.7-13.1,2.8-27.7-5.2-39.1c-1.5-2.2-3.2-4.2-5.1-6c-16.9-16.5-43.9-16.3-60.7,0.3l-37.2,37.1 + c-2.2,2.3-5,3.8-8.1,4.5c-2.9,0.7-6,0.5-8.8-0.6c-2.9-1-5.5-2.7-7.7-5L182.6,524.2c-2.3-2.3-3.9-5.2-4.6-8.4 + c-0.8-4-0.1-8.2,2.1-11.8l0.8-0.9L334,350.3c2.4-2.4,5.4-4,8.7-4.6c1-0.2,2.1-0.3,3.1-0.3c4.4-0.1,8.7,1.7,11.7,5l105.8,105.2 + l-5.3,5.3l-10.4,10.6c-1.7,1.7-2.3,4.1-1.7,6.4c0.5,2,2,3.7,3.9,4.4l95.7,11.7c8.2-0.1,14.8-6.7,15-15L550.9,380.8z`}),jsxRuntimeExports.jsxs("linearGradient",{id:"ID_InfinityWallet_3",gradientUnits:"userSpaceOnUse",x1:"137.7126",y1:"-935.1906",x2:"201.098",y2:"-882.1746",gradientTransform:"matrix(1 0 0 1 -0.94 1473.3899)",children:[jsxRuntimeExports.jsx("stop",{offset:"3.000000e-02",style:{stopColor:"#1B1464"}}),jsxRuntimeExports.jsx("stop",{offset:"1",style:{stopColor:"#1B1464",stopOpacity:0}})]}),jsxRuntimeExports.jsx("path",{className:"infinityWallet-st2",d:"M181.4,522.9c-4.3-4.9-5.1-13.3-1.3-19c0,0-49.7,54.3-25.8,114.4l31.5,31.3l45.8-76.2L181.4,522.9z"}),jsxRuntimeExports.jsxs("linearGradient",{id:"ID_InfinityWallet_4",gradientUnits:"userSpaceOnUse",x1:"4132.3252",y1:"1674.2513",x2:"4102.1333",y2:"1717.0756",gradientTransform:"matrix(-1 0 0 -1 4515 2382.0898)",children:[jsxRuntimeExports.jsx("stop",{offset:"3.000000e-02",style:{stopColor:"#1B1464"}}),jsxRuntimeExports.jsx("stop",{offset:"1",style:{stopColor:"#1B1464",stopOpacity:0}})]}),jsxRuntimeExports.jsx("path",{className:"infinityWallet-st3",d:`M336.4,677.7c56.1,51.6,117.9,22.9,117.9,22.9s8.1-7.5,11.4-17.4c-8.3-4-68.6-47.2-68.6-47.2l-35.6,35.6 + C348.6,687.1,336.4,677.7,336.4,677.7z`}),jsxRuntimeExports.jsxs("linearGradient",{id:"ID_InfinityWallet_5",gradientUnits:"userSpaceOnUse",x1:"4217.4238",y1:"2067.1885",x2:"4240.0796",y2:"2011.1337",gradientTransform:"matrix(-1 0 0 -1 4515 2382.0898)",children:[jsxRuntimeExports.jsx("stop",{offset:"3.000000e-02",style:{stopColor:"#1B1464"}}),jsxRuntimeExports.jsx("stop",{offset:"1",style:{stopColor:"#1B1464",stopOpacity:0}})]}),jsxRuntimeExports.jsx("path",{className:"infinityWallet-st4",d:"M299.4,385c0,0,35.9-36.2,36-36c0,0,9.6-7.7,19.7-0.7c0,0-59.7-49.2-123.6-18.3l-18.6,18.7L299.4,385z"})]}),jsxRuntimeExports.jsxs("g",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"ID_InfinityWallet_6",gradientUnits:"userSpaceOnUse",x1:"698.9443",y1:"-1280.3162",x2:"698.9443",y2:"-296.3967",gradientTransform:"matrix(1 0 0 1 0 1474)",children:[jsxRuntimeExports.jsx("stop",{offset:"1.000000e-02",style:{stopColor:"#00BFE1"}}),jsxRuntimeExports.jsx("stop",{offset:"0.97",style:{stopColor:"#2738AB"}})]}),jsxRuntimeExports.jsx("path",{className:"infinityWallet-st5",d:`M474.1,644.3c0.7,2,2.4,3.4,4.4,3.9c2.3,0.6,4.7,0,6.4-1.7l13.4-13.4l2.2-2.2l106.2,105.6 + c40.2,40,105.2,40,145.4,0l151.2-151.4c40-40.5,40-105.6,0-146.1L751.9,288.5c-40.2-40-105.1-40-145.3,0l-34.4,34.4 + c-4.5,4.5-9.9,10.7-12.9,18.7c-4.7,13.1-2.8,27.7,5.2,39.1c1.5,2.2,3.2,4.2,5.1,6c16.9,16.5,43.9,16.3,60.7-0.3l37.2-37.1 + c2.2-2.3,5-3.8,8.1-4.5c2.9-0.7,6-0.5,8.8,0.6c2.9,1,5.5,2.7,7.7,5l150.3,150.3c2.3,2.3,3.9,5.2,4.6,8.4c0.8,4,0.1,8.2-2.1,11.8 + l-0.8,0.9L691,674.5c-2.4,2.4-5.4,4-8.7,4.6c-1,0.2-2.1,0.3-3.1,0.3c-4.4,0.1-8.7-1.7-11.7-5L561.6,569.7l5.3-5.3l10.4-10.6 + c1.7-1.7,2.3-4.1,1.7-6.4c-0.5-2-2-3.7-3.9-4.4l-95.6-11.7c-8.2,0.1-14.8,6.7-15,15L474.1,644.3z`}),jsxRuntimeExports.jsxs("linearGradient",{id:"ID_InfinityWallet_7",gradientUnits:"userSpaceOnUse",x1:"3824.9182",y1:"1469.7789",x2:"3888.3037",y2:"1522.7949",gradientTransform:"matrix(-1 0 0 -1 4713.1299 1956.6599)",children:[jsxRuntimeExports.jsx("stop",{offset:"3.000000e-02",style:{stopColor:"#1B1464"}}),jsxRuntimeExports.jsx("stop",{offset:"1",style:{stopColor:"#1B1464",stopOpacity:0}})]}),jsxRuntimeExports.jsx("path",{className:"infinityWallet-st6",d:"M843.6,502.2c4.3,4.9,5.1,13.3,1.3,19c0,0,49.7-54.3,25.8-114.4l-31.5-31.3l-45.8,76.2L843.6,502.2z"}),jsxRuntimeExports.jsxs("linearGradient",{id:"ID_InfinityWallet_8",gradientUnits:"userSpaceOnUse",x1:"445.1279",y1:"-730.6945",x2:"414.9359",y2:"-687.8702",gradientTransform:"matrix(1 0 0 1 197.19 1047.96)",children:[jsxRuntimeExports.jsx("stop",{offset:"3.000000e-02",style:{stopColor:"#1B1464"}}),jsxRuntimeExports.jsx("stop",{offset:"1",style:{stopColor:"#1B1464",stopOpacity:0}})]}),jsxRuntimeExports.jsx("path",{className:"infinityWallet-st7",d:`M688.6,347.4c-56.1-51.6-117.9-22.9-117.9-22.9s-8.1,7.5-11.4,17.4c8.3,4,68.6,47.2,68.6,47.2l35.6-35.6 + C676.4,338,688.6,347.4,688.6,347.4z`}),jsxRuntimeExports.jsxs("linearGradient",{id:"ID_InfinityWallet_9",gradientUnits:"userSpaceOnUse",x1:"530.1512",y1:"-337.7953",x2:"552.8069",y2:"-393.8502",gradientTransform:"matrix(1 0 0 1 197.19 1047.96)",children:[jsxRuntimeExports.jsx("stop",{offset:"3.000000e-02",style:{stopColor:"#1B1464"}}),jsxRuntimeExports.jsx("stop",{offset:"1",style:{stopColor:"#1B1464",stopOpacity:0}})]}),jsxRuntimeExports.jsx("path",{className:"infinityWallet-st8",d:"M725.5,640.1c0,0-35.9,36.2-36,36c0,0-9.6,7.7-19.7,0.7c0,0,59.7,49.2,123.6,18.3l18.6-18.7L725.5,640.1z"})]})]})]}),Rabby=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"88",height:"88",viewBox:"0 0 88 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:"#8697FF"},children:[jsxRuntimeExports.jsx("path",{d:"M76.2062 48.0657C78.7621 42.356 66.1267 26.404 54.0555 19.7581C46.4467 14.6095 38.5183 15.3169 36.9125 17.5775C33.3886 22.5385 48.5814 26.7423 58.742 31.6478C56.5579 32.5964 54.4996 34.2987 53.2893 36.4758C49.5013 32.3404 41.1872 28.7791 31.4315 31.6478C24.8574 33.5809 19.3937 38.1382 17.2821 45.0216C16.7689 44.7936 16.2009 44.6669 15.6032 44.6669C13.3176 44.6669 11.4648 46.5197 11.4648 48.8052C11.4648 51.0908 13.3176 52.9435 15.6032 52.9435C16.0268 52.9435 17.3514 52.6594 17.3514 52.6594L38.5183 52.8128C30.0532 66.2418 23.3634 68.2049 23.3634 70.5314C23.3634 72.8579 29.7643 72.2274 32.1678 71.3602C43.6732 67.2088 56.0306 54.2706 58.1511 50.5462C67.056 51.6572 74.5397 51.7886 76.2062 48.0657Z",fill:"url(#paint0_linear_60607_36577)"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M58.65 31.6053C58.682 31.6193 58.7139 31.6332 58.7458 31.6471C59.2168 31.4616 59.1406 30.766 59.0113 30.2198C58.714 28.9643 53.5856 23.9001 48.7696 21.6318C42.1984 18.5367 37.3618 18.7007 36.6582 20.1307C37.9975 22.8695 44.1927 25.441 50.663 28.1266C53.3909 29.2589 56.1676 30.4114 58.65 31.6053Z",fill:"url(#paint1_linear_60607_36577)"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M50.4154 59.2247C49.0895 58.7182 47.592 58.2536 45.8898 57.8319C47.707 54.5801 48.0884 49.7663 46.3721 46.7226C43.9635 42.4512 40.9399 40.1777 33.9139 40.1777C30.0495 40.1777 19.6451 41.4794 19.4603 50.1648C19.441 51.0763 19.4599 51.9118 19.5259 52.68L38.5175 52.8176C35.9568 56.8798 33.5586 59.8928 31.4589 62.1841C33.9831 62.8309 36.0657 63.3738 37.9775 63.8722C39.7885 64.3443 41.4462 64.7764 43.1809 65.2191C45.8007 63.3102 48.2635 61.2288 50.4154 59.2247Z",fill:"url(#paint2_linear_60607_36577)"}),jsxRuntimeExports.jsx("path",{d:"M17.0296 51.7821C17.8058 58.38 21.5555 60.9657 29.2177 61.7309C36.8799 62.4961 41.2751 61.9828 47.1265 62.5151C52.0136 62.9598 56.3772 65.4502 57.996 64.5895C59.4529 63.815 58.6378 61.0167 56.6884 59.2214C54.1614 56.8943 50.6641 55.2763 44.5104 54.7021C45.7368 51.3443 45.3931 46.6362 43.4885 44.0748C40.7345 40.3711 35.6513 38.6967 29.2177 39.4282C22.4962 40.1926 16.0556 43.5018 17.0296 51.7821Z",fill:"url(#paint3_linear_60607_36577)"}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_60607_36577",x1:"30.666",y1:"43.0094",x2:"75.6558",y2:"55.7677",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"white"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"white"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint1_linear_60607_36577",x1:"68.0842",y1:"42.1521",x2:"35.6221",y2:"9.60636",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#7258DC"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"#797DEA",stopOpacity:"0"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint2_linear_60607_36577",x1:"51.3184",y1:"60.3591",x2:"20.1383",y2:"42.4347",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#7461EA"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"#BFC2FF",stopOpacity:"0"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint3_linear_60607_36577",x1:"33.3531",y1:"42.6732",x2:"54.4308",y2:"69.4547",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"white"}),jsxRuntimeExports.jsx("stop",{offset:"0.983895",stopColor:"#D5CEFF"})]})]})]}),TokenPocket=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"88px",height:"88px",viewBox:"0 0 88 88",version:"1.1",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsxs("linearGradient",{x1:"107.511425%",y1:"50.0147427%",x2:"0.0459570557%",y2:"50.0147427%",id:"linearGradient-1",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#FFFFFF",offset:"0%"}),jsxRuntimeExports.jsx("stop",{stopColor:"#FFFFFF",stopOpacity:"0.3233",offset:"96.67%"}),jsxRuntimeExports.jsx("stop",{stopColor:"#FFFFFF",stopOpacity:"0.3",offset:"100%"})]})}),jsxRuntimeExports.jsx("g",{stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:jsxRuntimeExports.jsxs("g",{id:"tokenpocket",fillRule:"nonzero",children:[jsxRuntimeExports.jsx("polygon",{fill:"#2980FE",points:"87.9604864 0 0 0 0 88 87.9604864 88"}),jsxRuntimeExports.jsxs("g",{transform:"translate(16.052385, 23.804688)",children:[jsxRuntimeExports.jsx("path",{d:"M19.6653508,13.8911953 L19.6784508,13.8911953 C19.6653508,13.8236484 19.6653508,13.7448437 19.6653508,13.6772969 L19.6653508,13.8911953 Z",fill:"#29AEFF"}),jsxRuntimeExports.jsx("path",{d:"M41.1271993,16.0301797 L29.2440711,16.0301797 L29.2440711,38.4205938 C29.2440711,39.4787422 30.0635659,40.3343359 31.0771712,40.3343359 L39.2940168,40.3343359 C40.3077044,40.3343359 41.1271993,39.4787422 41.1271993,38.4205938 L41.1271993,16.0301797 Z",fill:"#FFFFFF"}),jsxRuntimeExports.jsx("path",{d:"M23.5075248,0 L23.1085201,0 L1.83318241,0 C0.819494855,0 0,0.855507812 0,1.91374219 L0,9.68111719 C0,10.7393516 0.819494855,11.5948594 1.83318241,11.5948594 L6.82580355,11.5948594 L8.80996071,11.5948594 L8.80996071,13.8912813 L8.80996071,38.4768828 C8.80996071,39.5351172 9.62945557,40.390625 10.6430608,40.390625 L18.4502002,40.390625 C19.4638054,40.390625 20.2833003,39.5351172 20.2833003,38.4768828 L20.2833003,13.8912813 L20.2833003,13.6774688 L20.2833003,11.5948594 L22.2674574,11.5948594 L23.0761684,11.5948594 L23.4751731,11.5948594 C26.5376389,11.5948594 29.0285575,8.99447656 29.0285575,5.79742969 C29.0609093,2.60038281 26.5699906,0 23.5075248,0 Z",fill:"#FFFFFF"}),jsxRuntimeExports.jsx("path",{d:"M41.1381478,16.0301797 L41.1381478,31.6550781 C41.5479364,31.7563984 41.9684266,31.8352031 42.399783,31.90275 C43.0036819,31.9928125 43.6290664,32.0491016 44.2545332,32.0603594 C44.2868849,32.0603594 44.3192367,32.0603594 44.3623723,32.0603594 L44.3623723,19.6324219 C42.5615416,19.5085859 41.1381478,17.9438359 41.1381478,16.0301797 Z",fill:"url(#linearGradient-1)"}),jsxRuntimeExports.jsx("path",{d:"M44.5993714,0 C36.1237942,0 29.2440711,7.18205469 29.2440711,16.0301797 C29.2440711,23.6400312 34.3229635,30.0115234 41.1379832,31.6550781 L41.1379832,16.0301797 C41.1379832,14.0376328 42.6907839,12.4165937 44.5993714,12.4165937 C46.5080412,12.4165937 48.0608419,14.0376328 48.0608419,16.0301797 C48.0608419,17.7075078 46.9717493,19.1146484 45.483652,19.5198437 C45.2032703,19.5986484 44.9013209,19.6436797 44.5993714,19.6436797 L44.5993714,32.0603594 C44.9013209,32.0603594 45.1924864,32.0491016 45.483652,32.0378438 C53.5495229,31.5537578 59.9547666,24.5743438 59.9547666,16.0301797 C59.9655379,7.18205469 53.0858148,0 44.5993714,0 Z",fill:"#FFFFFF"}),jsxRuntimeExports.jsx("path",{d:"M44.5992891,32.0603594 L44.5992891,19.6436797 C44.5131001,19.6436797 44.4376127,19.6436797 44.3513414,19.6324219 L44.3513414,32.0603594 C44.4376127,32.0603594 44.523884,32.0603594 44.5992891,32.0603594 Z",fill:"#FFFFFF"})]})]})})]}),Talisman=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"82",height:"82",viewBox:"0 0 82 82",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("rect",{width:"82",height:"82",rx:"12",fill:"#D5FF5C"}),jsxRuntimeExports.jsx("path",{d:"M35.04 55C35.04 58.2905 37.6887 60.9623 40.9703 60.9996C44.2519 60.9623 46.9006 58.2905 46.9006 55C46.9006 51.7096 44.2519 49.0377 40.9703 49.0004C37.6887 49.0377 35.04 51.7096 35.04 55Z",fill:"#FD4848"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M22.8544 44.6623C22.2462 45.9868 20.4553 46.4546 19.4248 45.4241L17.5356 43.5349C15.583 41.5823 12.4171 41.5823 10.4645 43.5349C8.51184 45.4875 8.51184 48.6534 10.4645 50.606L25.7391 65.8807C29.3942 70.2176 34.8595 72.9788 40.9703 72.9994C47.0811 72.9788 52.5464 70.2176 56.2014 65.8807L71.4761 50.606C73.4287 48.6534 73.4287 45.4875 71.4761 43.5349C69.5234 41.5823 66.3576 41.5823 64.4049 43.5349L62.5158 45.4241C61.4852 46.4546 59.6943 45.9868 59.0861 44.6623C58.9663 44.4013 58.901 44.1213 58.901 43.8341L58.901 20.9995C58.901 18.2381 56.6624 15.9995 53.901 15.9995C51.1396 15.9995 48.901 18.2381 48.901 20.9995L48.901 32.5568C48.901 33.5506 47.8829 34.2252 46.9353 33.9257C46.3356 33.7361 45.9023 33.1901 45.9023 32.5611L45.9023 13.9996C45.9023 11.2608 43.7004 9.03637 40.9703 9C38.2402 9.03637 36.0382 11.2608 36.0382 13.9996L36.0382 32.5611C36.0382 33.1901 35.605 33.7361 35.0052 33.9257C34.0576 34.2252 33.0395 33.5506 33.0395 32.5568L33.0396 20.9995C33.0396 18.2381 30.801 15.9995 28.0395 15.9995C25.2781 15.9995 23.0395 18.2381 23.0395 20.9995L23.0395 43.8341C23.0395 44.1213 22.9743 44.4013 22.8544 44.6623ZM40.9703 44.9999C32.1659 45.0525 25.0403 54.9997 25.0403 54.9997C25.0403 54.9997 32.1659 64.9469 40.9703 64.9995C49.7746 64.9469 56.9002 54.9997 56.9002 54.9997C56.9002 54.9997 49.7746 45.0525 40.9703 44.9999Z",fill:"#FD4848"})]}),OtherWallets=({...et})=>{const o={position:"relative",display:"flex",flexDirection:"column",gap:2},tt={position:"relative",display:"flex",gap:2},rt={width:"50%",overflow:"hidden",borderRadius:"27.5%"};return jsxRuntimeExports.jsxs("div",{style:o,...et,children:[jsxRuntimeExports.jsxs("div",{style:tt,children:[jsxRuntimeExports.jsx("div",{style:rt,children:jsxRuntimeExports.jsx(WalletConnect,{background:!0})}),jsxRuntimeExports.jsx("div",{style:rt,children:isZerion()?jsxRuntimeExports.jsx(Phantom,{}):jsxRuntimeExports.jsx(Zerion,{})})]}),jsxRuntimeExports.jsxs("div",{style:tt,children:[jsxRuntimeExports.jsx("div",{style:rt,children:isFamily()?jsxRuntimeExports.jsx(ImToken,{}):jsxRuntimeExports.jsx(Family,{})}),jsxRuntimeExports.jsx("div",{style:rt,children:isRainbow()?jsxRuntimeExports.jsx(Trust,{}):jsxRuntimeExports.jsx(Rainbow,{})})]})]})},Fordefi=({...et})=>jsxRuntimeExports.jsxs("svg",{...et,width:"88",height:"88",viewBox:"0 0 96 96",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsxs("g",{clipPath:"url(#clip0_14298_75627)",children:[jsxRuntimeExports.jsx("path",{d:"M43.5075 62.5508H6V73.5954C6 79.2046 10.5379 83.7515 16.1357 83.7515H32.9997L43.5075 62.5508Z",fill:"#7994FF"}),jsxRuntimeExports.jsx("path",{d:"M6.00098 39.1016H76.2075L68.0567 55.4841H6.00098V39.1016Z",fill:"#486DFF"}),jsxRuntimeExports.jsx("path",{d:"M30.6398 12H6.09766V32.0282H89.8447V12H65.3025V26.9577H60.2423V12H35.7001V26.9577H30.6398V12Z",fill:"#5CD1FA"})]}),jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsx("clipPath",{id:"clip0_14298_75627",children:jsxRuntimeExports.jsx("rect",{width:"84",height:"72",fill:"white",transform:"translate(6 12)"})})})]});var Logos={Mock,Injected,OtherWallets,WalletConnect,MetaMask,Coinbase,Family,Trust,Argent,ImToken,Rainbow,Crypto,Ledger,Brave:Brave$1,Steak,Unstoppable,ONTO,Slope,Safe,Frontier,Zerion,Phantom,PlaceHolder,Frame,Dawn,InfinityWallet,Rabby,Fordefi,TokenPocket,Talisman};const truncateRegex=/^(0x[a-zA-Z0-9]{4})[a-zA-Z0-9]+([a-zA-Z0-9]{4})$/,truncateEthAddress=(et,o="••••")=>{if(!et)return"";const tt=et.match(truncateRegex);return tt?`${tt[1]}${o}${tt[2]}`:et},truncateENSAddress=(et,o)=>et.length>o?et.replace(".eth","").slice(0,o)+"...":et,nFormatter=(et,o=2)=>{if(et<1e4)return et.toFixed(2);const tt=[{value:1,symbol:""},{value:1e3,symbol:"k"},{value:1e6,symbol:"m"},{value:1e9,symbol:"g"},{value:1e12,symbol:"t"},{value:1e15,symbol:"p"},{value:1e18,symbol:"e"}],rt=/\.0+$|(\.[0-9]*[1-9])0+$/;var nt=tt.slice().reverse().find(function(ot){return et>=ot.value});return nt?(et/nt.value).toFixed(o).replace(rt,"$1")+nt.symbol:"0"},detectBrowser=()=>{var et;const o=detect();return(et=o==null?void 0:o.name)!==null&&et!==void 0?et:""},detectOS=()=>{var et;const o=detect();return(et=o==null?void 0:o.os)!==null&&et!==void 0?et:""},isIOS=()=>detectOS().toLowerCase().includes("ios"),isAndroid=()=>detectOS().toLowerCase().includes("android"),isMobile=()=>isAndroid()||isIOS();function flattenChildren(et){return React.Children.toArray(et).reduce((tt,rt)=>rt.type===React.Fragment?tt.concat(flattenChildren(rt.props.children)):(tt.push(rt),tt),[])}const isWalletConnectConnector=et=>et==="walletConnect",isCoinbaseWalletConnector=et=>et==="coinbaseWalletSDK",isSafeConnector=et=>et==="safe",isInjectedConnector=et=>et==="injected",walletConfigs={mock:{icon:jsxRuntimeExports.jsx(Logos.Mock,{})},argent:{name:"Argent",icon:jsxRuntimeExports.jsx(Logos.Argent,{}),downloadUrls:{download:"https://connect.family.co/v0/download/argent",android:"https://play.google.com/store/apps/details?id=im.argent.contractwalletclient",ios:"https://apps.apple.com/app/argent/id1358741926"},getWalletConnectDeeplink:et=>isAndroid()?et:`https://argent.link/app/wc?uri=${encodeURIComponent(et)}`},"coinbaseWallet, coinbaseWalletSDK":{name:"Coinbase Wallet",shortName:"Coinbase",icon:jsxRuntimeExports.jsx(Logos.Coinbase,{background:!0}),iconShape:"squircle",downloadUrls:{download:"https://connect.family.co/v0/download/coinbasewallet",website:"https://www.coinbase.com/wallet/getting-started-extension",android:"https://play.google.com/store/apps/details?id=org.toshi",ios:"https://apps.apple.com/app/coinbase-wallet-store-crypto/id1278383455",chrome:"https://chrome.google.com/webstore/detail/coinbase-wallet-extension/hnfanknocfeofbddgcijnmhnfnkdnaad"},getWalletConnectDeeplink:et=>`https://go.cb-w.com/wc?uri=${encodeURIComponent(et)}`},"com.coinbase.wallet":{name:"Coinbase Wallet",shortName:"Coinbase",icon:jsxRuntimeExports.jsx(Logos.Coinbase,{background:!0}),iconShape:"circle",downloadUrls:{download:"https://connect.family.co/v0/download/coinbasewallet",website:"https://www.coinbase.com/wallet/getting-started-extension",android:"https://play.google.com/store/apps/details?id=org.toshi",ios:"https://apps.apple.com/app/coinbase-wallet-store-crypto/id1278383455",chrome:"https://chrome.google.com/webstore/detail/coinbase-wallet-extension/hnfanknocfeofbddgcijnmhnfnkdnaad"},getWalletConnectDeeplink:et=>`https://go.cb-w.com/wc?uri=${encodeURIComponent(et)}`},"com.crypto.wallet":{name:"Crypto.com",shortName:"Crypto"},dawn:{name:"Dawn Wallet",shortName:"Dawn",downloadUrls:{download:"https://apps.apple.com/us/app/dawn-ethereum-wallet/id1673143782",website:"https://www.dawnwallet.xyz/",ios:"https://apps.apple.com/us/app/dawn-ethereum-wallet/id1673143782"}},"co.family.wallet":{name:"Family",shortName:"Family",icon:jsxRuntimeExports.jsx(Logos.Family,{}),iconShape:"squircle",downloadUrls:{download:"https://connect.family.co/v0/download/family",website:"https://family.co",ios:"https://family.co/download"},getWalletConnectDeeplink:et=>isAndroid()?et:`familywallet://wc?uri=${encodeURIComponent(et)}`},frame:{name:"Frame",icon:jsxRuntimeExports.jsx(Logos.Frame,{}),iconShouldShrink:!0,downloadUrls:{download:"https://connect.family.co/v0/download/frame",website:"https://frame.sh",chrome:"https://chrome.google.com/webstore/detail/frame-companion/ldcoohedfbjoobcadoglnnmmfbdlmmhf",firefox:"https://addons.mozilla.org/en-US/firefox/addon/frame-extension",brave:"https://chrome.google.com/webstore/detail/frame-companion/ldcoohedfbjoobcadoglnnmmfbdlmmhf"},getWalletConnectDeeplink:et=>et},frontier:{name:"Frontier Wallet",shortName:"Frontier",icon:jsxRuntimeExports.jsx(Logos.Frontier,{}),downloadUrls:{download:"https://connect.family.co/v0/download/frontier",ios:"https://apps.apple.com/app/frontier-crypto-defi-wallet/id1482380988",android:"https://play.google.com/store/apps/details?id=com.frontierwallet",website:"https://frontier.xyz/",chrome:"https://chrome.google.com/webstore/detail/frontier-wallet/kppfdiipphfccemcignhifpjkapfbihd"},getWalletConnectDeeplink:et=>isAndroid()?et:`frontier://wc?uri=${encodeURIComponent(et)}`},injected:{name:"Browser Wallet",shortName:"Browser",icon:jsxRuntimeExports.jsx(Logos.Injected,{})},"metaMask, metaMask-io, io.metamask, io.metamask.mobile, metaMaskSDK":{name:"MetaMask",icon:jsxRuntimeExports.jsx(Logos.MetaMask,{}),iconConnector:jsxRuntimeExports.jsx(Logos.MetaMask,{}),iconShouldShrink:!0,downloadUrls:{download:"https://connect.family.co/v0/download/metamask",website:"https://metamask.io/download/",android:"https://play.google.com/store/apps/details?id=io.metamask",ios:"https://apps.apple.com/app/metamask/id1438144202",chrome:"https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn",firefox:"https://addons.mozilla.org/firefox/addon/ether-metamask/",brave:"https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn",edge:"https://microsoftedge.microsoft.com/addons/detail/metamask/ejbalbakoplchlghecdalmeeeajnimhm"},getWalletConnectDeeplink:et=>isAndroid()?et:`https://metamask.app.link/wc?uri=${encodeURIComponent(et)}`},"app.phantom":{name:"Phantom",iconShape:"squircle"},"me.rainbow":{name:"Rainbow Wallet",shortName:"Rainbow",icon:jsxRuntimeExports.jsx(Logos.Rainbow,{}),iconShape:"squircle",downloadUrls:{download:"https://connect.family.co/v0/download/rainbow",website:"https://rainbow.me/?utm_source=connectkit",android:"https://play.google.com/store/apps/details?id=me.rainbow&referrer=utm_source%3Dconnectkit&utm_source=connectkit",ios:"https://apps.apple.com/app/rainbow-ethereum-wallet/id1457119021?pt=119997837&ct=connectkit&mt=8",chrome:"https://rainbow.me/extension?utm_source=connectkit",edge:"https://rainbow.me/extension?utm_source=connectkit",brave:"https://rainbow.me/extension?utm_source=connectkit"},getWalletConnectDeeplink:et=>isAndroid()?et:`https://rnbwapp.com/wc?uri=${encodeURIComponent(et)}&connector=connectkit`},"io.rabby":{name:"Rabby Wallet",shortName:"Rabby",downloadUrls:{website:"https://rabby.io",chrome:"https://chrome.google.com/webstore/detail/rabby-wallet/acmacodkjbdgmoleebolmdjonilkdbch"}},safe:{name:"Safe",icon:jsxRuntimeExports.jsx(Logos.Safe,{}),downloadUrls:{download:"https://connect.family.co/v0/download/safe",website:"https://safe.global/",ios:"https://apps.apple.com/app/id1515759131",android:"https://play.google.com/store/apps/details?id=io.gnosis.safe"},getWalletConnectDeeplink:et=>isAndroid()?et:`https://gnosis-safe.io/wc?uri=${encodeURIComponent(et)}`},"xyz.talisman":{name:"Talisman",shortName:"Talisman",iconShape:"squircle",downloadUrls:{download:"https://talisman.xyz/download",website:"https://talisman.xyz",chrome:"https://chrome.google.com/webstore/detail/talisman-polkadot-wallet/fijngjgcjhjmmpcmkeiomlglpeiijkld",firefox:"https://addons.mozilla.org/en-US/firefox/addon/talisman-wallet-extension/"}},"com.trustwallet.app":{name:"Trust Wallet",shortName:"Trust",icon:jsxRuntimeExports.jsx(Logos.Trust,{}),iconShouldShrink:!0,downloadUrls:{download:"https://connect.family.co/v0/download/trust",android:"https://play.google.com/store/apps/details?id=com.wallet.crypto.trustapp",ios:"https://apps.apple.com/app/trust-crypto-bitcoin-wallet/id1288339409"},getWalletConnectDeeplink(et){return isAndroid()?et:`https://link.trustwallet.com/wc?uri=${encodeURIComponent(et)}`}},infinityWallet:{name:"Infinity Wallet",icon:jsxRuntimeExports.jsx(Logos.InfinityWallet,{}),downloadUrls:{download:"https://connect.family.co/v0/download/infinityWallet",website:"https://infinitywallet.io/download",chrome:"https://infinitywallet.io/download",firefox:"https://infinitywallet.io/download",brave:"https://infinitywallet.io/download",edge:"https://infinitywallet.io/download"}},imToken:{name:"imToken",icon:jsxRuntimeExports.jsx(Logos.ImToken,{}),downloadUrls:{download:"https://connect.family.co/v0/download/imToken",android:"https://play.google.com/store/apps/details?id=im.token.app",ios:"https://itunes.apple.com/us/app/imtoken2/id1384798940"},getWalletConnectDeeplink:et=>`imtokenv2://wc?uri=${encodeURIComponent(et)}`},unstoppable:{name:"Unstoppable",icon:jsxRuntimeExports.jsx(Logos.Unstoppable,{}),downloadUrls:{download:"https://connect.family.co/v0/download/unstoppable",ios:"https://apps.apple.com/app/bank-bitcoin-wallet/id1447619907",android:"https://play.google.com/store/apps/details?id=io.horizontalsystems.bankwallet"},getWalletConnectDeeplink:et=>isAndroid()?et:`https://unstoppable.money/wc?uri=${encodeURIComponent(et)}`},onto:{name:"ONTO",icon:jsxRuntimeExports.jsx(Logos.ONTO,{}),downloadUrls:{download:"https://connect.family.co/v0/download/onto",ios:"https://apps.apple.com/app/onto-an-ontology-dapp/id1436009823",android:"https://play.google.com/store/apps/details?id=com.github.ontio.onto",website:"https://onto.app/en/download/"},getWalletConnectDeeplink:et=>isAndroid()?et:`https://onto.app/wc?uri=${encodeURIComponent(et)}`},steak:{name:"Steak",icon:jsxRuntimeExports.jsx(Logos.Steak,{}),downloadUrls:{download:"https://connect.family.co/v0/download/steak",android:"https://play.google.com/store/apps/details?id=fi.steakwallet.app",ios:"https://apps.apple.com/app/steakwallet/id1569375204",website:"https://steakwallet.fi/download"},getWalletConnectDeeplink:et=>isAndroid()?et:`https://links.steakwallet.fi/wc?uri=${encodeURIComponent(et)}`},ledger:{name:"Ledger Live",shortName:"Ledger",icon:jsxRuntimeExports.jsx(Logos.Ledger,{}),downloadUrls:{download:"https://connect.family.co/v0/download/ledger",website:"https://www.ledger.com/ledger-live/download#download-device-2",android:"https://play.google.com/store/apps/details?id=com.ledger.live",ios:"https://apps.apple.com/app/ledger-live-web3-wallet/id1361671700"},getWalletConnectDeeplink:et=>isAndroid()?et:`ledgerlive://wc?uri=${encodeURIComponent(et)}`,shouldDeeplinkDesktop:!0},zerion:{name:"Zerion",icon:jsxRuntimeExports.jsx(Logos.Zerion,{}),downloadUrls:{download:"https://connect.family.co/v0/download/zerion",ios:"https://apps.apple.com/app/apple-store/id1456732565",android:"https://play.google.com/store/apps/details?id=io.zerion.android",website:"https://zerion.io/"},getWalletConnectDeeplink:et=>isAndroid()?et:`https://app.zerion.io/wc?uri=${encodeURIComponent(et)}`},slope:{name:"Slope",icon:jsxRuntimeExports.jsx(Logos.Slope,{}),downloadUrls:{download:"https://connect.family.co/v0/download/slope",ios:"https://apps.apple.com/app/slope-wallet/id1574624530",android:"https://play.google.com/store/apps/details?id=com.wd.wallet",chrome:"https://chrome.google.com/webstore/detail/slope-wallet/pocmplpaccanhmnllbbkpgfliimjljgo",website:"https://slope.finance/"},getWalletConnectDeeplink:et=>isAndroid()?et:`https://slope.finance/app/wc?uri=${encodeURIComponent(et)}`},tokenPocket:{name:"TokenPocket Wallet",icon:jsxRuntimeExports.jsx(Logos.TokenPocket,{}),downloadUrls:{website:"https://www.tokenpocket.pro/en/download/app",download:"https://www.tokenpocket.pro/en/download/app",android:"https://play.google.com/store/apps/details?id=vip.mytokenpocket",ios:"https://apps.apple.com/us/app/tp-global-wallet/id6444625622",chrome:"https://chrome.google.com/webstore/detail/tokenpocket/mfgccjchihfkkindfppnaooecgfneiii"}},talisman:{name:"Talisman",icon:jsxRuntimeExports.jsx(Logos.Talisman,{}),downloadUrls:{download:"https://talisman.xyz/download",website:"https://talisman.xyz",chrome:"https://chrome.google.com/webstore/detail/talisman-polkadot-wallet/fijngjgcjhjmmpcmkeiomlglpeiijkld",firefox:"https://addons.mozilla.org/en-US/firefox/addon/talisman-wallet-extension/"}},walletConnect:{name:"Other Wallets",shortName:"Other",icon:jsxRuntimeExports.jsx(Logos.WalletConnect,{background:!0}),iconConnector:jsxRuntimeExports.jsx(Logos.OtherWallets,{}),iconShape:"square",getWalletConnectDeeplink:et=>et}};Object.keys(walletConfigs).reduce((et,o)=>{var tt,rt,nt,ot,it,st;const at=walletConfigs[o];if(!(at!=null&&at.getWalletConnectDeeplink))return et;const ct=o.split(",")[0].trim(),lt=(rt=(tt=at.name)===null||tt===void 0?void 0:tt.replace("Wallet","").replace(" ",""))!==null&&rt!==void 0?rt:ct[0].toUpperCase()+ct.slice(1),dt=injected({target:{id:ct,name:(ot=(nt=at.name)!==null&&nt!==void 0?nt:at.shortName)!==null&&ot!==void 0?ot:o,provider:mt=>{var ft;return(ft=mt==null?void 0:mt.ethereum)===null||ft===void 0?void 0:ft[`is${lt}`]}}}),ht=((st=(it=at.name)!==null&&it!==void 0?it:at.shortName)!==null&&st!==void 0?st:o).toLowerCase().replace(/(?:^|\s)\S/g,mt=>mt.toUpperCase()).replace(/\s/g,"").replace(/(?:^|\s)\S/g,mt=>mt.toLowerCase());return et[ht]=dt,et},{});const defaultLightTheme={font:{family:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, 'Apple Color Emoji', Arial, sans-serif, 'Segoe UI Emoji'"},text:{primary:{color:"#373737"},secondary:{color:"#999999",hover:{color:"#111111"}},error:"#FC6464",valid:"#32D74B"},buttons:{primary:{borderRadius:16,color:"#000373737000",background:"#FFFFFF",border:"#F0F0F0",hover:{color:"#000000",border:"#1A88F8"}},secondary:{borderRadius:16,background:"#F6F7F9",color:"#000000"}},navigation:{color:"#999999"},modal:{background:"#ffffff",divider:"#f7f6f8"},tooltips:{color:"#999999",background:"#ffffff",hover:{background:"#f6f7f9"}},overlay:{background:"rgba(0, 0, 0, 0.06)"},qrCode:{accentColor:"#F7F6F8"}},parseTheme=et=>et,userPrefersDarkMode=()=>typeof window>"u"?!1:window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;userPrefersDarkMode();const defaultTheme$1={connectKit:{options:{iconStyle:"light"},theme:{preferred:"dark",light:parseTheme(defaultLightTheme),dark:parseTheme(defaultLightTheme)}}};var styled=typeof qe.div=="function"?qe:qe.default;const hexToP3=et=>{const o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(et);if(o==null)return et;const tt={r:parseInt(o[1],16),g:parseInt(o[2],16),b:parseInt(o[3],16)};return`color(display-p3 ${tt.r/255} ${tt.g/255} ${tt.b/255})`};var base$m={light:{"--ck-connectbutton-font-size":"15px","--ck-connectbutton-color":"#373737","--ck-connectbutton-background":"#F6F7F9","--ck-connectbutton-background-secondary":"#FFFFFF","--ck-connectbutton-hover-color":"#373737","--ck-connectbutton-hover-background":"#F0F2F5","--ck-connectbutton-active-color":"#373737","--ck-connectbutton-active-background":"#EAECF1","--ck-connectbutton-balance-color":"#373737","--ck-connectbutton-balance-background":"#fff","--ck-connectbutton-balance-box-shadow":"inset 0 0 0 1px var(--ck-connectbutton-background)","--ck-connectbutton-balance-hover-background":"#F6F7F9","--ck-connectbutton-balance-hover-box-shadow":"inset 0 0 0 1px var(--ck-connectbutton-hover-background)","--ck-connectbutton-balance-active-background":"#F0F2F5","--ck-connectbutton-balance-active-box-shadow":"inset 0 0 0 1px var(--ck-connectbutton-active-background)","--ck-primary-button-border-radius":"16px","--ck-primary-button-color":"#373737","--ck-primary-button-background":"#F6F7F9","--ck-primary-button-font-weight":"600","--ck-primary-button-hover-color":"#373737","--ck-primary-button-hover-background":"#F0F2F5","--ck-secondary-button-border-radius":"16px","--ck-secondary-button-color":"#373737","--ck-secondary-button-background":"#F6F7F9","--ck-tertiary-button-background":"#FFFFFF","--ck-secondary-button-hover-background":"#e0e4eb","--ck-modal-box-shadow":"0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-overlay-background":"rgba(71, 88, 107, 0.24)","--ck-body-color":"#373737","--ck-body-color-muted":"#999999","--ck-body-color-muted-hover":"#111111","--ck-body-background":"#ffffff","--ck-body-background-transparent":"rgba(255,255,255,0)","--ck-body-background-secondary":"#f6f7f9","--ck-body-background-secondary-hover-background":"#e0e4eb","--ck-body-background-secondary-hover-outline":"#4282FF","--ck-body-background-tertiary":"#F3F4F7","--ck-body-action-color":"#999999","--ck-body-divider":"#f7f6f8","--ck-body-divider-secondary":"rgba(0, 0, 0, 0.06)","--ck-body-color-danger":"#FF4E4E","--ck-body-color-valid":"#32D74B","--ck-siwe-border":"#F0F0F0","--ck-body-disclaimer-color":"#AAAAAB","--ck-body-disclaimer-link-color":"#838485","--ck-body-disclaimer-link-hover-color":"#000000","--ck-tooltip-background":"#ffffff","--ck-tooltip-background-secondary":"#ffffff","--ck-tooltip-color":"#999999","--ck-tooltip-shadow":"0px 2px 10px rgba(0, 0, 0, 0.08)","--ck-dropdown-button-color":"#999999","--ck-dropdown-button-box-shadow":"0 0 0 1px rgba(0,0,0,0.01), 0px 0px 7px rgba(0, 0, 0, 0.05)","--ck-dropdown-button-background":"#fff","--ck-dropdown-button-hover-color":"#8B8B8B","--ck-dropdown-button-hover-background":"#F5F7F9","--ck-qr-dot-color":"#000000","--ck-qr-border-color":"#f7f6f8","--ck-focus-color":"#1A88F8","--ck-spinner-color":"var(--ck-focus-color)","--ck-copytoclipboard-stroke":"#CCCCCC"},dark:{"--ck-connectbutton-font-size":"15px","--ck-connectbutton-color":"#ffffff","--ck-connectbutton-background":"#383838","--ck-connectbutton-background-secondary":"#282828","--ck-connectbutton-hover-background":"#404040","--ck-connectbutton-active-background":"#4D4D4D","--ck-connectbutton-balance-color":"#fff","--ck-connectbutton-balance-background":"#282828","--ck-connectbutton-balance-box-shadow":"inset 0 0 0 1px var(--ck-connectbutton-background)","--ck-connectbutton-balance-hover-background":"#383838","--ck-connectbutton-balance-hover-box-shadow":"inset 0 0 0 1px var(--ck-connectbutton-hover-background)","--ck-connectbutton-balance-active-background":"#404040","--ck-connectbutton-balance-active-box-shadow":"inset 0 0 0 1px var(--ck-connectbutton-active-background)","--ck-primary-button-color":"#ffffff","--ck-primary-button-background":"#383838","--ck-primary-button-border-radius":"16px","--ck-primary-button-font-weight":"600","--ck-primary-button-hover-background":"#404040","--ck-primary-button-active-border-radius":"16px","--ck-secondary-button-color":"#ffffff","--ck-secondary-button-background":"#333333","--ck-secondary-button-hover-background":"#4D4D4D","--ck-tertiary-button-background":"#424242","--ck-focus-color":"#1A88F8","--ck-overlay-background":"rgba(0,0,0,0.4)","--ck-body-color":"#ffffff","--ck-body-color-muted":"rgba(255, 255, 255, 0.4)","--ck-body-color-muted-hover":"rgba(255, 255, 255, 0.8)","--ck-body-background":"#2B2B2B","--ck-body-background-transparent":"rgba(0,0,0,0)","--ck-body-background-secondary":"#333333","--ck-body-background-secondary-hover-background":"#4D4D4D","--ck-body-background-secondary-hover-outline":"#ffffff","--ck-body-background-tertiary":"#333333","--ck-body-action-color":"#808080","--ck-body-divider":"#383838","--ck-body-color-danger":"#FF4E4E","--ck-body-disclaimer-color":"#858585","--ck-body-disclaimer-link-color":"#ADADAD","--ck-body-disclaimer-link-hover-color":"#FFFFFF","--ck-modal-box-shadow":"0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-copytoclipboard-stroke":"#555555","--ck-tooltip-background":"#2B2B2B","--ck-tooltip-background-secondary":"#333333","--ck-tooltip-color":"#999999","--ck-tooltip-shadow":"0px 2px 10px rgba(0, 0, 0, 0.08)","--ck-dropdown-button-color":"#6C7381","--ck-spinner-color":"var(--ck-focus-color)","--ck-qr-dot-color":"#ffffff","--ck-qr-border-color":"#3d3d3d"}},web95={"--ck-font-family":"Lato","--ck-border-radius":"0px","--ck-connectbutton-color":"#373737","--ck-connectbutton-background":"linear-gradient(180deg, #F0F0EA 0%, #FFFFFF 50%, #F0F0EA 100%) 100% 100% / 200% 200%, #F5F5F1","--ck-connectbutton-box-shadow":" 0 0 0 1px #003C74, 2px 2px 0px rgba(255, 255, 255, 0.75), -2px -2px 0px rgba(0, 0, 0, 0.05), inset 0px 0px 0px 0px #97B9EC, inset -1px -2px 2px rgba(0, 0, 0, 0.2)","--ck-connectbutton-border-radius":"4.5px","--ck-connectbutton-hover-color":"#373737","--ck-connectbutton-hover-background":"linear-gradient(180deg, #F0F0EA 0%, #FFFFFF 50%, #F0F0EA 100%) 100% 0% / 200% 200%, #F5F5F1","--ck-connectbutton-active-background":"linear-gradient(180deg, #F0F0EA 0%, #FFFFFF 50%, #F0F0EA 100%) 100% 100% / 200% 200%, #F5F5F1","--ck-connectbutton-balance-color":"#373737","--ck-connectbutton-balance-background":"#fff","--ck-connectbutton-balance-box-shadow":"0 0 0 1px #E4E7E7","--ck-connectbutton-balance-hover-box-shadow":"0 0 0 1px #d7dbdb","--ck-connectbutton-balance-active-box-shadow":"0 0 0 1px #bbc0c0","--ck-focus-color":"#1A88F8","--ck-overlay-background":"rgba(0, 127, 128, 0.8)","--ck-body-color":"#373737","--ck-body-color-muted":"#808080","--ck-body-color-muted-hover":"#111111","--ck-body-background":"#F0EDE2","--ck-body-background-transparent":"rgba(255,255,255,0)","--ck-body-background-secondary-hover-background":"#FAFAFA","--ck-body-background-secondary-hover-outline":"#4282FF","--ck-body-action-color":"#373737","--ck-body-color-danger":"#FC6464","--ck-body-color-valid":"#32D74B","--ck-body-divider":"#919B9C","--ck-body-divider-box-shadow":"0px 1px 0px #FBFBF8","--ck-primary-button-background":"linear-gradient(180deg, #FFFFFF 0%, #F0F0EA 100%), #F5F5F1","--ck-primary-button-box-shadow":"inset 0 0 0 1px #003C74, 1px 1px 0px rgba(255, 255, 255, 0.75), -1px -1px 0px rgba(0, 0, 0, 0.05), inset 0px 0px 0px 0px #97B9EC, inset -1px -2px 2px rgba(0, 0, 0, 0.2)","--ck-primary-button-border-radius":"6px","--ck-primary-button-hover-box-shadow":"inset 0 0 0 1px #003C74, 1px 1px 0px rgba(255, 255, 255, 0.75), -1px -1px 0px rgba(0, 0, 0, 0.05), inset 0px 0px 0px 5px #97B9EC, inset -1px -2px 2px rgba(0, 0, 0, 0.2)","--ck-primary-button-hover-border-radius":"6px","--ck-modal-heading-font-weight":400,"--ck-modal-box-shadow":` + inset 0px -3px 0px #0F37A9, + inset -2px 0px 0px #0F37A9, + inset 0px -4px 0px #0D5DDF, + inset -4px 0px 0px #0D5DDF, + inset 2px 0px 0px #0453DD, + inset 0px 2px 0px #044FD1, + inset 4px 0px 0px #4283EB, + inset 0px 4px 0px #4283EB + `,"--ck-modal-h1-font-weight":400,"--ck-secondary-button-color":"#373737","--ck-secondary-button-border-radius":"6px","--ck-secondary-button-box-shadow":"inset 0 0 0 1px #003C74, 1px 1px 0px rgba(255, 255, 255, 0.75), -1px -1px 0px rgba(0, 0, 0, 0.05), inset 0px 0px 0px 0px #97B9EC, inset -1px -2px 2px rgba(0, 0, 0, 0.2)","--ck-secondary-button-background":"linear-gradient(180deg, #FFFFFF 0%, #F0F0EA 100%), #F5F5F1","--ck-secondary-button-hover-box-shadow":"inset 0 0 0 1px #003C74, 1px 1px 0px rgba(255, 255, 255, 0.75), -1px -1px 0px rgba(0, 0, 0, 0.05), inset 0px 0px 0px 4px #97B9EC, inset -1px -2px 2px rgba(0, 0, 0, 0.2)","--ck-body-background-secondary":"rgba(0, 0, 0, 0.1)","--ck-body-background-tertiary":"linear-gradient(180deg, #FBFBFB 0%, #EFEFEE 100%)","--ck-tertiary-border-radius":"0px","--ck-tertiary-box-shadow":"inset 0 0 0 1px #919B9C, 1px 1px 2px rgba(0, 0, 0, 0.15), inset -2px -2px 0px #FFFFFF","--ck-body-button-text-align":"left","--ck-body-button-box-shadow":"0 2px 4px rgba(0, 0, 0, 0.05 )","--ck-body-disclaimer-background":"linear-gradient(180deg, #FBFBFB 0%, #EFEFEE 100%)","--ck-body-disclaimer-box-shadow":` + inset 0px -3px 0px #0F37A9, + inset -2px 0px 0px #0F37A9, + inset 0px -4px 0px #0D5DDF, + inset -4px 0px 0px #0D5DDF, + inset 2px 0px 0px #0453DD, + inset 4px 0px 0px #4283EB, + inset 0 1px 0 0 #919B9C`,"--ck-body-disclaimer-font-size":"14px","--ck-body-disclaimer-color":"#959594","--ck-body-disclaimer-link-color":"#626262","--ck-body-disclaimer-link-hover-color":"#000000","--ck-qr-dot-color":"#000000","--ck-qr-border-color":"#919B9C","--ck-qr-border-radius":"0","--ck-qr-background":"#FFFFFF","--ck-copytoclipboard-stroke":"rgba(55, 55, 55, 0.4)","--ck-tooltip-background":"linear-gradient(270deg, #F7F3E6 7.69%, #F5F7DA 100%)","--ck-tooltip-background-secondary":"#f6f7f9","--ck-tooltip-color":"#000000","--ck-tooltip-shadow":" 0 0 0 1.5px #2b2622, 0px 2px 10px rgba(0, 0, 0, 0.08)","--ck-spinner-color":"var(--ck-focus-color)","--ck-dropdown-button-color":"#999999","--ck-dropdown-button-box-shadow":"0 0 0 1px #A0A0A0, 1px 1px 0px rgba(255, 255, 255, 0.75), -1px -1px 0px rgba(0, 0, 0, 0.05), inset -1px -2px 2px rgba(0, 0, 0, 0.2)","--ck-dropdown-button-background":"linear-gradient(180deg, #FFFFFF 0%, #F0F0EA 100%), #F5F5F1","--ck-dropdown-button-hover-background":"linear-gradient(0deg, #FFFFFF 0%, #F0F0EA 100%), #F5F5F1","--ck-dropdown-pending-color":"#ACA899","--ck-dropdown-active-color":"#FFFFFF","--ck-dropdown-active-static-color":"#ACA899","--ck-dropdown-active-background":"#3F69BF","--ck-dropdown-active-border-radius":"0","--ck-dropdown-active-inset":"-12px","--ck-dropdown-color":"#ACA899","--ck-dropdown-background":"#FFFFFF","--ck-dropdown-box-shadow":"inset 0 0 0 1px #ACA899, 2px 2px 7px rgba(0, 0, 0, 0.15)","--ck-dropdown-border-radius":"0","--ck-alert-color":"#ACA899","--ck-alert-background":"linear-gradient(180deg, #FBFBFB 0%, #EFEFEE 100%)","--ck-alert-box-shadow":"inset 0 0 0 1px #919B9C, 1px 1px 2px rgba(0, 0, 0, 0.15), inset -2px -2px 0px #FFFFFF","--ck-alert-border-radius":"0","--ck-recent-badge-border-radius":"32px","--ck-recent-badge-top-offset":"0px","--ck-graphic-primary-color":"#333333","--ck-graphic-primary-background":"#FFFFFF","--ck-graphic-compass-background":"#FFFFFF","--ck-siwe-border":"#919B9C"},retro={"--ck-font-family":'"SF Pro Rounded",ui-rounded,"Nunito",-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,"Apple Color Emoji",Arial,sans-serif,"Segoe UI Emoji","Segoe UI Symbol"',"--ck-border-radius":"8px","--ck-connectbutton-font-size":"17px","--ck-connectbutton-color":"#000000","--ck-connectbutton-background":"#ffffff","--ck-connectbutton-box-shadow":"-4px 4px 0px #000000, inset 0 0 0 2px #000000","--ck-connectbutton-border-radius":"8px","--ck-connectbutton-hover-background":"#F3EDE8","--ck-connectbutton-active-box-shadow":"0 0 0 0 #000000, inset 0 0 0 2px #000000","--ck-connectbutton-balance-color":"#000000","--ck-connectbutton-balance-background":"#F3EDE8","--ck-connectbutton-balance-box-shadow":"-4px 4px 0px #000000, inset 0 0 0 2px #000000","--ck-connectbutton-balance-hover-background":"#eee5dd","--ck-connectbutton-balance-connectbutton-box-shadow":"-4px 8px 0px -4px #000000, inset 0 0 0 2px #000000","--ck-connectbutton-balance-connectbutton-border-radius":"0px 8px 8px 0","--ck-primary-button-color":"#373737","--ck-primary-button-background":"#ffffff","--ck-primary-button-box-shadow":"inset 0 0 0 2px #000000, -4px 4px 0 0 #000000","--ck-primary-button-border-radius":"8px","--ck-primary-button-hover-background":"#F3EDE8","--ck-primary-button-hover-box-shadow":"inset 0 0 0 2px #000000, -0px 0px 0 0 #000000","--ck-secondary-button-border-radius":"8px","--ck-secondary-button-color":"#373737","--ck-secondary-button-background":"#ffffff","--ck-secondary-button-box-shadow":"-4px 4px 0 0 #000000, inset 0 0 0 2px #000000","--ck-secondary-button-hover-background":"#F3EDE8","--ck-secondary-button-hover-box-shadow":"0 0 0 0 #000000, inset 0 0 0 2px #000000","--ck-focus-color":"#3B99FC","--ck-overlay-background":"rgba(133, 120, 122, 0.8)","--ck-body-color":"#373737","--ck-body-color-muted":"rgba(0, 0, 0, 0.5)","--ck-body-color-muted-hover":"#000000","--ck-body-background":"#EBE1D8","--ck-body-background-transparent":"rgba(255,255,255,0)","--ck-body-background-secondary":"rgba(0,0,0,0.1)","--ck-body-background-secondary-hover-background":"#4D4D4D","--ck-body-background-secondary-hover-outline":"#373737","--ck-body-background-tertiary":"#ffffff","--ck-tertiary-border-radius":"8px","--ck-tertiary-box-shadow":"-4px 4px 0 0 #000000, inset 0 0 0 2px #000000","--ck-body-action-color":"#373737","--ck-body-divider":"#373737","--ck-body-color-danger":"#FF4E4E","--ck-body-disclaimer-background":"#E3D6C9","--ck-body-disclaimer-box-shadow":"-4px 4px 0 0 #000000, inset 2px 0 0 0 #000000, inset -2px 0 0 0 #000000, inset 0 -2px 0 0 #000000","--ck-body-disclaimer-font-weight":"500","--ck-body-disclaimer-color":"#888079","--ck-body-disclaimer-link-color":"#5B5650","--ck-body-disclaimer-link-hover-color":"#000000","--ck-modal-box-shadow":"-10px 10px 0px #000000, inset 0 0 0 2px #000000","--ck-copytoclipboard-stroke":"#555555","--ck-tooltip-border-radius":"8px","--ck-tooltip-color":"#373737","--ck-tooltip-background":"#ffffff","--ck-tooltip-background-secondary":"#EBE1D8","--ck-tooltip-shadow":"-6px 6px 0 0 #000000, 0 0 0 2px #000000","--ck-spinner-color":"#1A88F8","--ck-dropdown-button-color":"#000","--ck-dropdown-button-box-shadow":"-2px 2px 0 2px #000000, 0 0 0 2px #000000","--ck-dropdown-button-background":"#ffffff","--ck-dropdown-button-hover-background":"#F3EDE8","--ck-dropdown-button-hover-box-shadow":"-2px 2px 0 0 #000000, 0 0 0 2px #000000","--ck-dropdown-pending-color":"rgba(0, 0, 0, 0.5)","--ck-dropdown-active-color":"#FFFFFF","--ck-dropdown-active-static-color":"rgba(0, 0, 0, 0.5)","--ck-dropdown-active-background":"#3B99FC","--ck-dropdown-active-box-shadow":"inset 0 0 0 2px #000000","--ck-dropdown-active-border-radius":"8px","--ck-dropdown-color":"rgba(0, 0, 0, 0.5)","--ck-dropdown-background":"#FFFFFF","--ck-dropdown-box-shadow":"-4px 4px 0 0 #000000, inset 0 0 0 2px #000000","--ck-dropdown-border-radius":"8px","--ck-alert-color":"rgba(0, 0, 0, 0.5)","--ck-alert-background":" #F5F5F5","--ck-alert-border-radius":"8px","--ck-qr-border-radius":"8px","--ck-qr-dot-color":"#000000","--ck-qr-border-color":"#000000","--ck-qr-background":"#ffffff","--ck-recent-badge-border-radius":"32px","--ck-recent-badge-box-shadow":"inset 0 0 0 2px currentColor","--ck-graphic-primary-color":"#000000","--ck-graphic-primary-background":"#ffffff","--ck-graphic-compass-background":"#FFFFFF","--ck-siwe-border":"#8E8985"},soft={"--ck-border-radius":"12px","--ck-connectbutton-font-size":"17px","--ck-connectbutton-border-radius":"12px","--ck-connectbutton-color":"#414451","--ck-connectbutton-background":"#ffffff","--ck-connectbutton-box-shadow":"inset 0 0 0 1px #E9EAEC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-connectbutton-hover-background":"#F6F7F9","--ck-connectbutton-hover-box-shadow":"inset 0 0 0 1px #E9EAEC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-connectbutton-balance-color":"#373737","--ck-connectbutton-balance-background":"#F6F7F9","--ck-connectbutton-balance-box-shadow":"none","--ck-connectbutton-balance-hover-background":"#f1f1f3","--ck-primary-button-border-radius":"12px","--ck-primary-button-color":"#414451","--ck-primary-button-background":"#ffffff","--ck-primary-button-box-shadow":"0 0 0 1px #E9EAEC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-primary-button-hover-background":"#F6F7F9","--ck-primary-button-hover-box-shadow":"0 0 0 1px #D9DBDD, 0px 0 0 rgba(0, 0, 0, 0.02)","--ck-secondary-button-border-radius":"12px","--ck-secondary-button-color":"#414451","--ck-secondary-button-background":"#ffffff","--ck-secondary-button-box-shadow":"0 0 0 1px #E9EAEC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-secondary-button-hover-background":"#F6F7F9","--ck-secondary-button-hover-box-shadow":"0 0 0 1px #D9DBDD, 0px 0 0 rgba(0, 0, 0, 0.02)","--ck-focus-color":"#1A88F8","--ck-modal-box-shadow":"0px 3px 16px rgba(0, 0, 0, 0.08)","--ck-body-color":"#414451","--ck-body-color-muted":"#9196A1","--ck-body-color-muted-hover":"#000000","--ck-body-background":"#ffffff","--ck-body-background-transparent":"rgba(255,255,255,0)","--ck-body-background-secondary":"#f6f7f9","--ck-body-background-secondary-hover-background":"#e0e4eb","--ck-body-background-secondary-hover-outline":"#4282FF","--ck-body-background-tertiary":"#F6F8FA","--ck-tertiary-border-radius":"13px","--ck-tertiary-box-shadow":"inset 0 0 0 1px rgba(0, 0, 0, 0.04)","--ck-body-action-color":"#999999","--ck-body-divider":"#f7f6f8","--ck-body-color-danger":"#FF4E4E","--ck-body-color-valid":"#32D74B","--ck-body-disclaimer-background":"#F9FAFA","--ck-body-disclaimer-color":"#AFB1B6","--ck-body-disclaimer-link-color":"#787B84","--ck-body-disclaimer-link-hover-color":"#000000","--ck-copytoclipboard-stroke":"#CCCCCC","--ck-tooltip-background":"#ffffff","--ck-tooltip-background-secondary":"#ffffff","--ck-tooltip-color":"#999999","--ck-tooltip-shadow":"0px 2px 10px rgba(0, 0, 0, 0.08)","--ck-spinner-color":"var(--ck-focus-color)","--ck-dropdown-button-color":"#999999","--ck-dropdown-button-box-shadow":"0 0 0 1px rgba(0, 0, 0, 0.01), 0px 0px 7px rgba(0, 0, 0, 0.05)","--ck-dropdown-button-background":"#fff","--ck-dropdown-button-hover-color":"#8B8B8B","--ck-dropdown-button-hover-background":"#E7E7E7","--ck-dropdown-color":"rgba(55, 55, 55, 0.4)","--ck-dropdown-box-shadow":"0px 2px 15px rgba(0, 0, 0, 0.15)","--ck-alert-color":"#9196A1","--ck-alert-background":"#F6F8FA","--ck-alert-box-shadow":"inset 0 0 0 1px rgba(0, 0, 0, 0.04)","--ck-alert-border-radius":"8px","--ck-qr-border-radius":"12px","--ck-qr-dot-color":"#2E3138","--ck-qr-border-color":"#E9EAEC","--ck-siwe-border":"#EAEBED"},midnight={"--ck-font-family":'"Inter",-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,"Apple Color Emoji",Arial,sans-serif,"Segoe UI Emoji","Segoe UI Symbol"',"--ck-border-radius":"10px","--ck-connectbutton-font-size":"17px","--ck-connectbutton-border-radius":"8px","--ck-connectbutton-color":"#ffffff","--ck-connectbutton-background":"#313235","--ck-connectbutton-box-shadow":"inset 0 0 0 1px rgba(255, 255, 255, 0.05)","--ck-connectbutton-hover-background":"#414144","--ck-connectbutton-active-background":"#4C4D4F","--ck-connectbutton-balance-color":"#ffffff","--ck-connectbutton-balance-background":"#1F2023","--ck-connectbutton-balance-box-shadow":"inset 0 0 0 1px #313235","--ck-connectbutton-balance-hover-background":"#313235","--ck-connectbutton-balance-active-background":"#414144","--ck-primary-button-border-radius":"8px","--ck-primary-button-color":"#ffffff","--ck-primary-button-background":"rgba(255, 255, 255, 0.08)","--ck-primary-button-box-shadow":"inset 0 0 0 1px rgba(255, 255, 255, 0.05)","--ck-primary-button-hover-background":"rgba(255, 255, 255, 0.2)","--ck-secondary-button-border-radius":"8px","--ck-secondary-button-color":"#ffffff","--ck-secondary-button-background":"#363638","--ck-secondary-button-box-shadow":"inset 0 0 0 1px rgba(255, 255, 255, 0.05)","--ck-secondary-button-hover-background":"#3c3c3e","--ck-overlay-background":"rgba(0,0,0,0.4)","--ck-modal-box-shadow":"inset 0 0 0 1px #38393C, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-focus-color":"#1A88F8","--ck-body-color":"#ffffff","--ck-body-color-muted":"#8B8F97","--ck-body-color-muted-hover":"#ffffff","--ck-body-background":"#1F2023","--ck-body-background-transparent":"rgba(31, 32, 35, 0)","--ck-body-background-secondary":"#313235","--ck-body-background-secondary-hover-background":"#e0e4eb","--ck-body-background-secondary-hover-outline":"rgba(255, 255, 255, 0.02)","--ck-body-background-tertiary":"#313235","--ck-tertiary-border-radius":"12px","--ck-tertiary-box-shadow":"inset 0 0 0 1px rgba(255, 255, 255, 0.02)","--ck-body-action-color":"#8B8F97","--ck-body-divider":"rgba(255,255,255,0.1)","--ck-body-color-danger":"#FF4E4E","--ck-body-color-valid":"#32D74B","--ck-body-disclaimer-background":"#2B2D31","--ck-body-disclaimer-box-shadow":"none","--ck-body-disclaimer-color":"#808183","--ck-body-disclaimer-link-color":"#AAABAD","--ck-body-disclaimer-link-hover-color":"#ffffff","--ck-copytoclipboard-stroke":"#CCCCCC","--ck-tooltip-background":"#1F2023","--ck-tooltip-background-secondary":"#1F2023","--ck-tooltip-color":"#ffffff","--ck-tooltip-shadow":" 0 0 0 1px rgba(255, 255, 255, 0.1), 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-spinner-color":"var(--ck-focus-color)","--ck-dropdown-button-color":"#6C7381","--ck-dropdown-button-box-shadow":"inset 0 0 0 1px rgba(255, 255, 255, 0.05)","--ck-dropdown-button-background":"#313235","--ck-dropdown-pending-color":"#8B8F97","--ck-dropdown-active-color":"#FFF","--ck-dropdown-active-static-color":"#FFF","--ck-dropdown-active-background":"rgba(255, 255, 255, 0.07)","--ck-dropdown-color":"#8B8F97","--ck-dropdown-background":"#313235","--ck-dropdown-box-shadow":"inset 0 0 0 1px rgba(255, 255, 255, 0.03)","--ck-dropdown-border-radius":"8px","--ck-alert-color":"#8B8F97","--ck-alert-background":"#404145","--ck-alert-box-shadow":"inset 0 0 0 1px rgba(255, 255, 255, 0.02)","--ck-qr-border-radius":"12px","--ck-qr-dot-color":"#ffffff","--ck-qr-border-color":"rgba(255,255,255,0.1)","--ck-recent-badge-border-radius":"32px"},minimal$1={"--ck-font-family":'"Inter",-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,"Apple Color Emoji",Arial,sans-serif,"Segoe UI Emoji","Segoe UI Symbol"',"--ck-border-radius":"0px","--ck-connectbutton-font-size":"17px","--ck-connectbutton-border-radius":"0px","--ck-connectbutton-color":"#414451","--ck-connectbutton-background":"#ffffff","--ck-connectbutton-box-shadow":"inset 0 0 0 1px #EBEBEB","--ck-connectbutton-hover-color":"#111","--ck-connectbutton-hover-box-shadow":"inset 0 0 0 1px #111","--ck-connectbutton-balance-color":"#111111","--ck-connectbutton-balance-background":"#F7F7F7","--ck-connectbutton-balance-box-shadow":"inset 0 0 0 1px #F7F7F7","--ck-connectbutton-balance-hover-background":"#f1f1f3","--ck-connectbutton-balance-hover-box-shadow":"inset 0 0 0 1px #111","--ck-primary-button-border-radius":"0px","--ck-primary-button-color":"#111111","--ck-primary-button-background":"#ffffff","--ck-primary-button-box-shadow":"inset 0 0 0 1px #EBEBEB","--ck-primary-button-hover-box-shadow":"inset 0 0 0 1px #111111","--ck-secondary-button-border-radius":"0px","--ck-secondary-button-color":"#111111","--ck-secondary-button-background":"#ffffff","--ck-secondary-button-box-shadow":"inset 0 0 0 1px #EBEBEB","--ck-secondary-button-hover-box-shadow":"inset 0 0 0 1px #111111","--ck-dropdown-button-color":"#999999","--ck-dropdown-button-box-shadow":"0 0 0 1px rgba(0, 0, 0, 0.01), 0px 0px 7px rgba(0, 0, 0, 0.05)","--ck-dropdown-button-background":"#fff","--ck-dropdown-button-hover-color":"#8B8B8B","--ck-dropdown-button-hover-background":"#E7E7E7","--ck-focus-color":"#1A88F8","--ck-modal-box-shadow":"0px 3px 16px rgba(0, 0, 0, 0.08)","--ck-body-color":"#111111","--ck-body-color-muted":"#A0A0A0","--ck-body-color-muted-hover":"#000000","--ck-body-background":"#ffffff","--ck-body-background-transparent":"rgba(255,255,255,0)","--ck-body-background-secondary":"#f6f7f9","--ck-body-background-secondary-hover-background":"#e0e4eb","--ck-body-background-secondary-hover-outline":"#4282FF","--ck-body-background-tertiary":"#ffffff","--ck-tertiary-border-radius":"0px","--ck-tertiary-box-shadow":"inset 0 0 0 1px rgba(0, 0, 0, 0.04)","--ck-body-action-color":"#A0A0A0","--ck-body-divider":"#EBEBEB","--ck-body-color-danger":"#FF4E4E","--ck-body-color-valid":"#32D74B","--ck-body-disclaimer-background":"#FAFAFA","--ck-body-disclaimer-box-shadow":"inset 0 1px 0 0 #ECECEC","--ck-body-disclaimer-color":"#9D9D9D","--ck-body-disclaimer-link-color":"#6E6E6E","--ck-body-disclaimer-link-hover-color":"#000000","--ck-copytoclipboard-stroke":"#CCCCCC","--ck-tooltip-border-radius":"0px","--ck-tooltip-background":"#ffffff","--ck-tooltip-background-secondary":"#ffffff","--ck-tooltip-color":"#999999","--ck-tooltip-shadow":"0px 2px 10px rgba(0, 0, 0, 0.08)","--ck-spinner-color":"var(--ck-focus-color)","--ck-dropdown-active-border-radius":"0","--ck-dropdown-box-shadow":"0px 2px 15px rgba(0, 0, 0, 0.15)","--ck-dropdown-border-radius":"0","--ck-alert-color":"rgba(17, 17, 17, 0.4)","--ck-alert-background":"#fff","--ck-alert-box-shadow":"inset 0 0 0 1px #EBEBEB","--ck-alert-border-radius":"0","--ck-qr-border-radius":"0px","--ck-qr-dot-color":"#111111","--ck-qr-border-color":"#EBEBEB","--ck-modal-h1-font-weight":"400","--ck-modal-heading-font-weight":"400","--ck-primary-button-font-weight":"400","--ck-recent-badge-top-offset":"0px","--ck-siwe-border":"#EBEBEB"},rounded={"--ck-font-family":'"Nunito",ui-rounded,-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,"Apple Color Emoji",Arial,sans-serif,"Segoe UI Emoji","Segoe UI Symbol"',"--ck-border-radius":"24px","--ck-connectbutton-font-size":"17px","--ck-connectbutton-font-weight":"700","--ck-connectbutton-border-radius":"14px","--ck-connectbutton-color":"#000000","--ck-connectbutton-background":"#ffffff","--ck-connectbutton-box-shadow":"inset 0 0 0 2px #DFE4EC, 0 2px 0 0 #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-connectbutton-hover-background":"#F9FAFB","--ck-connectbutton-balance-color":"#414451","--ck-connectbutton-balance-background":"#F9FAFB","--ck-connectbutton-balance-box-shadow":"0 2px 0 0 #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-connectbutton-balance-hover-background":"#F5F7F9","--ck-connectbutton-balance-hover-box-shadow":"0 2px 0 0 #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-connectbutton-balance-active-box-shadow":"0 0 0 0 #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-connectbutton-active-background":"#F5F7F9","--ck-connectbutton-active-box-shadow":"inset 0 0 0 2px #CFD7E2, 0 0px 0 0 #CFD7E2, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-primary-button-border-radius":"18px","--ck-primary-button-color":"#000000","--ck-primary-button-background":"#ffffff","--ck-primary-button-box-shadow":"inset 0 0 0 2px #DFE4EC, inset 0 -4px 0 0 #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-primary-button-hover-background":"#F5F7F9","--ck-primary-button-hover-box-shadow":"inset 0 0 0 2px #DFE4EC, inset 0 -2px 0 0 #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-secondary-button-border-radius":"16px","--ck-secondary-button-color":"#000000","--ck-secondary-button-background":"#ffffff","--ck-secondary-button-box-shadow":"inset 0 0 0 2px #DFE4EC, inset 0 -4px 0 0 #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-secondary-button-hover-background":"#F5F7F9","--ck-secondary-button-hover-box-shadow":"inset 0 0 0 2px #DFE4EC, inset 0 -2px 0 0 #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-focus-color":"#1A88F8","--ck-modal-box-shadow":"0px 3px 16px rgba(0, 0, 0, 0.08)","--ck-body-color":"#000000","--ck-body-color-muted":"#93989F","--ck-body-color-muted-hover":"#000000","--ck-body-background":"#ffffff","--ck-body-background-transparent":"rgba(255,255,255,0)","--ck-body-background-secondary":"#f6f7f9","--ck-body-background-secondary-hover-background":"#e0e4eb","--ck-body-background-secondary-hover-outline":"#4282FF","--ck-body-background-tertiary":"#ffffff","--ck-tertiary-border-radius":"22px","--ck-tertiary-box-shadow":"inset 0 0 0 2px #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-body-action-color":"#93989F","--ck-body-divider":"#DFE4EC","--ck-body-color-danger":"#FF4E4E","--ck-body-color-valid":"#32D74B","--ck-body-disclaimer-background":"#F9FAFB","--ck-body-disclaimer-font-size":"14px","--ck-body-disclaimer-font-weight":"700","--ck-body-disclaimer-color":"#959697","--ck-body-disclaimer-link-color":"#646464","--ck-body-disclaimer-link-hover-color":"#000000","--ck-copytoclipboard-stroke":"#CCCCCC","--ck-tooltip-background":"#ffffff","--ck-tooltip-background-secondary":"#ffffff","--ck-tooltip-color":"#999999","--ck-tooltip-shadow":" 0 0 0 2px #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-spinner-color":"var(--ck-focus-color)","--ck-dropdown-button-color":"#999999","--ck-dropdown-button-box-shadow":"0 0 0 2px #DFE4EC, 0 2px 0 2px #DFE4EC, 0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-dropdown-button-background":"#fff","--ck-dropdown-button-hover-color":"#8B8B8B","--ck-dropdown-button-hover-background":"#F5F7F9","--ck-dropdown-pending-color":"#848D9A","--ck-dropdown-active-color":"#000000","--ck-dropdown-active-static-color":"#848D9A","--ck-dropdown-active-background":"#F5F7F9","--ck-dropdown-color":"#848D9A","--ck-dropdown-background":"#FFFFFF","--ck-dropdown-box-shadow":"0px 2px 15px rgba(0, 0, 0, 0.15)","--ck-dropdown-border-radius":"16px","--ck-alert-color":"#848D9A","--ck-alert-background":"#F5F7F9","--ck-qr-border-radius":"24px","--ck-qr-dot-color":"#111111","--ck-qr-border-color":"#DFE4EC","--ck-modal-h1-font-weight":"700","--ck-modal-heading-font-weight":"700","--ck-primary-button-font-weight":"700","--ck-recent-badge-box-shadow":"inset 0 0 0 2px currentColor","--ck-recent-badge-top-offset":"0px","--ck-siwe-border":"#DFE4EC"},nouns={"--ck-font-family":'"PT Root UI",ui-rounded,"Nunito",-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,"Apple Color Emoji",Arial,sans-serif,"Segoe UI Emoji","Segoe UI Symbol"',"--ck-border-radius":"24px","--ck-connectbutton-font-size":"16px","--ck-connectbutton-font-weight":"700","--ck-connectbutton-border-radius":"10px","--ck-connectbutton-color":"#151C3B","--ck-connectbutton-background":"#ffffff","--ck-connectbutton-box-shadow":"inset 0 0 0 1px #D6D8E1","--ck-connectbutton-hover-background":"#E9EBF3","--ck-connectbutton-hover-box-shadow":"inset 0 0 0 1px #D4D8E8","--ck-connectbutton-active-background":"#D4D8E8","--ck-connectbutton-active-box-shadow":"inset 0 0 0 1px #D4D8E8","--ck-connectbutton-balance-color":"#373737","--ck-connectbutton-balance-background":"#F6F7F9","--ck-connectbutton-balance-box-shadow":"none","--ck-connectbutton-balance-hover-background":"#f1f1f3","--ck-primary-button-border-radius":"16px","--ck-primary-button-color":"#151C3B","--ck-primary-button-background":"#ffffff","--ck-primary-button-font-weight":"700","--ck-primary-button-hover-background":"#DEE1ED","--ck-secondary-button-border-radius":"16px","--ck-secondary-button-color":"#151C3B","--ck-secondary-button-background":"#ffffff","--ck-secondary-button-font-weight":"700","--ck-secondary-button-hover-background":"#DEE1ED","--ck-focus-color":"#1A88F8","--ck-modal-box-shadow":"0px 2px 4px rgba(0, 0, 0, 0.02)","--ck-overlay-background":"rgba(213, 215, 225, 0.8)","--ck-overlay-backdrop-filter":"blur(6px)","--ck-body-color":"#151C3B","--ck-body-color-muted":"#757A8E","--ck-body-color-muted-hover":"#000000","--ck-body-background":"#F4F4F8","--ck-body-background-transparent":"rgba(255,255,255,0)","--ck-body-background-secondary":"#E9E9F1","--ck-body-background-secondary-hover-background":"#e0e4eb","--ck-body-background-tertiary":"#E9E9F1","--ck-tertiary-border-radius":"24px","--ck-body-action-color":"#79809C","--ck-body-divider":"#D9DBE3","--ck-body-color-danger":"#FF4E4E","--ck-body-color-valid":"#32D74B","--ck-body-disclaimer-background":"#F9FAFA","--ck-body-disclaimer-color":"#AFB1B6","--ck-body-disclaimer-link-color":"#787B84","--ck-body-disclaimer-link-hover-color":"#000000","--ck-copytoclipboard-stroke":"#79809C","--ck-tooltip-background":"#ffffff","--ck-tooltip-background-secondary":"#ffffff","--ck-tooltip-color":"#999999","--ck-tooltip-shadow":"0px 2px 10px rgba(0, 0, 0, 0.08)","--ck-spinner-color":"var(--ck-focus-color)","--ck-dropdown-button-color":"#999999","--ck-dropdown-button-box-shadow":"0 0 0 1px rgba(0, 0, 0, 0.01), 0px 0px 7px rgba(0, 0, 0, 0.05)","--ck-dropdown-button-background":"#fff","--ck-dropdown-button-hover-color":"#8B8B8B","--ck-dropdown-button-hover-background":"#DEE1ED","--ck-dropdown-button-hover-box-shadow":"0px 0px 7px rgba(0, 0, 0, 0.05)","--ck-dropdown-color":"#757A8E","--ck-dropdown-box-shadow":"0 0 0 1px rgba(0, 0, 0, 0.01), 0px 0px 7px rgba(0, 0, 0, 0.05)","--ck-alert-color":"#9196A1","--ck-alert-background":"#F6F8FA","--ck-alert-box-shadow":"inset 0 0 0 1px rgba(0, 0, 0, 0.04)","--ck-alert-border-radius":"8px","--ck-qr-border-radius":"24px","--ck-qr-dot-color":"#000000","--ck-qr-background":"#ffffff","--ck-recent-badge-color":"#79809C","--ck-recent-badge-background":"#F4F4F8","--ck-recent-badge-box-shadow":"none","--ck-siwe-border":"#DFE4EC","--ck-graphic-primary-background":"#fff","--ck-graphic-compass-background":"#fff","--ck-graphic-primary-box-shadow":"0px 2.94737px 14.7368px rgba(0, 0, 0, 0.1)","--ck-graphic-compass-box-shadow":"0px 2px 9px rgba(0, 0, 0, 0.15)"},predefinedThemes={base:base$m,web95,retro,soft,midnight,minimal:minimal$1,rounded,nouns};const themeGlobals={default:{"--ck-font-family":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, + 'Apple Color Emoji', Arial, sans-serif, 'Segoe UI Emoji', + 'Segoe UI Symbol'`,"--ck-border-radius":"20px","--ck-secondary-button-border-radius":"16px"},graphics:{light:{"--ck-graphic-wave-stop-01":"#E8F17D","--ck-graphic-wave-stop-02":"#A8ECDE","--ck-graphic-wave-stop-03":"#7AA1F2","--ck-graphic-wave-stop-04":"#DEA1E8","--ck-graphic-wave-stop-05":"#F46D98","--ck-graphic-scaniconwithlogos-01":"#4E4E4E","--ck-graphic-scaniconwithlogos-02":"#272727","--ck-graphic-scaniconwithlogos-03":"#F8D74A","--ck-graphic-scaniconwithlogos-04":"#F6F7F9","--ck-chain-ethereum-01":"#25292E","--ck-chain-ethereum-02":"#fff","--ck-chain-ethereum-03":"#DFE0E0"},dark:{"--ck-graphic-wave-stop-01":"#E8F17D","--ck-graphic-wave-stop-02":"#A8ECDE","--ck-graphic-wave-stop-03":"#7AA1F2","--ck-graphic-wave-stop-04":"#DEA1E8","--ck-graphic-wave-stop-05":"#F46D98","--ck-graphic-scaniconwithlogos-01":"#AFAFAF","--ck-graphic-scaniconwithlogos-02":"#696969","--ck-graphic-scaniconwithlogos-03":"#F8D74A","--ck-graphic-scaniconwithlogos-04":"#3D3D3D"}},ens:{light:{"--ck-ens-01-start":"#FF3B30","--ck-ens-01-stop":"#FF9500","--ck-ens-02-start":"#FF9500","--ck-ens-02-stop":"#FFCC00","--ck-ens-03-start":"#FFCC00","--ck-ens-03-stop":"#34C759","--ck-ens-04-start":"#5856D6","--ck-ens-04-stop":"#AF52DE","--ck-ens-05-start":"#5AC8FA","--ck-ens-05-stop":"#007AFF","--ck-ens-06-start":"#007AFF","--ck-ens-06-stop":"#5856D6","--ck-ens-07-start":"#5856D6","--ck-ens-07-stop":"#AF52DE","--ck-ens-08-start":"#AF52DE","--ck-ens-08-stop":"#FF2D55"},dark:{"--ck-ens-01-start":"#FF453A","--ck-ens-01-stop":"#FF9F0A","--ck-ens-02-start":"#FF9F0A","--ck-ens-02-stop":"#FFD60A","--ck-ens-03-start":"#FFD60A","--ck-ens-03-stop":"#32D74B","--ck-ens-04-start":"#32D74B","--ck-ens-04-stop":"#64D2FF","--ck-ens-05-start":"#64D2FF","--ck-ens-05-stop":"#0A84FF","--ck-ens-06-start":"#0A84FF","--ck-ens-06-stop":"#5E5CE6","--ck-ens-07-start":"#5E5CE6","--ck-ens-07-stop":"#BF5AF2","--ck-ens-08-start":"#BF5AF2","--ck-ens-08-stop":"#FF2D55"}},brand:{"--ck-family-brand":"#1A88F8","--ck-brand-walletConnect":"#3B99FC","--ck-brand-coinbaseWallet":"#0052FF","--ck-brand-metamask":"#f6851b","--ck-brand-metamask-01":"#F6851B","--ck-brand-metamask-02":"#E2761B","--ck-brand-metamask-03":"#CD6116","--ck-brand-metamask-04":"#161616","--ck-brand-metamask-05":"#763D16","--ck-brand-metamask-06":"#D7C1B3","--ck-brand-metamask-07":"#C0AD9E","--ck-brand-metamask-08":"#E4761B","--ck-brand-metamask-09":"#233447","--ck-brand-metamask-10":"#E4751F","--ck-brand-metamask-11":"#FEF5E7","--ck-brand-metamask-12":"#E3C8AB","--ck-brand-trust-01":"#3375BB","--ck-brand-trust-02":"#ffffff","--ck-brand-trust-01b":"#ffffff","--ck-brand-trust-02b":"#3375BB","--ck-brand-argent":"#f36a3d","--ck-brand-imtoken-01":"#11C4D1","--ck-brand-imtoken-02":"#0062AD","--ck-brand-safe":"#12FF80","--ck-brand-dawn":"#000000"}},themeColors={light:predefinedThemes.base.light,dark:predefinedThemes.base.dark,web95:predefinedThemes.web95,retro:predefinedThemes.retro,soft:predefinedThemes.soft,midnight:predefinedThemes.midnight,minimal:predefinedThemes.minimal,rounded:predefinedThemes.rounded,nouns:predefinedThemes.nouns},createCssVars=(et,o)=>Ae` + ${Object.keys(et).map(tt=>{const rt=et[tt];return rt&&`${tt}:${rt};`})} + `,createCssColors=(et,o)=>{const tt=o?" !important":"";return Ae` + ${Object.keys(et).map(rt=>{const nt=et[rt];return nt&&`${rt}:${nt}${tt};`})} + @supports (color: color(display-p3 1 1 1)) { + ${Object.keys(et).map(rt=>{const nt=et[rt];return`${rt}:${hexToP3(nt)}${tt};`})} + } + `},themes={default:createCssVars(themeGlobals.default),light:createCssColors(themeColors.light),dark:createCssColors(themeColors.dark),web95:createCssColors(themeColors.web95),retro:createCssColors(themeColors.retro),soft:createCssColors(themeColors.soft),midnight:createCssColors(themeColors.midnight),minimal:createCssColors(themeColors.minimal),rounded:createCssColors(themeColors.rounded),nouns:createCssColors(themeColors.nouns)},globals={brand:createCssVars(themeGlobals.brand),ensLight:createCssVars(themeGlobals.ens.light),ensDark:createCssVars(themeGlobals.ens.dark),graphicsLight:createCssVars(themeGlobals.graphics.light),graphicsDark:createCssVars(themeGlobals.graphics.dark)},globalsLight=Ae` + ${globals.brand} + ${globals.ensLight} + ${globals.graphicsLight} +`,globalsDark=Ae` + ${globals.brand} + ${globals.ensDark} + ${globals.graphicsDark} +`;let mode="auto";const ResetContainer=styled(motion.div)` + ${themes.default} + + ${et=>{switch(et.$useTheme){case"web95":return mode="light",themes.web95;case"retro":return mode="light",themes.retro;case"soft":return mode="light",themes.soft;case"midnight":return mode="dark",themes.midnight;case"minimal":return mode="light",themes.minimal;case"rounded":return mode="light",themes.rounded;case"nouns":return mode="light",themes.nouns;default:return et.$useMode==="light"?(mode="light",themes.light):et.$useMode==="dark"?(mode="dark",themes.dark):Ae` + @media (prefers-color-scheme: light) { + ${themes.light} + } + @media (prefers-color-scheme: dark) { + ${themes.dark} + } + `}}} + + ${et=>{switch(mode){case"light":return globalsLight;case"dark":return globalsDark;default:return Ae` + ${globalsLight} + @media (prefers-color-scheme: dark) { + ${globalsDark} + } + `}}} + + + ${et=>{var o;if(et.$customTheme&&et.$customTheme["--ck-accent-color"]&&["light","dark","auto","",void 0].includes(et.$useTheme)){const tt=et.$customTheme["--ck-accent-color"],rt=(o=et.$customTheme["--ck-accent-text-color"])!==null&&o!==void 0?o:"#ffffff";return{"--ck-accent-color":tt,"--ck-accent-text-color":rt,"--ck-secondary-button-background":tt,"--ck-secondary-button-hover-background":tt,"--ck-secondary-button-color":rt,"--ck-button-primary-color":rt,"--ck-focus-color":tt}}if(et.$customTheme)return createCssColors(et.$customTheme,!0)}} + + all: initial; + text-align: left; + text-direction: ltr; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + -webkit-text-stroke: 0.001px transparent; + text-size-adjust: none; + font-size: 16px; + + button { + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + -webkit-text-stroke: 0.001px transparent; + } + + &, + * { + font-family: var(--ck-font-family); + box-sizing: border-box; + outline: none; + border: none; + } + /* + @media (prefers-reduced-motion) { + * { + animation-duration: 60ms !important; + transition-duration: 60ms !important; + } + } + */ + img, + svg { + max-width: 100%; + } + strong { + font-weight: 600; + } + a:focus-visible, + button:focus-visible { + outline: 2px solid var(--ck-focus-color); + } +`,Portal$2=et=>{et={selector:"__CONNECTKIT__",...et};const{selector:o,children:tt}=et,rt=reactExports.useRef(null),[nt,ot]=reactExports.useState(!1);return reactExports.useEffect(()=>{const it="#"+o.replace(/^#/,"");if(rt.current=document.querySelector(it),!rt.current){const st=document.createElement("div");st.setAttribute("id",o),st.setAttribute("data-connectkit",`${CONNECTKIT_VERSION}`),document.body.appendChild(st),rt.current=st}ot(!0)},[o]),rt.current&&nt?reactDomExports.createPortal(tt,rt.current):null};var defaultTheme={mobileWidth:560};const ErrorMessage=styled(motion.div)` + z-index: -1; + pointer-events: auto; + position: absolute; + left: 50%; + transform: translateX(-50%); + width: var(--width); + top: 64px; + color: #fff; + font-size: 14px; + line-height: 20px; + font-weight: 500; + background: var(--ck-body-color-danger); + border-radius: 20px; + padding: 24px 46px 82px 24px; + transition: width var(--duration) var(--ease); + a { + font-weight: 700; + text-decoration: underline; + } + code { + font-size: 0.9em; + display: inline-block; + font-family: monospace; + margin: 1px; + padding: 0 4px; + border-radius: 8px; + font-weight: bold; + background: rgba(255, 255, 255, 0.1); + } +`,FadeIn=We` +from { opacity: 0; } + to { opacity: 1; } +`,FadeInScaleUp=We` +from { opacity: 0; transform: scale(0.85); } + to { opacity: 1; transform: scale(1); } +`,FadeInScaleDown=We` +from { opacity: 0; transform: scale(1.1); } + to { opacity: 1; transform: scale(1); } +`,FadeOut=We` +from { opacity: 1; } + to { opacity: 0; } +`,FadeOutScaleUp=We` +from { opacity: 1; transform: scale(1); } + to { opacity: 0; transform: scale(1.1); } +`,FadeOutScaleDown=We` +from { opacity: 1; transform: scale(1); } + to { opacity: 0; transform: scale(0.85); } +`,PageContent=styled(motion.div)` + max-width: 100%; + width: 295px; + padding-top: 48px; +`,TextWithHr=styled(motion.div)` + user-select: none; + position: relative; + display: block; + text-align: center; + color: var(--ck-body-color-muted); + font-size: 15px; + font-weight: 400; + line-height: 21px; + span { + z-index: 2; + position: relative; + display: inline-block; + user-select: none; + pointer-events: none; + padding: 0 14px; + background: var(--ck-body-background); + transition: background-color 200ms ease; + } + &:before { + z-index: 2; + content: ''; + position: absolute; + top: 50%; + left: 0; + right: 0; + height: 1px; + transform: translateY(-1px); + background: var(--ck-body-divider); + box-shadow: var(--ck-body-divider-box-shadow); + } +`,ModalHeading=styled(motion.div)` + z-index: 3; + pointer-events: none; + user-select: none; + position: absolute; + top: 25px; + left: 50%; + display: flex; + align-items: center; + justify-content: center; + height: 26px; + transform: translateX(-50%); + width: var(--width); + text-align: center; + font-size: 17px; + line-height: 20px; + font-weight: var(--ck-modal-heading-font-weight, 600); + color: var(--ck-body-color); + span { + display: inline-block; + } +`,ModalContentContainer=styled(motion.div)` + position: relative; + padding: 0; +`,ModalContent=styled(motion.div)` + left: 0; + right: 0; + text-align: center; + display: flex; + flex-direction: column; + gap: 12px; + padding: 0 0 16px; + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + display: block; + } +`,ModalH1=styled(motion.h1)` + margin: 0; + padding: 0; + line-height: ${et=>et.$small?20:22}px; + font-size: ${et=>et.$small?17:19}px; + font-weight: var(--ck-modal-h1-font-weight, 600); + color: ${et=>et.$error?"var(--ck-body-color-danger)":et.$valid?"var(--ck-body-color-valid)":"var(--ck-body-color)"}; + > svg { + position: relative; + top: -2px; + display: inline-block; + vertical-align: middle; + margin-right: 6px; + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + margin-bottom: 6px; + font-size: 17px; + } +`,ModalBody=styled.div` + font-size: 16px; + font-weight: 400; + line-height: 21px; + color: var(--ck-body-color-muted); + strong { + font-weight: 500; + color: var(--ck-body-color); + } +`;styled.div` + padding: 0 12px; + font-size: 13px; + font-weight: 400; + line-height: 16px; + color: var(--ck-body-color-muted); + strong { + font-weight: 500; + color: var(--ck-body-color); + } +`;const BackgroundOverlay=styled(motion.div)` + z-index: 1; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: var(--ck-overlay-background, rgba(71, 88, 107, 0.24)); + backdrop-filter: ${et=>et.$blur?`blur(${et.$blur}px)`:"var(--ck-overlay-backdrop-filter, none)"}; + opacity: 0; + animation: ${et=>et.$active?FadeIn:FadeOut} 150ms ease-out + both; +`,BoxIn=We` + from{ opacity: 0; transform: scale(0.97); } + to{ opacity: 1; transform: scale(1); } +`,BoxOut=We` + from{ opacity: 1; transform: scale(1); } + to{ opacity: 0; transform: scale(0.97); } +`,MobileBoxIn=We` + from { transform: translate3d(0, 100%, 0); } + to { transform: translate3d(0, 0%, 0); } +`,MobileBoxOut=We` + from { opacity: 1; } + to { opacity: 0; } +`,BoxContainer=styled(motion.div)` + z-index: 2; + position: relative; + color: var(--ck-body-color); + + animation: 150ms ease both; + animation-name: ${BoxOut}; + &.active { + animation-name: ${BoxIn}; + } + + &:before { + content: ''; + position: absolute; + top: 0; + bottom: 0; + left: 50%; + width: var(--width); + height: var(--height); + transform: translateX(-50%); + backface-visibility: hidden; + transition: all 200ms ease; + border-radius: var(--ck-border-radius, 20px); + background: var(--ck-body-background); + box-shadow: var(--ck-modal-box-shadow); + } + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + animation-name: ${MobileBoxOut}; + animation-duration: 130ms; + animation-timing-function: ease; + + &.active { + animation-name: ${MobileBoxIn}; + animation-duration: 300ms; + animation-delay: 32ms; + animation-timing-function: cubic-bezier(0.15, 1.15, 0.6, 1); + } + + &:before { + width: 100%; + transition: 0ms height cubic-bezier(0.15, 1.15, 0.6, 1); + will-change: height; + } + } +`,ControllerContainer=styled(motion.div)` + z-index: 3; + position: absolute; + top: 0; + left: 50%; + height: 64px; + transform: translateX(-50%); + backface-visibility: hidden; + width: var(--width); + transition: 0.2s ease width; + pointer-events: auto; + //border-bottom: 1px solid var(--ck-body-divider); +`,InnerContainer$1=styled(motion.div)` + position: relative; + overflow: hidden; + height: var(--height); + transition: 0.2s ease height; + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + transition: 0ms height cubic-bezier(0.15, 1.15, 0.6, 1); + /* animation-delay: 34ms; */ + } +`,PageContainer=styled(motion.div)` + z-index: 2; + position: relative; + top: 0; + left: 50%; + margin-left: calc(var(--width) / -2); + width: var(--width); + /* left: 0; */ + /* width: 100%; */ + display: flex; + justify-content: center; + align-items: center; + transform-origin: center center; + animation: 200ms ease both; + + &.active { + animation-name: ${FadeInScaleDown}; + } + &.active-scale-up { + animation-name: ${FadeInScaleUp}; + } + &.exit-scale-down { + z-index: 1; + pointer-events: none; + position: absolute; + /* top: 0; */ + /* left: 0; */ + animation-name: ${FadeOutScaleDown}; + } + &.exit { + z-index: 1; + pointer-events: none; + position: absolute; + /* top: 0; */ + /* left: 0; */ + /* left: 50%; */ + /* transform: translateX(-50%); */ + animation-name: ${FadeOutScaleUp}; + animation-delay: 16.6667ms; + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + /* animation: 0ms ease both; */ + /* animation-delay: 35ms; */ + animation: 0ms cubic-bezier(0.15, 1.15, 0.6, 1) both; + + &.active { + animation-name: ${FadeIn}; + } + &.active-scale-up { + animation-name: ${FadeIn}; + } + &.exit-scale-down { + z-index: 3; + animation-name: ${FadeOut}; + } + &.exit { + z-index: 3; + animation-name: ${FadeOut}; + animation-delay: 0ms; + } + } +`,PageContents=styled(motion.div)` + margin: 0 auto; + width: fit-content; + padding: 29px 24px 24px; + backface-visibility: hidden; +`,ModalContainer=styled.div` + z-index: 2147483646; // z-index set one below max (2147483647) for if we wish to layer things ontop of the modal in a seperate Portal + position: fixed; + inset: 0; +`,CloseButton=styled(motion.button)` + z-index: 3; + cursor: pointer; + position: absolute; + top: 22px; + right: 17px; + width: 32px; + height: 32px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 16px; + padding: 0; + margin: 0; + color: var(--ck-body-action-color); + background: var(--ck-body-background); + transition: background-color 200ms ease, transform 100ms ease; + /* will-change: transform; */ + svg { + display: block; + } + + &:hover { + background: var(--ck-body-background-secondary); + } + &:active { + transform: scale(0.9); + } +`,SiweButton=styled(motion.button)` + z-index: 3; + position: absolute; + inset: 0; + width: 100%; // FireFox fix + display: flex; + align-items: center; + justify-content: center; + border-radius: 16px; + padding: 0; + margin: 0; + color: var(--ck-body-action-color); + background: var(--ck-body-background); + transition: background-color 200ms ease, transform 100ms ease; + /* will-change: transform; */ + svg { + display: block; + position: relative; + } + + &:enabled { + cursor: pointer; + &:hover { + background: var(--ck-body-background-secondary); + } + &:active { + transform: scale(0.9); + } + } +`,BackButton=styled(motion.button)` + z-index: 3; + position: absolute; + inset: 0; + width: 100%; // FireFox fix + display: flex; + align-items: center; + justify-content: center; + border-radius: 16px; + padding: 0; + margin: 0; + color: var(--ck-body-action-color); + background: var(--ck-body-background); + transition: background-color 200ms ease, transform 100ms ease; + /* will-change: transform; */ + svg { + display: block; + position: relative; + left: -1px; + } + + &:enabled { + cursor: pointer; + &:hover { + background: var(--ck-body-background-secondary); + } + &:active { + transform: scale(0.9); + } + } +`,InfoButton=styled(motion.button)` + z-index: 3; + position: absolute; + inset: 0; + width: 100%; // FireFox fix + transform: translateX(-1px); + display: flex; + align-items: center; + justify-content: center; + border-radius: 16px; + padding: 0; + margin: 0; + color: var(--ck-body-action-color); + background: var(--ck-body-background); + transition: background-color 200ms ease, transform 100ms ease; + /* will-change: transform; */ + svg { + display: block; + position: relative; + } + &:enabled { + cursor: pointer; + &:hover { + background: var(--ck-body-background-secondary); + } + &:active { + transform: scale(0.9); + } + } +`,Container$7=styled(motion.div)` + --ease: cubic-bezier(0.25, 0.1, 0.25, 1); + --duration: 200ms; + --transition: height var(--duration) var(--ease), + width var(--duration) var(--ease); + z-index: 3; + display: block; + pointer-events: none; + position: absolute; + left: 50%; + top: 50%; + width: 100%; + transform: translate3d(-50%, -50%, 0); + backface-visibility: hidden; + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + pointer-events: auto; + left: 0; + top: auto; + bottom: -5px; + transform: none; + ${BoxContainer} { + max-width: 448px; + margin: 0 auto; + &:before { + width: 100%; + border-radius: var(--ck-border-radius, 30px) + var(--ck-border-radius, 30px) 0 0; + } + } + ${PageContainer} { + left: 0; + right: 0; + margin: 0 auto; + width: auto; + } + ${PageContent} { + margin: 0 auto; + width: 100% !important; + } + ${ModalHeading} { + top: 29px; + } + ${ModalContent} { + gap: 12px; + } + ${ModalBody} { + margin: 0 auto; + max-width: 295px; + } + ${PageContents} { + width: 100%; + padding: 31px 24px; + } + ${ControllerContainer} { + width: 100%; + top: 4px; + border-bottom: 0; + } + ${CloseButton} { + right: 22px; + } + ${BackButton} { + top: -1px; + left: -3px; + } + ${InfoButton} { + top: -1px; + left: -3px; + svg { + width: 65%; + height: auto; + } + } + ${CloseButton}, + ${BackButton}, + ${InfoButton} { + // Quick hack for bigger tappable area on mobile + transform: scale(1.4) !important; + background: transparent !important; + svg { + transform: scale(0.8) !important; + } + } + } +`,Disclaimer=styled(motion.div)` + display: flex; + align-items: center; + justify-content: center; + margin: 16px -24px -24px -24px; + padding: 15px 40px 18px; + font-size: var(--ck-body-disclaimer-font-size, 13px); + font-weight: var(--ck-body-disclaimer-font-weight, 400); + text-align: center; + line-height: 19px; + color: var(--ck-body-disclaimer-color, var(--ck-body-color-muted, inherit)); + + & a { + color: var(--ck-body-disclaimer-link-color, inherit); + font-weight: var(--ck-body-disclaimer-font-weight, 400); + text-decoration: none; + transition: color 200ms ease; + &:hover { + color: var(--ck-body-disclaimer-link-hover-color, inherit); + } + } + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + margin: 24px -24px -26px -24px; + padding: 20px 42px 22px 42px; + } +`,DisclaimerBackground=styled(motion.div)` + pointer-events: all; + z-index: 9; + position: absolute; + bottom: 0; + left: 50%; + width: var(--width); + backface-visibility: hidden; + transform: translateX(-50%); + transform-origin: bottom center; + + border-radius: var(--ck-border-radius, 30px); + border-top-left-radius: 0; + border-top-right-radius: 0; + transition: width 200ms ease; + + background: var( + --ck-body-disclaimer-background, + var(--ck-body-background-secondary) + ); + box-shadow: var(--ck-body-disclaimer-box-shadow); + + ${Disclaimer} { + margin: 0 !important; + /* visibility: hidden; */ + } + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + border-radius: 0; + } +`,SignInTooltip=styled(motion.div)` + z-index: 2; + position: absolute; + top: 100%; + white-space: nowrap; + padding: 8px 16px; + color: #fff; + font-size: 13px; + line-height: 1.5; + background: #1a88f8; + border-radius: calc(var(--ck-border-radius) * 0.75); + transform: translateY(8px) translateX(-48px); + box-shadow: var(--ck-modal-box-shadow); + &:before { + content: ''; + position: absolute; + box-shadow: var(--shadow); + width: 18px; + height: 18px; + transform: translate(215%, -75%) rotate(45deg); + background: inherit; + border-radius: 3px 0 0 0; + } + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + transform: translateY(8px) translateX(-16px); + &:before { + transform: translate(40%, -75%) rotate(45deg); + } + } +`,useIsomorphicLayoutEffect$2=typeof window<"u"?reactExports.useLayoutEffect:reactExports.useEffect;function useLockBodyScroll(et){const[o,tt]=reactExports.useState(et),rt=useContext();return useIsomorphicLayoutEffect$2(()=>{var nt;if(!o)return;const ot={overflow:document.body.style.overflow,position:document.body.style.position,touchAction:document.body.style.touchAction,paddingRight:document.body.style.paddingRight},it=getComputedStyle(document.body),st=parseInt(it.marginRight)+parseInt(it.paddingRight)+parseInt(it.borderRight)+parseInt(it.marginLeft)+parseInt(it.paddingLeft)+parseInt(it.borderLeft),at=window.innerWidth-document.body.offsetWidth-st;return document.documentElement.style.setProperty("--ck-scrollbar-width",`${at}px`),document.body.style.overflow="hidden",document.body.style.position="relative",document.body.style.touchAction="none",!((nt=rt.options)===null||nt===void 0)&&nt.avoidLayoutShift&&(document.body.style.paddingRight=`${at}px`),()=>{var ct;document.documentElement.style.removeProperty("--ck-scrollbar-width"),document.body.style.overflow=ot.overflow,document.body.style.position=ot.position,document.body.style.touchAction=ot.touchAction,!((ct=rt.options)===null||ct===void 0)&&ct.avoidLayoutShift&&(document.body.style.paddingRight=ot.paddingRight)}},[o]),reactExports.useEffect(()=>{o!==et&&tt(et)},[et]),[o,tt]}const KEYCODE_TAB=9;function useFocusTrap(){const et=reactExports.useRef(null);function o(tt){if(et.current){var rt=et.current.querySelectorAll(` + a[href]:not(:disabled), + button:not(:disabled), + textarea:not(:disabled), + input[type="text"]:not(:disabled), + input[type="radio"]:not(:disabled), + input[type="checkbox"]:not(:disabled), + select:not(:disabled) + `),nt=rt[0],ot=rt[rt.length-1],it=tt.key==="Tab"||tt.keyCode===KEYCODE_TAB;it&&(tt.shiftKey?document.activeElement===nt&&(ot.focus(),tt.preventDefault()):document.activeElement===ot&&(nt.focus(),tt.preventDefault()))}}return reactExports.useEffect(()=>(et.current&&(et.current.addEventListener("keydown",o),et.current.focus({preventScroll:!0})),()=>{et.current&&et.current.removeEventListener("keydown",o)}),[]),et}function FocusTrap(et){const o=useFocusTrap();return reactExports.useEffect(()=>{o.current&&o.current.focus({preventScroll:!0})},[]),jsxRuntimeExports.jsx("div",{ref:o,tabIndex:0,children:et.children})}function usePrevious(et,o){const tt=reactExports.useRef({target:et,previous:o});return tt.current.target!==et&&(tt.current.previous=tt.current.target,tt.current.target=et),tt.current.previous}const Context$1=reactExports.createContext(null),ConnectKitThemeProvider=({children:et,theme:o="auto",mode:tt="auto",customTheme:rt})=>{const nt={theme:o,mode:tt,customTheme:rt};return reactExports.createElement(Context$1.Provider,{value:nt},jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:et}))},useThemeContext=()=>{const et=React.useContext(Context$1);if(!et)throw Error("ConnectKitThemeProvider must be inside a Provider.");return et},ExternalLinkIcon=({...et})=>jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{left:0,top:0},...et,children:[jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M4 4C2.89543 4 2 4.89543 2 6V12C2 13.1046 2.89543 14 4 14H10C11.1046 14 12 13.1046 12 12V9.66667C12 9.11438 12.4477 8.66667 13 8.66667C13.5523 8.66667 14 9.11438 14 9.66667V12C14 14.2091 12.2091 16 10 16H4C1.79086 16 0 14.2091 0 12V6C0 3.79086 1.79086 2 4 2H6.33333C6.88562 2 7.33333 2.44772 7.33333 3C7.33333 3.55228 6.88562 4 6.33333 4H4Z",fill:"currentColor",fillOpacity:.3}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M9.5 1C9.5 0.447715 9.94772 0 10.5 0H15C15.5523 0 16 0.447715 16 1V5.5C16 6.05228 15.5523 6.5 15 6.5C14.4477 6.5 14 6.05228 14 5.5V3.41421L8.70711 8.70711C8.31658 9.09763 7.68342 9.09763 7.29289 8.70711C6.90237 8.31658 6.90237 7.68342 7.29289 7.29289L12.5858 2H10.5C9.94772 2 9.5 1.55228 9.5 1Z",fill:"currentColor",fillOpacity:.3})]}),AlertIcon=({...et})=>jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"19",height:"18",viewBox:"0 0 19 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:[jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M6.81753 1.60122C7.39283 0.530035 8.46953 0 9.50409 0C10.5507 0 11.6022 0.539558 12.1805 1.59767L18.6047 13.3334C18.882 13.8283 19 14.3568 19 14.8622C19 16.5296 17.7949 18 15.9149 18H3.08514C1.20508 18 0 16.5296 0 14.8622C0 14.3454 0.131445 13.8172 0.405555 13.3379L6.81753 1.60122ZM9.50409 2C9.13355 2 8.77256 2.18675 8.57866 2.54907L8.57458 2.5567L2.14992 14.3166L2.144 14.3268C2.04638 14.4959 2 14.6817 2 14.8622C2 15.5497 2.43032 16 3.08514 16H15.9149C16.5697 16 17 15.5497 17 14.8622C17 14.6681 16.9554 14.4805 16.8588 14.309L16.8529 14.2986L10.4259 2.55741C10.2191 2.1792 9.86395 2 9.50409 2Z",fill:"currentColor"}),jsxRuntimeExports.jsx("path",{d:"M9.5 11.2297C9.01639 11.2297 8.7459 10.9419 8.72951 10.4186L8.60656 6.4157C8.59016 5.88372 8.95902 5.5 9.4918 5.5C10.0164 5.5 10.4016 5.89244 10.3852 6.42442L10.2623 10.4099C10.2377 10.9419 9.96721 11.2297 9.5 11.2297ZM9.5 14.5C8.95082 14.5 8.5 14.0901 8.5 13.5058C8.5 12.9215 8.95082 12.5116 9.5 12.5116C10.0492 12.5116 10.5 12.9128 10.5 13.5058C10.5 14.0988 10.041 14.5 9.5 14.5Z",fill:"currentColor"})]}),DisconnectIcon=({...et})=>jsxRuntimeExports.jsx("svg",{"aria-hidden":"true",width:"15",height:"14",viewBox:"0 0 15 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{left:0,top:0},...et,children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M4 0C1.79086 0 0 1.79086 0 4V10C0 12.2091 1.79086 14 4 14H6C6.55228 14 7 13.5523 7 13C7 12.4477 6.55228 12 6 12H4C2.89543 12 2 11.1046 2 10V4C2 2.89543 2.89543 2 4 2H6C6.55228 2 7 1.55228 7 1C7 0.447715 6.55228 0 6 0H4ZM11.7071 3.29289C11.3166 2.90237 10.6834 2.90237 10.2929 3.29289C9.90237 3.68342 9.90237 4.31658 10.2929 4.70711L11.5858 6H9.5H6C5.44772 6 5 6.44772 5 7C5 7.55228 5.44772 8 6 8H9.5H11.5858L10.2929 9.29289C9.90237 9.68342 9.90237 10.3166 10.2929 10.7071C10.6834 11.0976 11.3166 11.0976 11.7071 10.7071L14.7071 7.70711C15.0976 7.31658 15.0976 6.68342 14.7071 6.29289L11.7071 3.29289Z",fill:"currentColor",fillOpacity:"0.4"})}),TickIcon=({...et})=>jsxRuntimeExports.jsx("svg",{"aria-hidden":"true",width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M9 18C13.9706 18 18 13.9706 18 9C18 4.02944 13.9706 0 9 0C4.02944 0 0 4.02944 0 9C0 13.9706 4.02944 18 9 18ZM13.274 7.13324C13.6237 6.70579 13.5607 6.07577 13.1332 5.72604C12.7058 5.37632 12.0758 5.43932 11.726 5.86676L7.92576 10.5115L6.20711 8.79289C5.81658 8.40237 5.18342 8.40237 4.79289 8.79289C4.40237 9.18342 4.40237 9.81658 4.79289 10.2071L7.29289 12.7071C7.49267 12.9069 7.76764 13.0128 8.04981 12.9988C8.33199 12.9847 8.59505 12.8519 8.77396 12.6332L13.274 7.13324Z",fill:"currentColor"})}),RetryIconCircle=({...et})=>jsxRuntimeExports.jsx("svg",{"aria-hidden":"true",width:"32",height:"32",viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M32 16C32 24.8366 24.8366 32 16 32C7.16344 32 0 24.8366 0 16C0 7.16344 7.16344 0 16 0C24.8366 0 32 7.16344 32 16ZM24.5001 8.74263C25.0834 8.74263 25.5563 9.21551 25.5563 9.79883V14.5997C25.5563 15.183 25.0834 15.6559 24.5001 15.6559H19.6992C19.1159 15.6559 18.643 15.183 18.643 14.5997C18.643 14.0164 19.1159 13.5435 19.6992 13.5435H21.8378L20.071 11.8798C20.0632 11.8724 20.0555 11.865 20.048 11.8574C19.1061 10.915 17.8835 10.3042 16.5643 10.1171C15.2452 9.92999 13.9009 10.1767 12.7341 10.82C11.5674 11.4634 10.6413 12.4685 10.0955 13.684C9.54968 14.8994 9.41368 16.2593 9.70801 17.5588C10.0023 18.8583 10.711 20.0269 11.7273 20.8885C12.7436 21.7502 14.0124 22.2582 15.3425 22.336C16.6726 22.4138 17.9919 22.0572 19.1017 21.3199C19.5088 21.0495 19.8795 20.7333 20.2078 20.3793C20.6043 19.9515 21.2726 19.9262 21.7004 20.3228C22.1282 20.7194 22.1534 21.3876 21.7569 21.8154C21.3158 22.2912 20.8176 22.7161 20.2706 23.0795C18.7793 24.0702 17.0064 24.5493 15.2191 24.4448C13.4318 24.3402 11.7268 23.6576 10.3612 22.4998C8.9956 21.3419 8.0433 19.7716 7.6478 18.0254C7.2523 16.2793 7.43504 14.4519 8.16848 12.8186C8.90192 11.1854 10.1463 9.83471 11.7142 8.97021C13.282 8.10572 15.0884 7.77421 16.861 8.02565C18.6282 8.27631 20.2664 9.09278 21.5304 10.3525L23.4439 12.1544V9.79883C23.4439 9.21551 23.9168 8.74263 24.5001 8.74263Z",fill:"currentColor"})}),RetryIcon=({...et})=>jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"16",height:"14",viewBox:"0 0 16 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:[jsxRuntimeExports.jsx("path",{d:"M14.5 2V6H10.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M14 5.66537L10.9899 2.75871C10.0931 1.83853 8.92897 1.24216 7.6729 1.05947C6.41683 0.876774 5.13688 1.11765 4.02592 1.7458C2.91497 2.37395 2.0332 3.35534 1.5135 4.54208C0.993792 5.72883 0.864305 7.05663 1.14455 8.3254C1.42479 9.59418 2.09958 10.7352 3.06724 11.5765C4.03489 12.4178 5.24298 12.9138 6.50946 12.9898C7.77594 13.0657 9.03219 12.7176 10.0889 11.9977C10.4765 11.7337 10.8295 11.4249 11.142 11.0792",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),CopyToClipboardIcon$1=({...et})=>jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:[jsxRuntimeExports.jsx("path",{d:"M14 9.5V7C14 5.89543 13.1046 5 12 5H7C5.89543 5 5 5.89543 5 7V12C5 13.1046 5.89543 14 7 14H9.5",stroke:"var(--ck-body-color-muted)",strokeWidth:"2"}),jsxRuntimeExports.jsx("rect",{x:"10",y:"10",width:"9",height:"9",rx:"2",stroke:"var(--ck-body-color-muted)",strokeWidth:"2"}),jsxRuntimeExports.jsx("path",{d:"M1 3L3 5L7 1",stroke:"var(--ck-body-color)",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round"})]}),AuthIcon=({...et})=>jsxRuntimeExports.jsx("div",{...et,style:{zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",bottom:0,right:0,background:"#34C759",borderRadius:10,boxShadow:"0 0 0 1.5px var(--background)",width:10,height:10,...et==null?void 0:et.style},children:jsxRuntimeExports.jsx("svg",{"aria-hidden":"true",width:"6",height:"6",viewBox:"0 0 6 6",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{d:"M0.75 3L2.25 4.5L5.25 1.5",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})});var StatusState;(function(et){et.READY="ready",et.LOADING="loading",et.SUCCESS="success",et.REJECTED="rejected",et.ERROR="error"})(StatusState||(StatusState={}));const SIWEContext=reactExports.createContext(null),useSIWE=({onSignIn:et,onSignOut:o}={})=>{const tt=reactExports.useContext(SIWEContext);if(!tt)return{isSignedIn:!1,data:void 0,status:StatusState.ERROR,error:new Error("useSIWE hook must be inside a SIWEProvider."),isRejected:!1,isError:!0,isLoading:!1,isSuccess:!1,isReady:!1,reset:()=>{},signIn:()=>Promise.reject(),signOut:()=>Promise.reject()};const{session:rt,nonce:nt,status:ot,signOut:it,signIn:st,resetStatus:at}=tt,{address:ct,chainId:lt}=rt.data||{},dt=ct?StatusState.SUCCESS:rt.isLoading||nt.isLoading?StatusState.LOADING:ot,ht=dt===StatusState.LOADING,mt=dt===StatusState.SUCCESS,ft=dt===StatusState.REJECTED,pt=dt===StatusState.ERROR,gt=!ct||nt.isFetching||ht||mt,yt=()=>at(),bt=!!ct;return{isSignedIn:bt,data:bt?{address:ct,chainId:lt}:void 0,status:dt,error:rt.error||nt.error,isRejected:ft,isError:pt,isLoading:ht,isSuccess:mt,isReady:gt,signIn:async()=>{if(!bt){const xt=await st();xt&&(et==null||et(xt))}},signOut:async()=>{bt&&(await it(),o==null||o())},reset:yt}},arAE={connectWallet:"الاتصال بالمحفظة",disconnect:"قطع الاتصال",connected:"متصل",wrongNetwork:"شبكة خاطئة",switchNetworks:"تغيير الشبكات",chainNetwork:"شبكة {{ CHAIN }}",copyToClipboard:"نسخ إلى الحافظة",copyCode:"نسخ الكود",moreInformation:"مزيد من المعلومات",back:"عودة",close:"إغلاق",or:"أو",more:"المزيد",tryAgain:"حاول مجددًا",tryAgainQuestion:"هل نحاول مرة أخرى؟",dontHaveTheApp:"ليس لديك التطبيق؟",scanTheQRCode:"مسح رمز الاستجابة السريعة",useWalletConnectModal:"استخدم نموذج ولِيت‌كنيكت",useModal:"استخدم النموذج",installTheExtension:"تثبيت الإضافة",getWalletName:"الحصول على {{ CONNECTORNAME }}",otherWallets:"محافظ أخرى",learnMore:"تعرف على المزيد",getWallet:"الحصول على محفظة",approveInWallet:"الموافقة في المحفظة",confirmInWallet:"تأكيد في المحفظة",awaitingConfirmation:"بانتظار التأكيد",signIn:"تسجيل الدخول",signOut:"تسجيل الخروج",signedIn:"تم تسجيل الدخول",signedOut:"تم تسجيل الخروج",walletNotConnected:"المحفظة غير متصلة",warnings_walletSwitchingUnsupported:"عذرًا، لا تدعم محفظتك تغيير الشبكات من هذا التطبيق.",warnings_walletSwitchingUnsupportedResolve:"حاول تغيير الشبكات من داخل محفظتك بدلاً من ذلك.",warnings_chainUnsupported:"هذا التطبيق غير متوافق مع الشبكة المتصلة حاليًا.",warnings_chainUnsupportedResolve:"للمتابعة، قم بتغيير الشبكة أو قطع الاتصال.",onboardingScreen_heading:"الحصول على محفظة",onboardingScreen_h1:"ابدأ استكشاف الويب3",onboardingScreen_p:"تعتبر محفظتك بوابتك إلى عوالم إيثريوم، التكنولوجيا السحرية التي تمكن استكشاف الويب3.",onboardingScreen_ctaText:"اختر محفظتك الأولى",onboardingScreen_ctaUrl:"https://ethereum.org/ar/wallets/find-wallet/",aboutScreen_heading:"حول المحافظ",aboutScreen_a_h1:"حافظ على أصولك الرقمية",aboutScreen_a_p:"تمكنك المحافظ من إرسال واستقبال وتخزين والتفاعل مع الأصول الرقمية مثل NFTs ورموز إيثريوم الأخرى.",aboutScreen_b_h1:"وسيلة أفضل لتسجيل الدخول",aboutScreen_b_p:"في تطبيقات العصر الحديث، يمكن استخدام محفظتك كوسيلة سهلة لتسجيل الدخول بدلاً من الحاجة إلى تذكر كلمة مرور.",aboutScreen_c_h1:"استكشاف عالم الويب3",aboutScreen_c_p:"تعتبر محفظتك أداة أساسية تمكنك من استكشاف والمشاركة في عالم الويب3 الذي يتطور بسرعة.",aboutScreen_ctaText:"استزيد من المعرفة",aboutScreen_ctaUrl:"https://ethereum.org/ar/wallets/",connectorsScreen_heading:"الاتصال بالمحفظة",connectorsScreen_newcomer:"ليس لدي محفظة",connectorsScreen_h1:"ما هي المحافظ؟",connectorsScreen_p:"تُستخدم المحافظ لإرسال واستقبال وتخزين الأصول الرقمية. يمكنك الاتصال بمحفظة للتفاعل مع التطبيقات.",mobileConnectorsScreen_heading:"اختر محفظة",scanScreen_heading:"مسح باستخدام الهاتف",scanScreen_heading_withConnector:"مسح باستخدام {{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:`افتح محفظة تدعم ولِيت‌كنيكت + لبدء المسح.`,scanScreen_tooltip_default:"افتح {{ CONNECTORNAME }} على هاتفك للمسح",downloadAppScreen_heading:"الحصول على {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:`استخدم كاميرا هاتفك للمسح وتنزيله على نظامي iOS أو Android + +.`,downloadAppScreen_ios:"استخدم كاميرا هاتفك للمسح وتنزيله على نظام iOS.",downloadAppScreen_android:"استخدم كاميرا هاتفك للمسح وتنزيله على نظام Android.",injectionScreen_unavailable_h1:"المتصفح غير مدعوم",injectionScreen_unavailable_p:"لتوصيل محفظتك {{ CONNECTORSHORTNAME }}، قم بتثبيت الإضافة على متصفح {{ SUGGESTEDEXTENSIONBROWSER }}.",injectionScreen_install_h1:"تثبيت {{ CONNECTORNAME }}",injectionScreen_install_p:"لتوصيل محفظتك {{ CONNECTORSHORTNAME }}، قم بتثبيت الإضافة على المتصفح.",injectionScreen_connecting_h1:"طلب الاتصال",injectionScreen_connecting_p:"افتح إضافة المتصفح {{ CONNECTORSHORTNAME }} لتوصيل محفظتك.",injectionScreen_connecting_injected_h1:"طلب الاتصال",injectionScreen_connecting_injected_p:"قبل الطلب من خلال محفظتك للاتصال بتطبيقنا.",injectionScreen_connected_h1:"الاتصال بالفعل",injectionScreen_connected_p:"من الآمن الآن إغلاق هذه النافذة المنبثقة.",injectionScreen_rejected_h1:"تم رفض الطلب",injectionScreen_rejected_p:"لقد قمت برفض الطلب. انقر أعلى للمحاولة مرة أخرى.",injectionScreen_failed_h1:"فشل الاتصال",injectionScreen_failed_p:"عذرًا، حدث خطأ ما. يُرجى المحاولة مرة أخرى للاتصال.",injectionScreen_notconnected_h1:"تسجيل الدخول إلى {{ CONNECTORNAME }}",injectionScreen_notconnected_p:"للمتابعة، يُرجى تسجيل الدخول إلى إضافة {{ CONNECTORNAME }}.",profileScreen_heading:"متصل",switchNetworkScreen_heading:"تبديل الشبكات",signInWithEthereumScreen_tooltip:`أنت غير مسجل الدخول حاليًا إلى هذا التطبيق. +**سجل الدخول باستخدام إثيريوم** للمتابعة.`,signInWithEthereumScreen_signedOut_heading:"سجل الدخول باستخدام إثيريوم",signInWithEthereumScreen_signedOut_h1:`يود هذا التطبيق التحقق منك + كصاحب لهذه المحفظة.`,signInWithEthereumScreen_signedOut_p:"يرجى تأكيد طلب الرسالة في محفظتك للمتابعة.",signInWithEthereumScreen_signedOut_button:"سجل الدخول",signInWithEthereumScreen_signedIn_heading:"تم تسجيل الدخول باستخدام إثيريوم",signInWithEthereumScreen_signedIn_h1:"لقد قمت بتأكيد نفسك كصاحب لهذه المحفظة بنجاح.",signInWithEthereumScreen_signedIn_p:"سيتطلب تسجيل الخروج منك إعادة المصادقة مرة أخرى في المستقبل.",signInWithEthereumScreen_signedIn_button:"تسجيل الخروج"},enUS={connectWallet:"Connect Wallet",disconnect:"Disconnect",connected:"Connected",wrongNetwork:"Wrong Network",switchNetworks:"Switch Networks",chainNetwork:"{{ CHAIN }} Network",copyToClipboard:"Copy to Clipboard",copyCode:"Copy Code",moreInformation:"More Information",back:"Back",close:"Close",or:"or",more:"More",tryAgain:"Try Again",tryAgainQuestion:"Try Again?",dontHaveTheApp:"Don't have the app?",scanTheQRCode:"Scan the QR code",useWalletConnectModal:"Use WalletConnect Modal",useModal:"Use Modal",installTheExtension:"Install the Extension",getWalletName:"Get {{ CONNECTORNAME }}",otherWallets:"Other Wallets",learnMore:"Learn More",getWallet:"Get a Wallet",approveInWallet:"Approve in Wallet",confirmInWallet:"Confirm in Wallet",awaitingConfirmation:"Awaiting Confirmation",signIn:"Sign In",signOut:"Sign Out",signedIn:"Signed In",signedOut:"Signed Out",walletNotConnected:"Wallet Not Connected",warnings_walletSwitchingUnsupported:"Your wallet does not support switching networks from this app.",warnings_walletSwitchingUnsupportedResolve:"Try switching networks from within your wallet instead.",warnings_chainUnsupported:"This app does not support the current connected network.",warnings_chainUnsupportedResolve:"Switch or disconnect to continue.",onboardingScreen_heading:"Get a Wallet",onboardingScreen_h1:"Start Exploring Web3",onboardingScreen_p:"Your wallet is the gateway to all things Ethereum, the magical technology that makes it possible to explore web3.",onboardingScreen_ctaText:"Choose Your First Wallet",onboardingScreen_ctaUrl:"https://ethereum.org/en/wallets/find-wallet/",aboutScreen_heading:"About Wallets",aboutScreen_a_h1:"For your digital assets",aboutScreen_a_p:"Wallets let you send, receive, store, and interact with digital assets like NFTs and other Ethereum tokens.",aboutScreen_b_h1:"A better way to login",aboutScreen_b_p:"With modern apps, your wallet can be used as an easy way to login, instead of having to remember a password.",aboutScreen_c_h1:"Explore the world of web3",aboutScreen_c_p:"Your wallet is an essential utility that lets you explore and participate in the fast evolving world of web3.",aboutScreen_ctaText:"Learn More",aboutScreen_ctaUrl:"https://ethereum.org/en/wallets/",connectorsScreen_heading:"Connect Wallet",connectorsScreen_newcomer:"I don’t have a wallet",connectorsScreen_h1:"What is a wallet?",connectorsScreen_p:"Wallets are used to send, receive, and store digital assets. Connecting a wallet lets you interact with apps.",mobileConnectorsScreen_heading:"Choose Wallet",scanScreen_heading:"Scan with Phone",scanScreen_heading_withConnector:"Scan with {{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:`Open a [WALLETCONNECTLOGO] WalletConnect +supported wallet to scan`,scanScreen_tooltip_default:`Open {{ CONNECTORNAME }} on +your mobile phone to scan`,downloadAppScreen_heading:"Get {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"Scan with your phone camera to download on iOS or Android.",downloadAppScreen_ios:"Scan with your phone camera to download on iOS.",downloadAppScreen_android:"Scan with your phone camera to download Android.",injectionScreen_unavailable_h1:"Unsupported Browser",injectionScreen_unavailable_p:`To connect your {{ CONNECTORSHORTNAME }} wallet, +install the extension on {{ SUGGESTEDEXTENSIONBROWSER }}.`,injectionScreen_install_h1:"Install {{ CONNECTORNAME }}",injectionScreen_install_p:`To connect your {{ CONNECTORSHORTNAME }} wallet, +install the browser extension.`,injectionScreen_connecting_h1:"Requesting Connection",injectionScreen_connecting_p:`Open the {{ CONNECTORSHORTNAME }} browser +extension to connect your wallet.`,injectionScreen_connecting_injected_h1:"Requesting Connection",injectionScreen_connecting_injected_p:"Accept the request through your wallet to connect to this app.",injectionScreen_connected_h1:"Already Connected",injectionScreen_connected_p:"It is now okay to close this popup",injectionScreen_rejected_h1:"Request Cancelled",injectionScreen_rejected_p:`You cancelled the request. +Click above to try again.`,injectionScreen_failed_h1:"Connection Failed",injectionScreen_failed_p:`Sorry, something went wrong. +Please try connecting again.`,injectionScreen_notconnected_h1:"Login to {{ CONNECTORNAME }}",injectionScreen_notconnected_p:"To continue, please login to your {{ CONNECTORNAME }} extension.",profileScreen_heading:"Connected",switchNetworkScreen_heading:"Switch Networks",signInWithEthereumScreen_tooltip:`You’re not signed in to this app. +**Sign In With Ethereum** to continue.`,signInWithEthereumScreen_signedOut_heading:"Sign In With Ethereum",signInWithEthereumScreen_signedOut_h1:`This app would like to verify you + as the owner of this wallet.`,signInWithEthereumScreen_signedOut_p:`Please sign the message request + in your wallet to continue.`,signInWithEthereumScreen_signedOut_button:"Sign In",signInWithEthereumScreen_signedIn_heading:"Signed In With Ethereum",signInWithEthereumScreen_signedIn_h1:`You successfully verified yourself + as the owner of this wallet.`,signInWithEthereumScreen_signedIn_p:`Signing out will require you to + authenticate again in the future.`,signInWithEthereumScreen_signedIn_button:"Sign Out"},eeEE={connectWallet:"Ühenda rahakott",disconnect:"Katkesta ühendus",connected:"Ühendatud",wrongNetwork:"Vale võrk",switchNetworks:"Vaheta võrke",chainNetwork:"{{ CHAIN }} Võrk",copyToClipboard:"Kopeeri lõikelauale",copyCode:"Kopeeri koodi",moreInformation:"Rohkem infot",back:"Tagasi",close:"Pane kinni",or:"või",more:"Rohkem",tryAgain:"Proovi uuesti",tryAgainQuestion:"Proovi uuesti?",dontHaveTheApp:"Kas teil pole rakendust?",scanTheQRCode:"Skaneeri QR-kood",useWalletConnectModal:"Kasuta WalletConnecti modalit",useModal:"Kasuta Modalit",installTheExtension:"Installi laiendust",getWalletName:"Hanki {{ CONNECTORNAME }}",otherWallets:"Teised rahakotid",learnMore:"Avasta rohkem",getWallet:"Lae alla rahakott",approveInWallet:"Kiita heaks rahakotis",confirmInWallet:"Kinnita rahakotis",awaitingConfirmation:"Kinnituse ootel",signIn:"Logi sisse",signOut:"Logi välja",signedIn:"Sisse logitud",signedOut:"Välja logitud",walletNotConnected:"Raakott pole ühendatud",warnings_walletSwitchingUnsupported:"Teie rahakott ei toeta võrgu vahetamist sellest rakendusest.",warnings_walletSwitchingUnsupportedResolve:"Proovige võrgu vahetamist teha oma rahakoti seest.",warnings_chainUnsupported:"See rakendus ei toeta praegu ühendatud võrku.",warnings_chainUnsupportedResolve:"Jätkamiseks vahetage või ühendage lahti.",onboardingScreen_heading:"Hankige rahakott",onboardingScreen_h1:"Alustage Web3 uurimist",onboardingScreen_p:"Teie rahakott on värav kõigele, mis puudutab Ethereumit, maagilist tehnoloogiat, mis võimaldab uurida Web3.",onboardingScreen_ctaText:"Valige oma esimene rahakott",onboardingScreen_ctaUrl:"https://ethereum.org/en/wallets/find-wallet/",aboutScreen_heading:"Rahakottidest",aboutScreen_a_h1:"Teie digitaalsetele varadele",aboutScreen_a_p:"Rahakotid võimaldavad teil saata, vastu võtta, salvestada ja suhelda digitaalsete varadega nagu NFT-d ja teised Ethereumi tokenid.",aboutScreen_b_h1:"Parem viis sisse logimiseks",aboutScreen_b_p:"Kaasaegsete rakendustega saab teie rahakotti kasutada lihtsa sisselogimisviisina, ilma et peaksite meeles pidama parooli.",aboutScreen_c_h1:"Uurige Web3 maailma",aboutScreen_c_p:"Teie rahakott on oluline tööriist, mis võimaldab teil uurida ja osaleda kiiresti arenevas Web3 maailmas.",aboutScreen_ctaText:"Lisateavet saamiseks",aboutScreen_ctaUrl:"https://ethereum.org/en/wallets/",connectorsScreen_heading:"Ühendage rahakott",connectorsScreen_newcomer:"Mul pole rahakotti",connectorsScreen_h1:"Mis on rahakott?",connectorsScreen_p:"Rahakotte kasutatakse digitaalsete varade saatmiseks, vastuvõtmiseks ja salvestamiseks. Rahakoti ühendamine võimaldab teil rakendustega suhelda.",mobileConnectorsScreen_heading:"Valige rahakott",scanScreen_heading:"Skaneerige telefoni abil",scanScreen_heading_withConnector:"Skaneerige koos {{ CONNECTORNAME }}-ga",scanScreen_tooltip_walletConnect:`Ava [WALLETCONNECTLOGO] WalletConnect +toetatud rahakott skaneerimiseks`,scanScreen_tooltip_default:`Ava {{ CONNECTORNAME }} oma +mobiiltelefonil skaneerimiseks`,downloadAppScreen_heading:"Hankige {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"Skaneerige oma telefoni kaameraga allalaadimiseks iOS-i või Androidi jaoks.",downloadAppScreen_ios:"Skaneerige oma telefoni kaameraga allalaadimiseks iOS-i jaoks.",downloadAppScreen_android:"Skaneerige oma telefoni kaameraga Androidi allalaadimiseks.",injectionScreen_unavailable_h1:"Toetuseta brauser",injectionScreen_unavailable_p:`Teie {{ CONNECTORSHORTNAME }} rahakoti ühendamiseks +installige laiendus {{ SUGGESTEDEXTENSIONBROWSER }}-le.`,injectionScreen_install_h1:"Installige {{ CONNECTORNAME }}",injectionScreen_install_p:`Teie {{ CONNECTORSHORTNAME }} rahakoti ühendamiseks +installige brauseri laiendus.`,injectionScreen_connecting_h1:"Ühenduse taotlemine",injectionScreen_connecting_p:`Ava {{ CONNECTORSHORTNAME }} brauseri +laiendus rahakoti ühendamiseks.`,injectionScreen_connecting_injected_h1:"Ühenduse taotlemine",injectionScreen_connecting_injected_p:"Nõustuge rakendusega ühendamiseks oma rahakotis.",injectionScreen_connected_h1:"Juba ühendatud",injectionScreen_connected_p:"Selle popup-i saab nüüd sulgeda",injectionScreen_rejected_h1:"Taotlus tühistatud",injectionScreen_rejected_p:`Tühistasite taotluse. +Klõpsake ülal, et uuesti proovida.`,injectionScreen_failed_h1:"Ühenduse loomine ebaõnnestus",injectionScreen_failed_p:`Vabandame, midagi läks valesti. +Proovige ühendust uuesti luua.`,injectionScreen_notconnected_h1:"Logige sisse {{ CONNECTORNAME }}-ga",injectionScreen_notconnected_p:"Jätkamiseks logige sisse oma {{ CONNECTORNAME }} laiendisse.",profileScreen_heading:"Ühendatud",switchNetworkScreen_heading:"Võrkude vahetamine",signInWithEthereumScreen_tooltip:`Te pole selle rakendusse sisse logitud. +**Logi sisse Ethereumiga** jätkamiseks.`,signInWithEthereumScreen_signedOut_heading:"Logi sisse Ethereumiga",signInWithEthereumScreen_signedOut_h1:`See rakendus soovib teid autentida + selle rahakoti omanikuna.`,signInWithEthereumScreen_signedOut_p:`Jätkamiseks allkirjastage sõnumipäring + oma rahakotis.`,signInWithEthereumScreen_signedOut_button:"Logi sisse",signInWithEthereumScreen_signedIn_heading:"Logi välja",signInWithEthereumScreen_signedIn_h1:`Olete edukalt autentinud end + selle rahakoti omanikuna.`,signInWithEthereumScreen_signedIn_p:`Välja logimine nõuab tulevikus + uuesti autentimist.`,signInWithEthereumScreen_signedIn_button:"Logi välja"},esES={connectWallet:"Conecta una cartera",disconnect:"Desconectar",connected:"Conectado",wrongNetwork:"Red incorrecta",switchNetworks:"Cambio de red",chainNetwork:"Red {{ CHAIN }}",copyToClipboard:"Copiar al portapapeles",copyCode:"Copiar código",moreInformation:"Más información",back:"Atrás",close:"Cerrar",or:"o",more:"Más",tryAgain:"Intentar de nuevo",tryAgainQuestion:"¿Intentar de nuevo?",dontHaveTheApp:"¿No tienes la aplicación?",scanTheQRCode:"Escanea el código QR",useWalletConnectModal:"Utilizar WalletConnect Modal",useModal:"Utilizar Modal",installTheExtension:"Instalar la extensión",getWalletName:"Obtén {{ CONNECTORNAME }}",otherWallets:"Otras carteras",learnMore:"Más información",getWallet:"Obtén una cartera",approveInWallet:"Aprobar en la cartera",confirmInWallet:"Confirmar en la cartera",awaitingConfirmation:"A la espera de confirmación",signIn:"Iniciar sesión",signOut:"Cerrar sesión",signedIn:"Sesión iniciada",signedOut:"Sesión cerrada",walletNotConnected:"Cartera no conectada",warnings_walletSwitchingUnsupported:"Tu cartera no permite cambiar de red desde esta aplicación.",warnings_walletSwitchingUnsupportedResolve:"Prueba a cambiar de red desde tu cartera.",warnings_chainUnsupported:"Esta aplicación no es compatible con la red conectada actualmente.",warnings_chainUnsupportedResolve:"Cambia o desconecta para continuar.",onboardingScreen_heading:"Obtén una cartera",onboardingScreen_h1:"Comienza a explorar la Web3",onboardingScreen_p:"Tu cartera es el portal de acceso a todo lo relacionado con Ethereum, la tecnología mágica que permite explorar la Web3.",onboardingScreen_ctaText:"Elige tu primera cartera",onboardingScreen_ctaUrl:"https://ethereum.org/es/wallets/find-wallet/",aboutScreen_heading:"Acerca de las carteras",aboutScreen_a_h1:"Para tus activos digitales",aboutScreen_a_p:"Las carteras te permiten enviar, recibir, almacenar e interactuar con activos digitales como los NFT y otros tokens de Ethereum.",aboutScreen_b_h1:"Una manera mejor de iniciar sesión",aboutScreen_b_p:"Con las aplicaciones modernas, puedes utilizar tu cartera para iniciar sesión fácilmente, en vez de tener que recordar una contraseña.",aboutScreen_c_h1:"Explora el mundo de la Web3",aboutScreen_c_p:"Tu cartera es una herramienta esencial que te permite explorar y participar en el mundo en rápida evolución de la Web3.",aboutScreen_ctaText:"Más información",aboutScreen_ctaUrl:"https://ethereum.org/es/wallets/",connectorsScreen_heading:"Conecta una cartera",connectorsScreen_newcomer:"No tengo una cartera",connectorsScreen_h1:"¿Qué es una cartera?",connectorsScreen_p:"Las carteras se utilizan para enviar, recibir y almacenar activos digitales. Si conectas una cartera, podrás interactuar con las aplicaciones.",mobileConnectorsScreen_heading:"Elige una cartera",scanScreen_heading:"Escanea con el teléfono",scanScreen_heading_withConnector:"Escanea con {{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:"Abre una cartera compatible con WalletConnect [WALLETCONNECTLOGO] para escanear",scanScreen_tooltip_default:"Abre {{ CONNECTORNAME }} en tu teléfono móvil para escanear",downloadAppScreen_heading:"Obtén {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"Escanea con la cámara de tu teléfono para descargarla en iOS o Android.",downloadAppScreen_ios:"Escanea con la cámara de tu teléfono para descargarla en iOS.",downloadAppScreen_android:"Escanea con la cámara de tu teléfono para descargarla en Android.",injectionScreen_unavailable_h1:"Navegador no compatible",injectionScreen_unavailable_p:"Para conectar tu cartera de {{ CONNECTORSHORTNAME }}, instala la extensión en {{ SUGGESTEDEXTENSIONBROWSER }}.",injectionScreen_install_h1:"Instala {{ CONNECTORNAME }}",injectionScreen_install_p:"Para conectar tu cartera de {{ CONNECTORSHORTNAME }}, instala la extensión del navegador.",injectionScreen_connecting_h1:"Solicitud de conexión",injectionScreen_connecting_p:"Abre la extensión del navegador de {{ CONNECTORSHORTNAME }} para conectar tu cartera.",injectionScreen_connecting_injected_h1:"Solicitud de conexión",injectionScreen_connecting_injected_p:"Acepta la solicitud a través de tu cartera para conectarte a esta aplicación.",injectionScreen_connected_h1:"Ya conectada",injectionScreen_connected_p:"Ya puedes cerrar esta ventana emergente",injectionScreen_rejected_h1:"Solicitud cancelada",injectionScreen_rejected_p:"Has cancelado la solicitud. Haz clic arriba para intentarlo de nuevo.",injectionScreen_failed_h1:"Error de conexión",injectionScreen_failed_p:"Lo sentimos, ha habido un problema. Intenta conectarte de nuevo.",injectionScreen_notconnected_h1:"Inicia sesión en {{ CONNECTORNAME }}",injectionScreen_notconnected_p:"Para continuar, inicia sesión en tu extensión de {{ CONNECTORNAME }}.",profileScreen_heading:"Conectado",switchNetworkScreen_heading:"Cambio de red",signInWithEthereumScreen_tooltip:`No has iniciado sesión en esta aplicación. +**Inicia sesión con Ethereum** para continuar.`,signInWithEthereumScreen_signedOut_heading:"Inicia sesión con Ethereum",signInWithEthereumScreen_signedOut_h1:"Esta aplicación desea verificar que eres el propietario de esta cartera.",signInWithEthereumScreen_signedOut_p:"Firma la solicitud de mensaje en tu cartera para continuar.",signInWithEthereumScreen_signedOut_button:"Iniciar sesión",signInWithEthereumScreen_signedIn_heading:"Sesión iniciada con Ethereum",signInWithEthereumScreen_signedIn_h1:"Te has verificado correctamente como propietario de esta cartera.",signInWithEthereumScreen_signedIn_p:"Si cierras la sesión, tendrás que volver a autenticarte más adelante.",signInWithEthereumScreen_signedIn_button:"Cerrar sesión"},faIR={connectWallet:"اتصال به کیف پول",disconnect:"قطع ارتباط",connected:"متصل شد",wrongNetwork:"شبکه نادرست",switchNetworks:"تغییر شبکه‌ها",chainNetwork:"{{ CHAIN }} شبکه",copyToClipboard:"کپی به کلیپ‌بورد",copyCode:"کپی کد",moreInformation:"اطلاعات بیشتر",back:"بازگشت",close:"بستن",or:"یا",more:"بیشتر",tryAgain:"تلاش دوباره",tryAgainQuestion:"آیا دوباره تلاش کنیم؟",dontHaveTheApp:"اپلیکیشن را ندارید؟",scanTheQRCode:"اسکن کیو‌آر کد",useWalletConnectModal:"استفاده از مودال والت‌‌کانکت",useModal:"استفاده از مودال",installTheExtension:"نصب افزونه",getWalletName:"دریافت {{ CONNECTORNAME }}",otherWallets:"کیف پول‌های دیگر",learnMore:"بیشتر بدانید",getWallet:"یک کیف پول دریافت کنید",approveInWallet:"در کیف پول تأیید کنید",confirmInWallet:"در کیف پول تأیید کنید",awaitingConfirmation:"در انتظار تأیید",signIn:"ورود",signOut:"خروج",signedIn:"وارد شده",signedOut:"خارج شده",walletNotConnected:"کیف پول متصل نیست",warnings_walletSwitchingUnsupported:"متاسفانه، کیف پول شما از تغییر شبکه در این برنامه پشتیبانی نمی‌کند.",warnings_walletSwitchingUnsupportedResolve:"بهتر است از داخل کیف پول خود تغییر شبکه دهید.",warnings_chainUnsupported:"این برنامه با شبکه‌ای که در حال حاضر متصل است، سازگاری ندارد.",warnings_chainUnsupportedResolve:"برای ادامه، شبکه را تغییر دهید یا اتصال را قطع کنید.",onboardingScreen_heading:"دریافت کیف پول",onboardingScreen_h1:"آغاز کاوش در وب3",onboardingScreen_p:"کیف پول شما دروازه‌ای است به دنیای اتریوم، فناوری جادویی که ممکن می‌سازد تا وب3 را کاوش کنید.",onboardingScreen_ctaText:"کیف پول نخست خود را انتخاب کنید",onboardingScreen_ctaUrl:"https://ethereum.org/fa/wallets/find-wallet/",aboutScreen_heading:"درباره کیف پول‌ها",aboutScreen_a_h1:"نگهبان دارایی‌های دیجیتالی شما",aboutScreen_a_p:"کیف پول‌ها به شما اجازه می‌دهند دارایی‌های دیجیتالی مانند ان‌اف‌تی و توکن‌های اتریومی دیگر را ارسال، دریافت، ذخیره و تعامل دهید.",aboutScreen_b_h1:"یک روش بهتر برای ورود",aboutScreen_b_p:"در برنامه‌های مدرن، کیف پول شما می‌تواند به عنوان یک راه ورود آسان به جای به یادآوری یک رمز عبور مورد استفاده قرار گیرد.",aboutScreen_c_h1:"جهان وب3 را کاوش کنید",aboutScreen_c_p:"کیف پول شما یک ابزار ضروری است که به شما اجازه می‌دهد جهان در حال تغییر سریع وب3 را کاوش و در آن شرکت کنید.",aboutScreen_ctaText:"دانش بیشتری بیافزایید",aboutScreen_ctaUrl:"https://ethereum.org/fa/wallets/",connectorsScreen_heading:"برقراری ارتباط با کیف پول",connectorsScreen_newcomer:"کیف پول ندارم",connectorsScreen_h1:"چیستی رمزگذاری کیف پول؟",connectorsScreen_p:"کیف پول‌ها برای ارسال، دریافت و نگهداری دارایی‌های دیجیتال استفاده می‌شوند. برقراری ارتباط با یک کیف پول به شما امکان تعامل با برنامه‌ها را می‌دهد.",mobileConnectorsScreen_heading:"انتخاب کیف پول",scanScreen_heading:"اسکن با گوشی",scanScreen_heading_withConnector:"اسکن با {{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:"یک کیف پول با پشتیبانی از والت‌‌کانکت را باز کنید تا اسکن را آغاز کنید",scanScreen_tooltip_default:"{{ CONNECTORNAME }} را روی گوشی خود باز کنید تا اسکن شود",downloadAppScreen_heading:"دریافت {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"از دوربین گوشی خود برای اسکن و دریافت نسخه iOS یا Android استفاده کنید.",downloadAppScreen_ios:"از دوربین گوشی خود برای دریافت نسخه iOS استفاده کنید.",downloadAppScreen_android:"از دوربین گوشی خود برای دریافت نسخه Android استفاده کنید.",injectionScreen_unavailable_h1:"مرورگر پشتیبانی نمی‌شود",injectionScreen_unavailable_p:"برای برقراری ارتباط با کیف پول {{ CONNECTORSHORTNAME }}، افزونه مرورگر را در {{ SUGGESTEDEXTENSIONBROWSER }} نصب کنید.",injectionScreen_install_h1:"نصب {{ CONNECTORNAME }}",injectionScreen_install_p:"برای برقراری ارتباط با کیف پول {{ CONNECTORSHORTNAME }}، افزونه مرورگر را نصب کنید.",injectionScreen_connecting_h1:"درخواست اتصال",injectionScreen_connecting_p:"افزونه مرورگر {{ CONNECTORSHORTNAME }} را باز کنید تا ارتباط با کیف پول ایجاد شود.",injectionScreen_connecting_injected_h1:"درخواست اتصال",injectionScreen_connecting_injected_p:"درخواست را از طریق کیف پول خود بپذیرید تا به این برنامه متصل شوید.",injectionScreen_connected_h1:"اتصال از قبل برقرار است",injectionScreen_connected_p:"اکنون می‌توانید این پنجره‌ی بازشو را ببندید.",injectionScreen_rejected_h1:"درخواست لغو شد",injectionScreen_rejected_p:"شما درخواست را لغو کرده‌اید. برای تلاش مجدد، بالا کلیک کنید.",injectionScreen_failed_h1:"ارتباط ناموفق",injectionScreen_failed_p:"متاسفانه، مشکلی بوجود آمد. لطفاً مجدداً اتصال برقرار کنید.",injectionScreen_notconnected_h1:"با ورود به {{ CONNECTORNAME }} وارد شوید",injectionScreen_notconnected_p:"برای ادامه، لطفاً وارد افزونه {{ CONNECTORNAME }} خود شوید.",profileScreen_heading:"اتصال‌ها",switchNetworkScreen_heading:"تغییر شبکه‌ها",signInWithEthereumScreen_tooltip:`شما در حال حاضر به این برنامه وارد نشده‌اید. +**با اتریوم وارد شوید** تا ادامه دهید.`,signInWithEthereumScreen_signedOut_heading:"با اتریوم وارد شوید",signInWithEthereumScreen_signedOut_h1:`این برنامه می‌خواهد هویت شما + به عنوان صاحب این کیف پول را تأیید کند.`,signInWithEthereumScreen_signedOut_p:"لطفاً درخواست پیام را در کیف پول خود تأیید کنید تا ادامه دهید.",signInWithEthereumScreen_signedOut_button:"با اتریوم وارد شوید",signInWithEthereumScreen_signedIn_heading:"با اتریوم وارد شده‌اید",signInWithEthereumScreen_signedIn_h1:"شما به عنوان صاحب این کیف پول هویت خود را با موفقیت تأیید کرده‌اید.",signInWithEthereumScreen_signedIn_p:"خروج از حساب کاربری شما در آینده نیاز به تأیید دوباره دارد.",signInWithEthereumScreen_signedIn_button:"خروج"},frFR={connectWallet:"Connecter le portefeuille",disconnect:"Déconnecter",connected:"Connecté",wrongNetwork:"Réseau incorrect",switchNetworks:"Changer de réseau",chainNetwork:"Réseau {{ CHAIN }}",copyToClipboard:"Copier dans le presse-papiers",copyCode:"Copier le code",moreInformation:"Plus d’informations",back:"Retour",close:"Fermer",or:"ou",more:"Plus",tryAgain:"Réessayer",tryAgainQuestion:"Réessayer ?",dontHaveTheApp:"Vous n’avez pas l’application ?",scanTheQRCode:"Scannez le code QR",useWalletConnectModal:"Utiliser la modale WalletConnect",useModal:"Utiliser la modale",installTheExtension:"Installer l’extension",getWalletName:"Obtenez {{ CONNECTORNAME }}",otherWallets:"Autres portefeuilles",learnMore:"En savoir plus",getWallet:"Obtenir un portefeuille",approveInWallet:"Approuver dans le portefeuille",confirmInWallet:"Confirmer dans le portefeuille",awaitingConfirmation:"En attente de confirmation",signIn:"Se connecter",signOut:"Se déconnecter",signedIn:"Connecté",signedOut:"Déconnecté",walletNotConnected:"Portefeuille non connecté",warnings_walletSwitchingUnsupported:"Votre portefeuille ne prend pas en charge le changement de réseau à partir de cette application.",warnings_walletSwitchingUnsupportedResolve:"Essayez plutôt de changer de réseau à partir de votre portefeuille.",warnings_chainUnsupported:"Cette application ne prend pas en charge le réseau connecté actuel.",warnings_chainUnsupportedResolve:"Changez ou déconnectez-vous pour continuer.",onboardingScreen_heading:"Obtenez un portefeuille",onboardingScreen_h1:"Commencez à explorer le Web3",onboardingScreen_p:"Votre portefeuille est la porte d'entrée vers tout ce qui concerne l'Ethereum, la technologie magique qui permet d'explorer le Web3.",onboardingScreen_ctaText:"Choisissez votre premier portefeuille",onboardingScreen_ctaUrl:"https://ethereum.org/fr/wallets/find-wallet/",aboutScreen_heading:"À propos des portefeuilles",aboutScreen_a_h1:"Pour vos actifs numériques",aboutScreen_a_p:"Les portefeuilles vous permettent d'envoyer, de recevoir, de stocker et d'interagir avec des actifs numériques tels que des NFT et d'autres jetons Ethereum.",aboutScreen_b_h1:"Une meilleure façon de se connecter",aboutScreen_b_p:"Avec les applications modernes, votre portefeuille peut s'utiliser pour vous connecter facilement, au lieu d'avoir à mémoriser un mot de passe.",aboutScreen_c_h1:"Explorez le monde du Web3",aboutScreen_c_p:"Votre portefeuille est un utilitaire essentiel qui vous permet d'explorer et de participer au monde en évolution rapide du Web3.",aboutScreen_ctaText:"En savoir plus",aboutScreen_ctaUrl:"https://ethereum.org/fr/wallets/",connectorsScreen_heading:"Connectez le portefeuille",connectorsScreen_newcomer:"Je n’ai pas de portefeuille",connectorsScreen_h1:"Qu’est-ce qu’un portefeuille ?",connectorsScreen_p:"Les portefeuilles s'utilisent pour envoyer, recevoir et stocker des actifs numériques. La connexion d'un portefeuille vous permet d'interagir avec les applications.",mobileConnectorsScreen_heading:"Choisissez le portefeuille",scanScreen_heading:"Scannez avec le téléphone",scanScreen_heading_withConnector:"Scannez avec {{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:"Ouvrez un portefeuille pris en charge par WalletConnect [WALLETCONNECTLOGO] pour scanner",scanScreen_tooltip_default:"Ouvrez {{ CONNECTORNAME }} sur votre téléphone mobile pour scanner",downloadAppScreen_heading:"Obtenez {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"Scannez avec l'appareil photo de votre téléphone pour le télécharger sur iOS ou Android.",downloadAppScreen_ios:"Scannez avec l'appareil photo de votre téléphone pour le télécharger sur iOS.",downloadAppScreen_android:"Scannez avec l'appareil photo de votre téléphone pour le télécharger sur Android.",injectionScreen_unavailable_h1:"Navigateur non pris en charge",injectionScreen_unavailable_p:"Pour connecter votre portefeuille {{ CONNECTORSHORTNAME }}, installez l’extension sur {{ SUGGESTEDEXTENSIONBROWSER }}.",injectionScreen_install_h1:"Installez {{ CONNECTORNAME }}",injectionScreen_install_p:"Pour connecter votre portefeuille {{ CONNECTORSHORTNAME }}, installez l’extension de navigateur.",injectionScreen_connecting_h1:"Demande de connexion",injectionScreen_connecting_p:"Ouvrez l’extension de navigateur {{ CONNECTORSHORTNAME }} pour connecter votre portefeuille.",injectionScreen_connecting_injected_h1:"Demande de connexion",injectionScreen_connecting_injected_p:"Acceptez la demande via votre portefeuille pour vous connecter à cette application.",injectionScreen_connected_h1:"Déjà connecté",injectionScreen_connected_p:"Vous pouvez maintenant fermer ce pop-up",injectionScreen_rejected_h1:"Demande annulée",injectionScreen_rejected_p:"Vous avez annulé la demande. Cliquez ci-dessus pour réessayer.",injectionScreen_failed_h1:"Échec de la connexion",injectionScreen_failed_p:"Malheureusement, un problème est survenu. Veuillez réessayer de vous connecter.",injectionScreen_notconnected_h1:"Connectez-vous à {{ CONNECTORNAME }}",injectionScreen_notconnected_p:"Pour continuer, veuillez vous connecter à votre extension {{ CONNECTORNAME }} .",profileScreen_heading:"Connecté",switchNetworkScreen_heading:"Changer de réseau",signInWithEthereumScreen_tooltip:`Vous n’êtes pas connecté à cette application. +**Connectez-vous avec Ethereum** pour continuer.`,signInWithEthereumScreen_signedOut_heading:"Connectez-vous avec Ethereum",signInWithEthereumScreen_signedOut_h1:"Cette application souhaite vérifier que vous êtes bien le propriétaire de ce portefeuille.",signInWithEthereumScreen_signedOut_p:"Veuillez signer la demande de message dans votre portefeuille pour continuer.",signInWithEthereumScreen_signedOut_button:"Se connecter",signInWithEthereumScreen_signedIn_heading:"Connecté avec Ethereum",signInWithEthereumScreen_signedIn_h1:"Vous avez réussi à vous identifier en tant que propriétaire de ce portefeuille.",signInWithEthereumScreen_signedIn_p:"La déconnexion vous obligera à vous authentifier à nouveau à l'avenir.",signInWithEthereumScreen_signedIn_button:"Se déconnecter"};var jaJP={connectWallet:"ウォレットの接続",disconnect:"切断",connected:"接続されました",wrongNetwork:"間違ったネットワーク",switchNetworks:"ネットワークの切り替え",chainNetwork:"{{ CHAIN }} ネットワーク",copyToClipboard:"クリップボードにコピー",copyCode:"コードをコピー",moreInformation:"詳細情報",back:"戻る",close:"閉じる",or:"または",more:"その他",tryAgain:"再試行",tryAgainQuestion:"もう一度試しますか?",dontHaveTheApp:"アプリをお持ちではありませんか?",scanTheQRCode:"QR コードをスキャン",useWalletConnectModal:"WalletConnect モーダルを使用",useModal:"モーダルを使用",installTheExtension:"拡張機能をインストール",getWalletName:"{{ CONNECTORNAME }} を取得",otherWallets:"その他のウォレット",learnMore:"詳細情報",getWallet:"ウォレットを入手",approveInWallet:"ウォレットで承認",confirmInWallet:"ウォレットで確認",awaitingConfirmation:"確認を待っています",signIn:"サインイン",signOut:"サインアウト",signedIn:"サインインしました",signedOut:"サインアウトしました",walletNotConnected:"ウォレットが接続されていません",warnings_walletSwitchingUnsupported:"お使いのウォレットは、このアプリからのネットワークの切り替えをサポートしていません。",warnings_walletSwitchingUnsupportedResolve:"代わりにウォレット内からネットワークを切り替えてみてください。",warnings_chainUnsupported:"このアプリは、現在接続されているネットワークをサポートしていません。",warnings_chainUnsupportedResolve:"切り替えるか切断して続行します。",onboardingScreen_heading:"ウォレットを入手",onboardingScreen_h1:"Web3 の探索を開始",onboardingScreen_p:"ウォレットは、web3 の探索を可能にする魔法のテクノロジーであるイーサリアムのすべてへのゲートウェイです。",onboardingScreen_ctaText:"最初のウォレットを選択してください",onboardingScreen_ctaUrl:"https://ethereum.org/ja/wallets/find-wallet/",aboutScreen_heading:"ウォレットについて",aboutScreen_a_h1:"デジタル資産用",aboutScreen_a_p:"ウォレットを使用すると、NFT やその他のイーサリアム トークンなどのデジタル資産を送信、受信、保存、および操作できます。",aboutScreen_b_h1:"より良いログイン方法",aboutScreen_b_p:"最新のアプリでは、パスワードを覚える必要がなく、ウォレットを簡単なログイン方法として使用できます。",aboutScreen_c_h1:"web3 の世界を探索",aboutScreen_c_p:"ウォレットは、急速に進化する web3 の世界を探索し、参加するために不可欠なユーティリティです。",aboutScreen_ctaText:"詳細情報",aboutScreen_ctaUrl:"https://ethereum.org/ja/wallets/",connectorsScreen_heading:"ウォレットの接続",connectorsScreen_newcomer:"ウォレットを持っていません",connectorsScreen_h1:"ウォレットとは何ですか?",connectorsScreen_p:"ウォレットは、デジタル資産の送信、受信、および保存に使用されます。 ウォレットを接続すると、アプリとやり取りできます。",mobileConnectorsScreen_heading:"ウォレットを選択",scanScreen_heading:"電話でスキャンする",scanScreen_heading_withConnector:"{{ CONNECTORNAME }}でスキャンする",scanScreen_tooltip_walletConnect:"[WALLETCONNECTLOGO] WalletConnect 対応の ウォレットを開いてスキャンします",scanScreen_tooltip_default:"携帯電話で {{ CONNECTORNAME }} を 開いてスキャンします",downloadAppScreen_heading:"{{ CONNECTORNAME }} を取得",downloadAppScreen_iosAndroid:"携帯電話のカメラでスキャンして、iOS または Android にダウンロードします。",downloadAppScreen_ios:"携帯電話のカメラでスキャンして、iOS にダウンロードします。",downloadAppScreen_android:"携帯電話のカメラでスキャンして、Android にダウンロードします。",injectionScreen_unavailable_h1:"サポートされていないブラウザ",injectionScreen_unavailable_p:"{{ CONNECTORSHORTNAME }} ウォレットを接続するには、{{ SUGGESTEDEXTENSIONBROWSER }} に拡張機能をインストールします。",injectionScreen_install_h1:"{{ CONNECTORNAME }} をインストール",injectionScreen_install_p:"{{ CONNECTORSHORTNAME }} ウォレットを接続するには、ブラウザ拡張機能をインストールします。",injectionScreen_connecting_h1:"接続を要求",injectionScreen_connecting_p:"{{ CONNECTORSHORTNAME }} ブラウザ拡張機能を 開いて、ウォレットを接続します。",injectionScreen_connecting_injected_h1:"接続を要求",injectionScreen_connecting_injected_p:"このアプリに接続するには、ウォレットを介して要求を受け入れます。",injectionScreen_connected_h1:"すでに接続済み",injectionScreen_connected_p:"このポップアップを閉じてもかまいません",injectionScreen_rejected_h1:"要求がキャンセルされました",injectionScreen_rejected_p:"要求をキャンセルしました。上をクリックしてもう一度お試しください。",injectionScreen_failed_h1:"接続に失敗しました",injectionScreen_failed_p:"申し訳ありませんが、問題が発生しました。もう一度接続してみてください。",injectionScreen_notconnected_h1:"{{ CONNECTORNAME }} にログイン",injectionScreen_notconnected_p:"続行するには、 {{ CONNECTORNAME }} 拡張機能にログインしてください。",profileScreen_heading:"接続されました",switchNetworkScreen_heading:"ネットワークの切り替え",signInWithEthereumScreen_tooltip:`このアプリにサインインしていません。 +続行するには、**イーサリアムでサインイン**してください。`,signInWithEthereumScreen_signedOut_heading:"イーサリアムでサインイン",signInWithEthereumScreen_signedOut_h1:"このアプリは、あなたがこのウォレットの 所有者であることを確認しようとしています。",signInWithEthereumScreen_signedOut_p:"続行するには、ウォレットで メッセージ リクエストに署名してください。",signInWithEthereumScreen_signedOut_button:"サインイン",signInWithEthereumScreen_signedIn_heading:"イーサリアムでサインインしました",signInWithEthereumScreen_signedIn_h1:"このウォレットの所有者であることが 正常に確認されました。",signInWithEthereumScreen_signedIn_p:"サインアウトすると、今後 再度認証する必要があります。",signInWithEthereumScreen_signedIn_button:"サインアウト"};const ptBR={connectWallet:"Conectar carteira",disconnect:"Desconectar",connected:"Conectado",wrongNetwork:"Rede incorreta",switchNetworks:"Alternar rede",chainNetwork:"Rede {{ CHAIN }}",copyToClipboard:"Copiar para a área de transferência",copyCode:"Copiar código",moreInformation:"Mais informações",back:"Voltar",close:"Fechar",or:"ou",more:"Mais",tryAgain:"Tentar novamente",tryAgainQuestion:"Tentar novamente?",dontHaveTheApp:"Não tem o aplicativo?",scanTheQRCode:"Escaneie o código QR",useWalletConnectModal:"Use o modal do WalletConnect",useModal:"Usar modal",installTheExtension:"Instale a extensão",getWalletName:"Obter {{ CONNECTORNAME }}",otherWallets:"Outras carteiras",learnMore:"Saiba mais",getWallet:"Obtenha uma carteira",approveInWallet:"Aprovar na carteira",confirmInWallet:"Confirmar na carteira",awaitingConfirmation:"Aguardando confirmação",signIn:"Entrar",signOut:"Sair",signedIn:"Conectado",signedOut:"Desconectado",walletNotConnected:"Carteira não conectada",warnings_walletSwitchingUnsupported:"A sua carteira não permite a troca de rede a partir deste aplicativo.",warnings_walletSwitchingUnsupportedResolve:"Tente trocar de rede de dentro da sua carteira.",warnings_chainUnsupported:"Este aplicativo não é compatível com a rede conectada.",warnings_chainUnsupportedResolve:"Altere a rede ou desconecte para continuar.",onboardingScreen_heading:"Obtenha uma carteira",onboardingScreen_h1:"Comece a explorar a Web3",onboardingScreen_p:"Sua carteira é a porta de entrada para todas as coisas Ethereum, a tecnologia mágica que torna possível explorar a web3.",onboardingScreen_ctaText:"Escolha sua primeira carteira",onboardingScreen_ctaUrl:"https://ethereum.org/pt-br/wallets/find-wallet/",aboutScreen_heading:"Sobre as carteiras",aboutScreen_a_h1:"Para seus ativos digitais",aboutScreen_a_p:"As carteiras permitem que você envie, receba, armazene e interaja com ativos digitais como NFTs e outros tokens Ethereum.",aboutScreen_b_h1:"Uma maneira melhor de fazer login",aboutScreen_b_p:"Com aplicativos modernos, sua carteira pode ser usada como uma maneira fácil de fazer login, em vez de ter que lembrar uma senha.",aboutScreen_c_h1:"Explore o mundo da Web3",aboutScreen_c_p:"Sua carteira é uma utilidade essencial que permite explorar e participar do mundo em rápida evolução da Web3.",aboutScreen_ctaText:"Saiba mais",aboutScreen_ctaUrl:"https://ethereum.org/pt-br/wallets/",connectorsScreen_heading:"Conectar carteira",connectorsScreen_newcomer:"Eu não tenho uma carteira",connectorsScreen_h1:"O que é uma carteira?",connectorsScreen_p:"As carteiras são usadas para enviar, receber e armazenar ativos digitais. A conexão de uma carteira permite que você interaja com aplicativos.",mobileConnectorsScreen_heading:"Escolha uma carteira",scanScreen_heading:"Escanear com o celular",scanScreen_heading_withConnector:"Escanear com o {{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:`Abra uma carteira compatível +com o WalletConnect [WALLETCONNECTLOGO] para escanear`,scanScreen_tooltip_default:`Abra o {{ CONNECTORNAME }} no +seu celular para escanear`,downloadAppScreen_heading:"Obter {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"Escaneie com a câmera do seu celular para baixar no iOS ou Android.",downloadAppScreen_ios:"Escaneie com a câmera do seu celular para baixar no iOS.",downloadAppScreen_android:"Escaneie com a câmera do seu celular para baixar no Android.",injectionScreen_unavailable_h1:"Navegador não compatível",injectionScreen_unavailable_p:`Para conectar sua carteira {{ CONNECTORSHORTNAME }}, +instale a extensão no {{ SUGGESTEDEXTENSIONBROWSER }}.`,injectionScreen_install_h1:"Instalar {{ CONNECTORNAME }}",injectionScreen_install_p:`Para conectar sua carteira {{ CONNECTORSHORTNAME }}, +instale a extensão do navegador`,injectionScreen_connecting_h1:"Solicitando conexão",injectionScreen_connecting_p:`Abra a extensão do navegador do {{ CONNECTORSHORTNAME }} +para conectar a sua carteira.`,injectionScreen_connecting_injected_h1:"Solicitando conexão",injectionScreen_connecting_injected_p:"Aceite a solicitação por meio de sua carteira para se conectar a este aplicativo.",injectionScreen_connected_h1:"Já conectado",injectionScreen_connected_p:"Agora você já pode fechar esta janela",injectionScreen_rejected_h1:"Solicitação cancelada",injectionScreen_rejected_p:`Você cancelou a solicitação. +Clique acima para tentar novamente.`,injectionScreen_failed_h1:"A conexão falhou",injectionScreen_failed_p:`Desculpe, ocorreu um erro. +Por favor, tente conectar novamente.`,injectionScreen_notconnected_h1:"Faça login no {{ CONNECTORNAME }}",injectionScreen_notconnected_p:"Para continuar, faça login na sua extensão do {{ CONNECTORNAME }}.",profileScreen_heading:"Conectado",switchNetworkScreen_heading:"Alternar rede",signInWithEthereumScreen_tooltip:`Você não está conectado a este aplicativo. +**Entre com Ethereum** para continuar.`,signInWithEthereumScreen_signedOut_heading:"Entrar com Ethereum",signInWithEthereumScreen_signedOut_h1:`Este aplicativo gostaria de verificar você + como o proprietário desta carteira.`,signInWithEthereumScreen_signedOut_p:`Por favor, assine o pedido de mensagem + em sua carteira para continuar.`,signInWithEthereumScreen_signedOut_button:"Entrar",signInWithEthereumScreen_signedIn_heading:"Conectado com Ethereum",signInWithEthereumScreen_signedIn_h1:`Você se verificou com sucesso + como o proprietário desta carteira`,signInWithEthereumScreen_signedIn_p:`Se sair, será necessário que você + autentique novamente no futuro.`,signInWithEthereumScreen_signedIn_button:"Sair"},ruRU={connectWallet:"Подключить кошелек",disconnect:"Отключить",connected:"Подключена",wrongNetwork:"Неверная сеть",switchNetworks:"Переключение сети",chainNetwork:"Сеть {{ CHAIN }}",copyToClipboard:"Скопировать в буфер обмена",copyCode:"Скопировать код",moreInformation:"Больше информации",back:"Назад",close:"Закрыть",or:"или",more:"Еще",tryAgain:"Попробовать снова",tryAgainQuestion:"Попробовать снова?",dontHaveTheApp:"У вас нет приложения?",scanTheQRCode:"Отсканируйте QR-код",useWalletConnectModal:"Использовать окно WalletConnect",useModal:"Использовать модальное окно",installTheExtension:"Установить расширение",getWalletName:"Скачать {{ CONNECTORNAME }}",otherWallets:"Другие кошельки",learnMore:"Узнать больше",getWallet:"Завести кошелек",approveInWallet:"Подтвердите",confirmInWallet:"Подтвердите",awaitingConfirmation:"Ожидаем подтверждение",signIn:"Войти",signOut:"Выйти",signedIn:"Вошли",signedOut:"Вышли",walletNotConnected:"Кошелек не подключен",warnings_walletSwitchingUnsupported:"Ваш кошелек не поддерживает переключение сетей из этого приложения.",warnings_walletSwitchingUnsupportedResolve:"Попробуйте переключиться на другую сеть прямо в вашем кошельке.",warnings_chainUnsupported:"Это приложение не поддерживает текущую подключенную сеть.",warnings_chainUnsupportedResolve:"Для продолжения переключите сеть или отключите кошелек.",onboardingScreen_heading:"Завести кошелек",onboardingScreen_h1:"Начните исследовать веб3",onboardingScreen_p:"Ваш кошелек — это врата в мир Ethereum, волшебной технологии, которая позволяет исследовать веб3.",onboardingScreen_ctaText:"Выбрать свой первый кошелек",onboardingScreen_ctaUrl:"https://ethereum.org/en/wallets/find-wallet/",aboutScreen_heading:"О кошельках",aboutScreen_a_h1:"Для ваших цифровых активов",aboutScreen_a_p:"Кошельки позволяют вам отправлять, получать, хранить и взаимодействовать с цифровыми активами, такими как NFT и другие токены Ethereum.",aboutScreen_b_h1:"Лучший способ входа",aboutScreen_b_p:"В современных приложениях ваш кошелек можно использовать как удобный способ входа без необходимости помнить пароль.",aboutScreen_c_h1:"Исследуйте мир веб3",aboutScreen_c_p:"Ваш кошелек - это неотъемлемый инструмент, который позволяет вам исследовать и участвовать в быстро развивающемся мире веб3.",aboutScreen_ctaText:"Узнать больше",aboutScreen_ctaUrl:"https://ethereum.org/en/wallets/",connectorsScreen_heading:"Подключение кошелька",connectorsScreen_newcomer:"У меня нет кошелька",connectorsScreen_h1:"Что такое кошелек?",connectorsScreen_p:"Кошельки используются для отправки, получения и хранения цифровых активов. Подключение кошелька позволяет вам взаимодействовать с приложениями.",mobileConnectorsScreen_heading:"Выберите кошелек",scanScreen_heading:"Сканирование с телефона",scanScreen_heading_withConnector:"Сканирование с помощью {{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:"Откройте [WALLETCONNECTLOGO] поддерживаемый WalletConnect кошелек для сканирования",scanScreen_tooltip_default:"Откройте {{ CONNECTORNAME }} на вашем мобильном телефоне для сканирования",downloadAppScreen_heading:"Скачивание {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"Отсканируйте камерой телефона для загрузки приложения на iOS или Android.",downloadAppScreen_ios:"Отсканируйте камерой телефона для загрузки приложения на iOS.",downloadAppScreen_android:"Сканируйте камерой телефона для загрузки приложения на Android.",injectionScreen_unavailable_h1:"Неподдерживаемый браузер",injectionScreen_unavailable_p:"Для подключения вашего кошелька {{ CONNECTORSHORTNAME }}, установите расширение для браузера {{ SUGGESTEDEXTENSIONBROWSER }}.",injectionScreen_install_h1:"Установите {{ CONNECTORNAME }}",injectionScreen_install_p:"Для подключения вашего кошелька {{ CONNECTORSHORTNAME }}, установите расширение для браузера.",injectionScreen_connecting_h1:"Запрос на подключение",injectionScreen_connecting_p:"Откройте расширение для браузера {{ CONNECTORSHORTNAME }} для подключения вашего кошелька.",injectionScreen_connecting_injected_h1:"Запрос на подключение",injectionScreen_connecting_injected_p:"Примите запрос в вашем кошельке, чтобы подключиться к приложению.",injectionScreen_connected_h1:"Уже подключен",injectionScreen_connected_p:"Можно закрыть это окно",injectionScreen_rejected_h1:"Запрос отменен",injectionScreen_rejected_p:`Вы отменили запрос. +Нажмите выше, чтобы попробовать снова.`,injectionScreen_failed_h1:"Сбой подключения",injectionScreen_failed_p:`Извините, что-то пошло не так. +Пожалуйста, попробуйте подключиться снова.`,injectionScreen_notconnected_h1:"Войдите в {{ CONNECTORNAME }}",injectionScreen_notconnected_p:"Для продолжения войдите в расширение {{ CONNECTORNAME }}.",profileScreen_heading:"Кошелек подключен",switchNetworkScreen_heading:"Переключение сетей",signInWithEthereumScreen_tooltip:`Вы не вошли в это приложение. +**Войдите с помощью Ethereum**, чтобы продолжить.`,signInWithEthereumScreen_signedOut_heading:"Войти с помощью Ethereum",signInWithEthereumScreen_signedOut_h1:`Это приложение хочет подтвердить вас + в качестве владельца этого кошелька.`,signInWithEthereumScreen_signedOut_p:`Пожалуйста, подпишите запрос на сообщение + в своем кошельке, чтобы продолжить.`,signInWithEthereumScreen_signedOut_button:"Войти",signInWithEthereumScreen_signedIn_heading:"Вошли с помощью Ethereum",signInWithEthereumScreen_signedIn_h1:`Вы успешно подтвердили себя + в качестве владельца этого кошелька.`,signInWithEthereumScreen_signedIn_p:`Выйти потребуется + повторная аутентификация в будущем.`,signInWithEthereumScreen_signedIn_button:"Выйти"},zhCN={connectWallet:"绑定钱包",disconnect:"解除绑定",connected:"已绑定",wrongNetwork:"错误网络",switchNetworks:"切换网络",chainNetwork:"{{ CHAIN }}网络",copyToClipboard:"复制到剪贴板",copyCode:"复制代码",moreInformation:"更多信息",back:"返回",close:"关闭",or:"或",more:"更多",tryAgain:"重试",tryAgainQuestion:"重试?",dontHaveTheApp:"没有该应用?",scanTheQRCode:"扫描二维码",useWalletConnectModal:"使用 WalletConnect 模态窗",useModal:"使用模态窗",installTheExtension:"安装扩展程序",getWalletName:"获取{{ CONNECTORNAME }}",otherWallets:"其他钱包",learnMore:"了解更多",getWallet:"获取钱包",approveInWallet:"在钱包中批准",confirmInWallet:"在钱包中确认",awaitingConfirmation:"等待确认",signIn:"登录",signOut:"登出",signedIn:"已登录",signedOut:"已登出",walletNotConnected:"钱包未绑定",warnings_walletSwitchingUnsupported:"您的钱包不支持从此应用切换网络。",warnings_walletSwitchingUnsupportedResolve:"请尝试从钱包中切换网络。",warnings_chainUnsupported:"此应用不支持当前连接的网络。",warnings_chainUnsupportedResolve:"请切换网络或断开连接以继续。",onboardingScreen_heading:"获取钱包",onboardingScreen_h1:"开始探索 Web3",onboardingScreen_p:"您的钱包是通往以太坊的一扇大门,而以太坊是探索 Web3 的一项神奇技术。",onboardingScreen_ctaText:"选择您的第一钱包",onboardingScreen_ctaUrl:"https://ethereum.org/zh/wallets/find-wallet/",aboutScreen_heading:"关于钱包",aboutScreen_a_h1:"对于您的数字资产",aboutScreen_a_p:"有了钱包,您可以发送、接收、存储数字资产及使用数字资产进行交互,例如 NFT 和其他以太坊通证等。",aboutScreen_b_h1:"更好的登录方式",aboutScreen_b_p:"使用现代应用,您的钱包可以用作简便的登录方法,而不必记住密码。",aboutScreen_c_h1:"探索 Web3 世界",aboutScreen_c_p:"您的钱包是一个重要的工具,可以让您探索并参与到快速发展的 Web3 世界。",aboutScreen_ctaText:"了解更多",aboutScreen_ctaUrl:"https://ethereum.org/zh/wallets/",connectorsScreen_heading:"绑定钱包",connectorsScreen_newcomer:"我没有钱包",connectorsScreen_h1:"什么是钱包?",connectorsScreen_p:"钱包可用于发送、接收和存储数字资产。通过绑定钱包,您可以与应用进行交互。",mobileConnectorsScreen_heading:"选择钱包",scanScreen_heading:"手机扫描",scanScreen_heading_withConnector:"手机扫描{{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:"打开 [WALLETCONNECTLOGO] WalletConnect 支持的钱包进行扫描",scanScreen_tooltip_default:"打开您手机上的{{ CONNECTORNAME }} 进行扫描",downloadAppScreen_heading:"获取{{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"使用手机相机扫描以下载 iOS 或 Android 应用。",downloadAppScreen_ios:"使用手机相机扫描以下载 iOS 应用。",downloadAppScreen_android:"使用手机相机扫描以下载 Android 应用。",injectionScreen_unavailable_h1:"不支持的浏览器",injectionScreen_unavailable_p:"要绑定您的{{ CONNECTORSHORTNAME }}钱包,请在{{ SUGGESTEDEXTENSIONBROWSER }}上安装此扩展程序。",injectionScreen_install_h1:"安装{{ CONNECTORNAME }}",injectionScreen_install_p:"要绑定您的{{ CONNECTORSHORTNAME }}钱包,请安装此浏览器扩展程序。",injectionScreen_connecting_h1:"请求绑定",injectionScreen_connecting_p:"打开{{ CONNECTORSHORTNAME }}浏览器 扩展程序以绑定您的钱包。",injectionScreen_connecting_injected_h1:"请求绑定",injectionScreen_connecting_injected_p:"通过您的钱包接受请求,以绑定到此应用。",injectionScreen_connected_h1:"已绑定",injectionScreen_connected_p:"现在可以关闭此弹窗",injectionScreen_rejected_h1:"请求已取消",injectionScreen_rejected_p:"您已取消请求。点击上面可重试。",injectionScreen_failed_h1:"绑定失败",injectionScreen_failed_p:"抱歉,发生错误。请尝试重新绑定。",injectionScreen_notconnected_h1:"登录{{ CONNECTORNAME }}",injectionScreen_notconnected_p:"要继续,请登录到您的{{ CONNECTORNAME }}扩展程序。",profileScreen_heading:"已绑定",switchNetworkScreen_heading:"切换网络",signInWithEthereumScreen_tooltip:`您尚未登录到此应用。 +请选择**使用以太坊登录**以继续。`,signInWithEthereumScreen_signedOut_heading:"使用以太坊登录",signInWithEthereumScreen_signedOut_h1:"此应用希望验证您是 此钱包的所有者。",signInWithEthereumScreen_signedOut_p:"请签署钱包中的消息请求 以继续。",signInWithEthereumScreen_signedOut_button:"登录",signInWithEthereumScreen_signedIn_heading:"已使用以太坊登录",signInWithEthereumScreen_signedIn_h1:"您已成功验证自己 是此钱包的所有者。",signInWithEthereumScreen_signedIn_p:"登出后,将来您还需要 再次进行身份验证。",signInWithEthereumScreen_signedIn_button:"登出"},caAD={connectWallet:"Connecta la cartera",disconnect:"Desconnectar",connected:"Connectat",wrongNetwork:"Xarxa incorrecta",switchNetworks:"Canvi de xarxa",chainNetwork:"Xarxa {{ CHAIN }}",copyToClipboard:"Copia al portapapers",copyCode:"Copia codi",moreInformation:"Més informació",back:"Enrere",close:"Tanca",or:"o",more:"Més",tryAgain:"Torna-ho a intentar",tryAgainQuestion:"Tornar a intentar-ho?",dontHaveTheApp:"No tens l'aplicació?",scanTheQRCode:"Escaneja el codi QR",useWalletConnectModal:"Utilitza WalletConnect Modal",useModal:"Utilitza Modal",installTheExtension:"Instal·la l'extensió",getWalletName:"Obté {{ CONNECTORNAME }}",otherWallets:"Altres carteres",learnMore:"Més informació",getWallet:"Obté una cartera",approveInWallet:"Aprova a la cartera",confirmInWallet:"Confirma a la cartera",awaitingConfirmation:"Esperant confirmació",signIn:"Inicia sessió",signOut:"Tanca sessió",signedIn:"Sessió iniciada",signedOut:"Sessió tancada",walletNotConnected:"Cartera no connectada",warnings_walletSwitchingUnsupported:"La teva cartera no permet canviar de xarxa des d'aquesta aplicació.",warnings_walletSwitchingUnsupportedResolve:"Prova a canviar de xarxa des de la teva cartera.",warnings_chainUnsupported:"Aquesta aplicació no és compatible amb la xarxa connectada actualment.",warnings_chainUnsupportedResolve:"Canvia o desconnecta per continuar.",onboardingScreen_heading:"Obté una cartera",onboardingScreen_h1:"Comença a explorar la Web3",onboardingScreen_p:"La teva cartera és el portal d'accés a tot el relacionat amb Ethereum, la tecnologia màgica que permet explorar la Web3.",onboardingScreen_ctaText:"Tria la teva primera cartera",onboardingScreen_ctaUrl:"https://ethereum.org/es/wallets/find-wallet/",aboutScreen_heading:"Sobre les carteres",aboutScreen_a_h1:"Per als teus actius digitals",aboutScreen_a_p:"Les carteres et permeten enviar, rebre, emmagatzemar i interactuar amb actius digitals com els NFT i altres tokens d'Ethereum.",aboutScreen_b_h1:"Una manera millor d'iniciar sessió",aboutScreen_b_p:"Amb les aplicacions modernes, pots utilitzar la teva cartera per iniciar sessió fàcilment, en lloc de haver de recordar una contrasenya.",aboutScreen_c_h1:"Explora el món de la Web3",aboutScreen_c_p:"La teva cartera és una eina essencial que et permet explorar i participar en el món en ràpida evolució de la Web3.",aboutScreen_ctaText:"Més informació",aboutScreen_ctaUrl:"https://ethereum.org/es/wallets/",connectorsScreen_heading:"Connecta una cartera",connectorsScreen_newcomer:"No tinc una cartera",connectorsScreen_h1:"Què és una cartera?",connectorsScreen_p:"Les carteres s'utilitzen per enviar, rebre i emmagatzemar actius digitals. Si connectes una cartera, podràs interactuar amb les aplicacions.",mobileConnectorsScreen_heading:"Tria una cartera",scanScreen_heading:"Escaneja amb el telèfon",scanScreen_heading_withConnector:"Escaneja amb {{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:"Obre una cartera compatible amb WalletConnect [WALLETCONNECTLOGO] per escanejar",scanScreen_tooltip_default:"Obre {{ CONNECTORNAME }} en el teu telèfon mòbil per escanejar",downloadAppScreen_heading:"Obté {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"Escaneja amb la càmera del teu telèfon per descarregar-la en iOS o Android.",downloadAppScreen_ios:"Escaneja amb la càmera del teu telèfon per descarregar-la en iOS.",downloadAppScreen_android:"Escaneja amb la càmera del teu telèfon per descarregar-la en Android.",injectionScreen_unavailable_h1:"Navegador no compatible",injectionScreen_unavailable_p:"Per connectar la teva cartera de {{ CONNECTORSHORTNAME }}, instal·la l'extensió en {{ SUGGESTEDEXTENSIONBROWSER }}.",injectionScreen_install_h1:"Instal·la {{ CONNECTORNAME }}",injectionScreen_install_p:"Per connectar la teva cartera de {{ CONNECTORSHORTNAME }}, instal·la l'extensió del navegador.",injectionScreen_connecting_h1:"Sol·licitud de connexió",injectionScreen_connecting_p:"Obre l'extensió del navegador de {{ CONNECTORSHORTNAME }} per connectar la teva cartera.",injectionScreen_connecting_injected_h1:"Sol·licitud de connexió",injectionScreen_connecting_injected_p:"Accepta la sol·licitud a través de la teva cartera per connectar-te a aquesta aplicació.",injectionScreen_connected_h1:"Ja connectada",injectionScreen_connected_p:"Ja pots tancar aquesta finestra emergent",injectionScreen_rejected_h1:"Sol·licitud cancel·lada",injectionScreen_rejected_p:"Has cancel·lat la sol·licitud. Fes clic a dalt per tornar-ho a intentar.",injectionScreen_failed_h1:"Error de connexió",injectionScreen_failed_p:"Ho sentim, hi ha hagut un problema. Intenta connectar-te de nou.",injectionScreen_notconnected_h1:"Inicia sessió en {{ CONNECTORNAME }}",injectionScreen_notconnected_p:"Per continuar, inicia sessió en la teva extensió de {{ CONNECTORNAME }}.",profileScreen_heading:"Connectat",switchNetworkScreen_heading:"Canvi de xarxa",signInWithEthereumScreen_tooltip:`No has iniciat sessió en aquesta aplicació. +**Inicia sessió amb Ethereum** per continuar.`,signInWithEthereumScreen_signedOut_heading:"Inicia sessió amb Ethereum",signInWithEthereumScreen_signedOut_h1:"Aquesta aplicació vol verificar que ets el propietari d'aquesta cartera.",signInWithEthereumScreen_signedOut_p:"Signa la sol·licitud de missatge en la teva cartera per continuar.",signInWithEthereumScreen_signedOut_button:"Inicia sessió",signInWithEthereumScreen_signedIn_heading:"Sessió iniciada amb Ethereum",signInWithEthereumScreen_signedIn_h1:"T'has verificat correctament com a propietari d'aquesta cartera.",signInWithEthereumScreen_signedIn_p:"Si tanques la sessió, hauràs de tornar a autenticar-te més endavant.",signInWithEthereumScreen_signedIn_button:"Tanca sessió"},trTR={connectWallet:"Cüzdan Bağla",disconnect:"Bağlantıyı Kes",connected:"Bağlandı",wrongNetwork:"Yanlış Ağ",switchNetworks:"Ağ Değiştir",chainNetwork:"{{ CHAIN }} Ağı",copyToClipboard:"Panoya Kopyala",copyCode:"Kodu Kopyala",moreInformation:"Daha Fazla Bilgi",back:"Geri",close:"Kapat",or:"veya",more:"Daha Fazla",tryAgain:"Tekrar Dene",tryAgainQuestion:"Tekrar Dene?",dontHaveTheApp:"Uygulaman yok mu?",scanTheQRCode:"Karekodu tarat",useWalletConnectModal:"WalletConnect Modalini Kullan ",useModal:"Modal Kullan",installTheExtension:"Eklentiyi İndir",getWalletName:"{{ CONNECTORNAME }} Alın",otherWallets:"Diğer Cüzdanlar",learnMore:"Daha Fazlasını Öğren",getWallet:"Cüzdan Al",approveInWallet:"Cüzdanda Yetki Ver",confirmInWallet:"Cüzdanda Onayla",awaitingConfirmation:"Doğrulama Bekleniyor",signIn:"Giriş Yap",signOut:"Çıkış Yap",signedIn:"Giriş Yapıldı",signedOut:"Çıkış Yapıldı",walletNotConnected:"Cüzdan Bağlı Değil",warnings_walletSwitchingUnsupported:"Bu uygulamada ağ değiştirmeyi cüzdanın desteklemiyor.",warnings_walletSwitchingUnsupportedResolve:"Bunun yerine cüzdanınızdan ağları değiştirmeyi deneyin.",warnings_chainUnsupported:"Bu uygulama kullanmış olduğunuz ağı desteklemiyor.",warnings_chainUnsupportedResolve:"Devam etmek için ağ değiştir veya bağlantıyı kes.",onboardingScreen_heading:"Cüzdan Al",onboardingScreen_h1:"Web3'ü keşfetmeye başla",onboardingScreen_p:"Cüzdanınız, Web3'ü keşfetmeyi mümkün kılan sihirli teknoloji olan Ethereum'a açılan kapıdır.",onboardingScreen_ctaText:"İlk Cüzdanını Seç",onboardingScreen_ctaUrl:"https://ethereum.org/tr/wallets/find-wallet/",aboutScreen_heading:"Cüzdanlar Hakkında",aboutScreen_a_h1:"Dijital varlıkların için",aboutScreen_a_p:"Cüzdanlar, NFT'ler ve diğer Ethereum varlıkları gibi dijital varlıklar göndermenize, almanıza, saklamanıza ve bunlarla etkileşim kurmanıza olanak tanır.",aboutScreen_b_h1:"Giriş yapmanın daha iyi bir yolu",aboutScreen_b_p:"Modern uygulamalar ile parola hatırlamak yerine cüzdanınız ile kolayca giriş yapabilirsiniz.",aboutScreen_c_h1:"Web3 dünyasını keşfet",aboutScreen_c_p:"Cüzdanınız, hızla gelişen Web3 dünyasını keşfetmenizi ve bu dünyaya katılmanızı sağlayan temel bir yardımcı programdır.",aboutScreen_ctaText:"Daha Fazlasını Öğren",aboutScreen_ctaUrl:"https://ethereum.org/tr/wallets/",connectorsScreen_heading:"Cüzdan Bağla",connectorsScreen_newcomer:"Cüzdanım Yok",connectorsScreen_h1:"Cüzdan nedir?",connectorsScreen_p:"Cüzdanlar, dijital varlıkları göndermek, almak ve depolamak için kullanılır. Bir cüzdanı bağlamak, uygulamalarla etkileşime geçmenizi sağlar.",mobileConnectorsScreen_heading:"Cüzdan Seç",scanScreen_heading:"Telefon ile Tarat",scanScreen_heading_withConnector:"{{ CONNECTORNAME }} ile tarat",scanScreen_tooltip_walletConnect:`Desteklenen bir cüzdan taramak için + [WALLETCONNECTLOGO] WalletConnect uygulamasını aç`,scanScreen_tooltip_default:`Taramak için telefonunda + {{ CONNECTORNAME }} uygulamasını aç`,downloadAppScreen_heading:"{{ CONNECTORNAME }} İndir",downloadAppScreen_iosAndroid:"iOS ve Android'e indirmek için telefon kameran ile tarat.",downloadAppScreen_ios:"iOS'a indirmek için telefon kameran ile tarat.",downloadAppScreen_android:"Android'e indirmek için telefon kameran ile tarat.",injectionScreen_unavailable_h1:"Desteklenmeyen Tarayıcı",injectionScreen_unavailable_p:`{{ CONNECTORSHORTNAME }} cüzdanına bağlanmak için +{{ SUGGESTEDEXTENSIONBROWSER }} üzerinde indirmen gerekiyor.`,injectionScreen_install_h1:"{{ CONNECTORNAME }} İndir",injectionScreen_install_p:`{{ CONNECTORSHORTNAME }} cüzdanına bağlanmak için, +tarayıcı eklentisini indir.`,injectionScreen_connecting_h1:"Bağlantı İsteniyor.",injectionScreen_connecting_p:`Cüzdanını bağlamak için + tarayıcıdan {{ CONNECTORSHORTNAME }} uzantısını açın.`,injectionScreen_connecting_injected_h1:"Bağlantı İsteniyor.",injectionScreen_connecting_injected_p:"Bu uygulamaya bağlanmak için cüzdanına gelen isteği kabul et.",injectionScreen_connected_h1:"Zaten Bağlanmış",injectionScreen_connected_p:"Bu açılır pencereyi artık kapatabilirsin",injectionScreen_rejected_h1:"İstek iptal edildi.",injectionScreen_rejected_p:`İsteği iptal ettin. +Tekrar denemek için yukarıyı tıklayın.`,injectionScreen_failed_h1:"Bağlantı Başarısız",injectionScreen_failed_p:`Üzgünüz, bir şeyler ters gitti. +Lütfen daha sonra tekrar deneyin.`,injectionScreen_notconnected_h1:"{{ CONNECTORNAME }} ile giriş yap",injectionScreen_notconnected_p:"Devam etmek için, {{ CONNECTORNAME }} eklentisine giriş yapın.",profileScreen_heading:"Bağlandı",switchNetworkScreen_heading:"Ağ Değiştir",signInWithEthereumScreen_tooltip:`Bu uygulamada oturum açmadınız. + Devam etmek için **Ethereum İle Giriş Yap**.`,signInWithEthereumScreen_signedOut_heading:"Ethereum İle Giriş Yap",signInWithEthereumScreen_signedOut_h1:`Bu uygulama seni + bu cüzdanın sahibi olarak doğrulamak istiyor.`,signInWithEthereumScreen_signedOut_p:`Devam etmek için + cüzdanınızdaki isteği onaylayın.`,signInWithEthereumScreen_signedOut_button:"Giriş Yap",signInWithEthereumScreen_signedIn_heading:"Ethereum İle Giriş Yapıldı",signInWithEthereumScreen_signedIn_h1:`Bu cüzdanın sahibi olduğunu + başarıyla onayladın.`,signInWithEthereumScreen_signedIn_p:`Çıkış yaparsan ileride + tekrar giriş yapman gerekecek. `,signInWithEthereumScreen_signedIn_button:"Çıkış Yap"},viVN={connectWallet:"Kết nối ví",disconnect:"Ngắt kết nối",connected:"Đã kết nối",wrongNetwork:"Mạng không hỗ trợ",switchNetworks:"Đổi mạng",chainNetwork:"Mạng {{ CHAIN }}",copyToClipboard:"Sao chép",copyCode:"Sao chép mã",moreInformation:"Thêm thông tin",back:"Quay lại",close:"Đóng",or:"hoặc",more:"Thêm",tryAgain:"Thử lại",tryAgainQuestion:"Thử lại?",dontHaveTheApp:"Không có app?",scanTheQRCode:"Quét mã QR",useWalletConnectModal:"Dùng WalletConnect Modal",useModal:"Dùng Modal",installTheExtension:"Cài tiện ích",getWalletName:"Lấy {{ CONNECTORNAME }}",otherWallets:"Các ví khác",learnMore:"Xem thêm",getWallet:"Tạo một ví",approveInWallet:"Cấp quyền trong ví",confirmInWallet:"Xác nhận trong ví",awaitingConfirmation:"Đang chờ xác nhận",signIn:"Đăng nhập",signOut:"Đăng xuất",signedIn:"Đã đăng nhập",signedOut:"Đã đăng xuất",walletNotConnected:"Chưa kết nối ví",warnings_walletSwitchingUnsupported:"Ví của bạn không hỗ trợ đổi mạng từ ứng dụng.",warnings_walletSwitchingUnsupportedResolve:"Hãy thử đổi mạng từ phía ví của bạn.",warnings_chainUnsupported:"Ứng dụng này không hỗ trợ mạng hiện tại.",warnings_chainUnsupportedResolve:"Đổi hoặc ngắt kết nối để tiếp tục.",onboardingScreen_heading:"Tạo một ví",onboardingScreen_h1:"Bắt đầu khám khá Web3",onboardingScreen_p:"Ví của bạn là cổng giao tiếp mọi thứ trên Ethereum, công nghệ tuyệt vời giúp khám phá Web3.",onboardingScreen_ctaText:"Chọn ví đầu tiên của bạn",onboardingScreen_ctaUrl:"https://ethereum.org/en/wallets/find-wallet/",aboutScreen_heading:"Giới thiệu các ví",aboutScreen_a_h1:"Cho tài sản số của bạn",aboutScreen_a_p:"Các ví để bạn gửi, nhận, lưu trữ, và tương tác với các tài sản điện tử như NFTs và các loại tiền Ethereum khác.",aboutScreen_b_h1:"Một cách tốt hơn để đăng nhập",aboutScreen_b_p:"Với các ứng dụng hiện đại, ví của bạn có thể dùng để đăng nhập dễ dàng thay vì phải nhớ tài khoản và mật khẩu.",aboutScreen_c_h1:"Khám phá thế giới Web3",aboutScreen_c_p:"Ví của bạn là một tiện ích thiết yếu cho phép bạn khám phá và tham gia vào thế giới web3 đang phát triển nhanh chóng.",aboutScreen_ctaText:"Tìm hiểu thêm",aboutScreen_ctaUrl:"https://ethereum.org/en/wallets/",connectorsScreen_heading:"Kết nối Ví",connectorsScreen_newcomer:"Tôi chưa có ví",connectorsScreen_h1:"Ví là gì?",connectorsScreen_p:"Ví dùng để gửi, nhận, và lưu trữ các tài sản điện tử. Kết nối với một ví giúp bạn tương tác với các ứng dụng.",mobileConnectorsScreen_heading:"Chọn ví",scanScreen_heading:"Scan bằng điện thoại",scanScreen_heading_withConnector:"Quét với {{ CONNECTORNAME }}",scanScreen_tooltip_walletConnect:`Mở một [WALLETCONNECTLOGO] mà WalletConnect + hỗ trợ để quét`,scanScreen_tooltip_default:`Mở {{ CONNECTORNAME }} trong +điện thoại của bạn để quét`,downloadAppScreen_heading:"Lấy {{ CONNECTORNAME }}",downloadAppScreen_iosAndroid:"Quét bằng camera trên điện thoại của bạn để tải về cho iOS hoặc Android.",downloadAppScreen_ios:"Quét bằng camera trên điện thoại ủa bạn để tải về cho iOS.",downloadAppScreen_android:"Quét bằng camera trên điện thoại ủa bạn để tải về cho Android.",injectionScreen_unavailable_h1:"Trình duyệt không được hỗ trợ",injectionScreen_unavailable_p:`Để kết nối ví {{ CONNECTORSHORTNAME }} của bạn, +cài đặt tiện ích trên {{ SUGGESTEDEXTENSIONBROWSER }}.`,injectionScreen_install_h1:"Cài {{ CONNECTORNAME }}",injectionScreen_install_p:`Để kết nối ví {{ CONNECTORSHORTNAME }}, +cài đặt tiện ích trên trình duyệt.`,injectionScreen_connecting_h1:"Đang yêu cầu kết nối",injectionScreen_connecting_p:`Mở tiện ích {{ CONNECTORSHORTNAME }} + trên trình duyệt để kết nối.`,injectionScreen_connecting_injected_h1:"Đang yêu cầu kết nối",injectionScreen_connecting_injected_p:"Đồng ý yêu cầu từ phía ví của bạn để kết nối ứng dụng này.",injectionScreen_connected_h1:"Đã kết nối",injectionScreen_connected_p:"Đã có thể đóng popup",injectionScreen_rejected_h1:"Đã hủy yêu cầu",injectionScreen_rejected_p:`Bạn vừa hủy yêu cầu. +Nhấn phía trên để thử lại.`,injectionScreen_failed_h1:"Kết nối không thành công",injectionScreen_failed_p:`Xin lỗi, có gì đó không đúng. +Vui lòng thử lại.`,injectionScreen_notconnected_h1:"Đăng nhập vào {{ CONNECTORNAME }}",injectionScreen_notconnected_p:"Để tiếp tục, vui lòng đăng nhập bằng tiện ích {{ CONNECTORNAME }}.",profileScreen_heading:"Đã kết nối",switchNetworkScreen_heading:"Đổi mạng",signInWithEthereumScreen_tooltip:`Bạn chưa đăng nhập vào ứng dụng. +**Đăng nhập qua Ethereum** để tiếp tục.`,signInWithEthereumScreen_signedOut_heading:"Đăng nhập qua Ethereum",signInWithEthereumScreen_signedOut_h1:`Ứng dụng này muốn xác nhận bạn + là chủ sở hữu của ví.`,signInWithEthereumScreen_signedOut_p:`Vui lòng ký tin nhắn yêu cầu + trên ví của bạn để tiếp tục.`,signInWithEthereumScreen_signedOut_button:"Đăng nhập",signInWithEthereumScreen_signedIn_heading:"Đăng nhập qua Ethereum",signInWithEthereumScreen_signedIn_h1:"Bạn đã xác nhận thành công.",signInWithEthereumScreen_signedIn_p:`Sau khi Đăng xuất bạn sẽ cần + xác nhận lại trong làn tiếp theo.`,signInWithEthereumScreen_signedIn_button:"Đăng xuất"},getLocale=et=>{switch(et){case"ee-EE":return eeEE;case"ar-AE":return arAE;case"es-ES":return esES;case"fa-IR":return faIR;case"fr-FR":return frFR;case"ja-JP":return jaJP;case"pt-BR":return ptBR;case"ru-RU":return ruRU;case"zh-CN":return zhCN;case"ca-AD":return caAD;case"tr-TR":return trTR;case"vi-VN":return viVN;default:return enUS}};function useLocales(et){var o,tt;const nt=(tt=(o=useContext().options)===null||o===void 0?void 0:o.language)!==null&&tt!==void 0?tt:"en-US",ot=reactExports.useMemo(()=>getLocale(nt),[nt]);if(!ot)return console.error(`Missing translations for: ${nt}`),`Missing translations for: ${nt}`;const it={};return Object.keys(ot).map(st=>{const at=ot[st];return it[st]=localize(at,et)}),it}const localize=(et,o)=>{let tt=et;return o&&Object.keys(o).forEach(rt=>{tt=tt.replace(new RegExp(`({{ ${rt} }})`,"g"),o[rt])}),replaceMarkdown(tt)},replaceMarkdown=et=>{let o=et;return o=o.split(` +`),o=o.map((tt,rt)=>jsxRuntimeExports.jsxs(React.Fragment,{children:[wrapTags(tt),rtet.split(/(\*\*[^\*]*\*\*)/g).map((rt,nt)=>/(\*\*.*\*\*)/g.test(rt)?jsxRuntimeExports.jsx("strong",{children:rt.replace(/\*\*/g,"")},nt):`${rt}`).map(rt=>typeof rt=="string"?rt.split(/(\[WALLETCONNECTLOGO\])/g).map(nt=>nt==="[WALLETCONNECTLOGO]"?jsxRuntimeExports.jsx("span",{className:"ck-tt-logo",children:jsxRuntimeExports.jsx(Logos.WalletConnect,{})},nt):nt):rt),LOG_LEVEL={debug:10,info:20,warn:30,error:40,none:100},useIsoLayoutEffect=typeof window<"u"&&window.document&&window.document.createElement!==void 0?reactExports.useLayoutEffect:reactExports.useEffect,useFitText=({logLevel:et="info",maxFontSize:o=100,minFontSize:tt=20,onFinish:rt,onStart:nt,resolution:ot=5}={})=>{const it=LOG_LEVEL[et],st=reactExports.useCallback(()=>({calcKey:0,fontSize:o,fontSizePrev:tt,fontSizeMax:o,fontSizeMin:tt}),[o,tt]),at=reactExports.useRef(null),ct=reactExports.useRef(),lt=reactExports.useRef(!1),[dt,ht]=reactExports.useState(st),{calcKey:mt,fontSize:ft,fontSizeMax:pt,fontSizeMin:gt,fontSizePrev:yt}=dt;let bt=null;const[xt]=reactExports.useState(()=>new index$1(()=>{bt=window.requestAnimationFrame(()=>{lt.current||(nt&&nt(),lt.current=!0,ht({...st(),calcKey:mt+1}))})}));reactExports.useEffect(()=>(at.current&&xt.observe(at.current),()=>{bt&&window.cancelAnimationFrame(bt),xt.disconnect()}),[bt,xt]);const vt=at.current&&at.current.innerHTML;return reactExports.useEffect(()=>{mt===0||lt.current||(vt!==ct.current&&(nt&&nt(),ht({...st(),calcKey:mt+1})),ct.current=vt)},[mt,st,vt,nt]),useIsoLayoutEffect(()=>{if(mt===0)return;const Et=Math.abs(ft-yt)<=ot,Ct=!!at.current&&(at.current.scrollHeight>at.current.offsetHeight||at.current.scrollWidth>at.current.offsetWidth),St=Ct&&ft===yt,At=ft>yt;if(Et){St?(lt.current=!1,it<=LOG_LEVEL.info&&console.info(`[use-fit-text] reached \`minFontSize = ${tt}\` without fitting text`)):Ct?ht({fontSize:At?yt:gt,fontSizeMax:pt,fontSizeMin:gt,fontSizePrev:yt,calcKey:mt}):(lt.current=!1,rt&&rt(ft));return}let kt,It=pt,Ot=gt;Ct?(kt=At?yt-ft:gt-ft,It=Math.min(pt,ft)):(kt=At?pt-ft:yt-ft,Ot=Math.max(gt,ft)),ht({calcKey:mt,fontSize:ft+kt/2,fontSizeMax:It,fontSizeMin:Ot,fontSizePrev:ft})},[mt,ft,pt,gt,yt,rt,at,ot]),{fontSize:ft,ref:at}},FitText=({children:et})=>{const[o,tt]=React.useState(!1),{fontSize:rt,ref:nt}=useFitText({logLevel:"none",maxFontSize:100,minFontSize:70,onStart:()=>tt(!0),onFinish:()=>tt(!0)});return jsxRuntimeExports.jsx("div",{ref:nt,style:{visibility:o?"visible":"hidden",fontSize:`${rt}%`,maxHeight:"100%",maxWidth:"100%",display:"flex",justifyContent:"center",alignItems:"center"},children:et})};FitText.displayName="FitText";function useConnectors(){const et=useConnectors$1();return et??[]}function useConnector(et,o){const tt=useConnectors();return et==="injected"&&o?tt.find(rt=>rt.id===et&&rt.name===o):et==="injected"?tt.find(rt=>rt.id===et&&rt.name.includes("Injected")):tt.find(rt=>rt.id===et)}function useWalletConnectConnector(){return useConnector("walletConnect")}const useWallet=et=>{const tt=useWallets().find(rt=>rt.id===et);return tt||null},useWallets=()=>{const et=useConnectors(),o=useContext();return et.map(rt=>{var nt,ot;const it=Object.keys(walletConfigs).find(at=>at.split(",").map(ct=>ct.trim()).indexOf(rt.id)!==-1),st={id:rt.id,name:(ot=(nt=rt.name)!==null&&nt!==void 0?nt:rt.id)!==null&&ot!==void 0?ot:rt.type,icon:jsxRuntimeExports.jsx("img",{src:rt.icon,alt:rt.name,width:"100%",height:"100%"}),connector:rt,iconShape:"squircle",isInstalled:rt.type==="mock"||rt.type==="injected"&&rt.id!=="metaMask"||isCoinbaseWalletConnector(rt.id)};if(it){const at=walletConfigs[it];return{...st,iconConnector:rt.icon?jsxRuntimeExports.jsx("img",{src:rt.icon,alt:rt.name,width:"100%",height:"100%"}):void 0,...at}}return st}).filter((rt,nt,ot)=>ot.findIndex(it=>it.id===rt.id)===nt).map(rt=>{var nt,ot;return rt.id==="walletConnect"?{...rt,name:((nt=o.options)===null||nt===void 0?void 0:nt.walletConnectName)||rt.name,shortName:((ot=o.options)===null||ot===void 0?void 0:ot.walletConnectName)||rt.shortName}:rt}).filter((rt,nt,ot)=>!(rt.id==="coinbaseWalletSDK"&&ot.find(it=>it.id==="com.coinbase.wallet"))).filter((rt,nt,ot)=>!((rt.id==="metaMaskSDK"||rt.id==="metaMask")&&ot.find(it=>it.id==="io.metamask"||it.id==="io.metamask.mobile"))).sort((rt,nt)=>{const ot=rt.isInstalled&&isInjectedConnector(rt.connector.type),it=nt.isInstalled&&isInjectedConnector(nt.connector.type);return ot&&!it?-1:!ot&&it?1:0}).sort((rt,nt)=>rt.id==="walletConnect"?1:nt.id==="walletConnect"?-1:0)},ProfileIcon=({isSignedIn:et})=>jsxRuntimeExports.jsxs("div",{style:{position:"relative"},children:[et?jsxRuntimeExports.jsx(AuthIcon,{style:{bottom:-1,right:-1}}):jsxRuntimeExports.jsx("div",{style:{zIndex:2,position:"absolute",top:-2,right:-2,background:"#1A88F8",borderRadius:8,boxShadow:"0 0 0 2px var(--ck-body-background)",width:8,height:8}}),jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{overflow:"visible"},children:[jsxRuntimeExports.jsx("circle",{cx:"10",cy:"10",r:"9",stroke:"currentColor",strokeWidth:"2"}),jsxRuntimeExports.jsx("path",{d:"M16.5 16.775C14.8618 15.0649 12.5552 14 10 14C7.44477 14 5.13825 15.0649 3.5 16.775",stroke:"currentColor",strokeWidth:"2"}),jsxRuntimeExports.jsx("circle",{cx:"10",cy:"8",r:"3",stroke:"currentColor",strokeWidth:"2"})]})]}),InfoIcon=({...et})=>jsxRuntimeExports.jsx("svg",{"aria-hidden":"true",width:"22",height:"22",viewBox:"0 0 22 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M20 11C20 15.9706 15.9706 20 11 20C6.02944 20 2 15.9706 2 11C2 6.02944 6.02944 2 11 2C15.9706 2 20 6.02944 20 11ZM22 11C22 17.0751 17.0751 22 11 22C4.92487 22 0 17.0751 0 11C0 4.92487 4.92487 0 11 0C17.0751 0 22 4.92487 22 11ZM11.6445 12.7051C11.6445 13.1348 11.3223 13.4678 10.7744 13.4678C10.2266 13.4678 9.92578 13.1885 9.92578 12.6191V12.4795C9.92578 11.4268 10.4951 10.8574 11.2686 10.3203C12.2031 9.67578 12.665 9.32129 12.665 8.59082C12.665 7.76367 12.0205 7.21582 11.043 7.21582C10.3232 7.21582 9.80762 7.57031 9.45312 8.16113C9.38282 8.24242 9.32286 8.32101 9.2667 8.39461C9.04826 8.68087 8.88747 8.8916 8.40039 8.8916C8.0459 8.8916 7.66992 8.62305 7.66992 8.15039C7.66992 7.96777 7.70215 7.7959 7.75586 7.61328C8.05664 6.625 9.27051 5.75488 11.1182 5.75488C12.9336 5.75488 14.5234 6.71094 14.5234 8.50488C14.5234 9.7832 13.7822 10.417 12.7402 11.1045C11.999 11.5986 11.6445 11.9746 11.6445 12.5762V12.7051ZM11.9131 15.5625C11.9131 16.1855 11.376 16.6797 10.7529 16.6797C10.1299 16.6797 9.59277 16.1748 9.59277 15.5625C9.59277 14.9395 10.1191 14.4453 10.7529 14.4453C11.3867 14.4453 11.9131 14.9287 11.9131 15.5625Z",fill:"currentColor"})}),CloseIcon=({...et})=>jsxRuntimeExports.jsx(motion.svg,{width:14,height:14,viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:jsxRuntimeExports.jsx("path",{d:"M1 13L13 1M1 1L13 13",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})}),BackIcon=({...et})=>jsxRuntimeExports.jsx(motion.svg,{width:9,height:16,viewBox:"0 0 9 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:jsxRuntimeExports.jsx("path",{d:"M8 1L1 8L8 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),contentTransitionDuration=.22,contentVariants$2={initial:{zIndex:2,opacity:0},animate:{opacity:1,scale:1,transition:{duration:contentTransitionDuration*.75,delay:contentTransitionDuration*.25,ease:[.26,.08,.25,1]}},exit:{zIndex:1,opacity:0,pointerEvents:"none",position:"absolute",left:["50%","50%"],x:["-50%","-50%"],transition:{duration:contentTransitionDuration,ease:[.26,.08,.25,1]}}},Modal=({open:et,pages:o,pageId:tt,positionInside:rt,inline:nt,demo:ot,onClose:it,onBack:st,onInfo:at})=>{var ct,lt,dt,ht,mt,ft,pt,gt,yt,bt,xt,vt;const Et=useContext(),Ct=useThemeContext(),St=isMobile(),{isSignedIn:At,reset:kt}=useSIWE(),It=useWallet((ct=Et.connector)===null||ct===void 0?void 0:ct.id),Ot={name:It==null?void 0:It.name,shortName:(lt=It==null?void 0:It.shortName)!==null&<!==void 0?lt:It==null?void 0:It.name,icon:(dt=It==null?void 0:It.iconConnector)!==null&&dt!==void 0?dt:It==null?void 0:It.icon,iconShape:(ht=It==null?void 0:It.iconShape)!==null&&ht!==void 0?ht:"circle",iconShouldShrink:It==null?void 0:It.iconShouldShrink},Nt=useLocales({CONNECTORNAME:Ot==null?void 0:Ot.name}),[Yt,Ft]=useTransition({timeout:160,preEnter:!0,mountOnEnter:!0,unmountOnExit:!0}),Ht=!(Yt==="exited"||Yt==="unmounted"),Qt=Yt==="preEnter"||Yt!=="exiting",Vt=Et.route===routes.CONNECTORS?0:Et.route===routes.DOWNLOAD?2:1,Bt=usePrevious(Vt,Vt);rt||useLockBodyScroll(Ht),usePrevious(tt,tt),reactExports.useEffect(()=>{Ft(et),et&&Kt(void 0)},[et]);const[Wt,jt]=reactExports.useState({width:void 0,height:void 0}),[Xt,Kt]=reactExports.useState(void 0),Pt=Zt=>{const nr={width:Zt==null?void 0:Zt.offsetWidth,height:Zt==null?void 0:Zt.offsetHeight};jt({width:`${nr==null?void 0:nr.width}px`,height:`${nr==null?void 0:nr.height}px`})};let Gt;const tr=reactExports.useCallback(Zt=>{Zt&&(rr.current=Zt,Kt(Xt!==void 0),clearTimeout(Gt),Gt=setTimeout(()=>Kt(!1),360),Pt(Zt))},[et,Xt]),{chain:zt}=useAccount(),{switchChain:lr}=useSwitchChain(),rr=reactExports.useRef(null);reactExports.useEffect(()=>{rr.current&&Pt(rr.current)},[zt,lr,St,At,Et.options,Et.resize]),reactExports.useEffect(()=>{if(!Ht){jt({width:void 0,height:void 0});return}const Zt=nr=>{nr.key==="Escape"&&it&&it()};return document.addEventListener("keydown",Zt),()=>{document.removeEventListener("keydown",Zt)}},[Ht,it]);const Jt={"--height":Wt.height,"--width":Wt.width};function Rt(){return It?!(!It.getWalletConnectDeeplink||It.isInstalled):!1}function Mt(){var Zt;switch(Et.route){case routes.ABOUT:return Nt.aboutScreen_heading;case routes.CONNECT:return Rt()?isWalletConnectConnector((Zt=It==null?void 0:It.connector)===null||Zt===void 0?void 0:Zt.id)?Nt.scanScreen_heading:Nt.scanScreen_heading_withConnector:Ot==null?void 0:Ot.name;case routes.CONNECTORS:return Nt.connectorsScreen_heading;case routes.MOBILECONNECTORS:return Nt.mobileConnectorsScreen_heading;case routes.DOWNLOAD:return Nt.downloadAppScreen_heading;case routes.ONBOARDING:return Nt.onboardingScreen_heading;case routes.PROFILE:return Nt.profileScreen_heading;case routes.SWITCHNETWORKS:return Nt.switchNetworkScreen_heading;case routes.SIGNINWITHETHEREUM:return At?Nt.signInWithEthereumScreen_signedIn_heading:Nt.signInWithEthereumScreen_signedOut_heading;default:return""}}const Ut=jsxRuntimeExports.jsx(ResetContainer,{$useTheme:(mt=ot==null?void 0:ot.theme)!==null&&mt!==void 0?mt:Ct.theme,$useMode:(ft=ot==null?void 0:ot.mode)!==null&&ft!==void 0?ft:Ct.mode,$customTheme:(pt=ot==null?void 0:ot.customTheme)!==null&&pt!==void 0?pt:Ct.customTheme,children:jsxRuntimeExports.jsxs(ModalContainer,{role:"dialog",style:{pointerEvents:Qt?"auto":"none",position:rt?"absolute":void 0},children:[!nt&&jsxRuntimeExports.jsx(BackgroundOverlay,{$active:Qt,onClick:it,$blur:(gt=Et.options)===null||gt===void 0?void 0:gt.overlayBlur}),jsxRuntimeExports.jsxs(Container$7,{style:Jt,initial:!1,children:[jsxRuntimeExports.jsx("div",{style:{pointerEvents:Xt?"all":"none",position:"absolute",top:0,bottom:0,left:"50%",transform:"translateX(-50%)",width:"var(--width)",zIndex:9,transition:"width 200ms ease"}}),jsxRuntimeExports.jsxs(BoxContainer,{className:`${Qt&&"active"}`,children:[jsxRuntimeExports.jsx(AnimatePresence,{initial:!1,children:((yt=Et.options)===null||yt===void 0?void 0:yt.disclaimer)&&Et.route===routes.CONNECTORS&&jsxRuntimeExports.jsx(DisclaimerBackground,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{delay:0,duration:.2,ease:[.25,.1,.25,1]},children:jsxRuntimeExports.jsx(Disclaimer,{children:jsxRuntimeExports.jsx("div",{children:(bt=Et.options)===null||bt===void 0?void 0:bt.disclaimer})})})}),jsxRuntimeExports.jsx(AnimatePresence,{initial:!1,children:Et.errorMessage&&jsxRuntimeExports.jsxs(ErrorMessage,{initial:{y:"10%",x:"-50%"},animate:{y:"-100%"},exit:{y:"100%"},transition:{duration:.2,ease:"easeInOut"},children:[jsxRuntimeExports.jsx("span",{children:Et.errorMessage}),jsxRuntimeExports.jsx("div",{onClick:()=>Et.displayError(null),style:{position:"absolute",right:24,top:24,cursor:"pointer"},children:jsxRuntimeExports.jsx(CloseIcon,{})})]})}),jsxRuntimeExports.jsxs(ControllerContainer,{children:[it&&jsxRuntimeExports.jsx(CloseButton,{"aria-label":flattenChildren(Nt.close).toString(),onClick:it,children:jsxRuntimeExports.jsx(CloseIcon,{})}),jsxRuntimeExports.jsx("div",{style:{position:"absolute",top:23,left:20,width:32,height:32},children:jsxRuntimeExports.jsx(AnimatePresence,{children:st?jsxRuntimeExports.jsx(BackButton,{disabled:Xt,"aria-label":flattenChildren(Nt.back).toString(),onClick:st,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:St?0:.1,delay:St?.01:0},children:jsxRuntimeExports.jsx(BackIcon,{})},"backButton"):Et.route===routes.PROFILE&&Et.signInWithEthereum?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[!At&&!(!((xt=Et.options)===null||xt===void 0)&&xt.hideTooltips)&&jsxRuntimeExports.jsx(motion.div,{style:{position:"absolute",inset:0,pointerEvents:"none"},initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1,transition:{delay:.5,duration:.2}},exit:{opacity:0,scale:.6,transition:{delay:0,duration:St?0:.1}},children:jsxRuntimeExports.jsx(SignInTooltip,{children:Nt.signInWithEthereumScreen_tooltip})}),jsxRuntimeExports.jsx(SiweButton,{disabled:Xt,"aria-label":Nt.signInWithEthereumScreen_signedOut_heading,onClick:()=>{kt(),Et.setRoute(routes.SIGNINWITHETHEREUM)},initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:St?0:.1,delay:St?.01:0},children:jsxRuntimeExports.jsx(ProfileIcon,{isSignedIn:At})},"siweButton")]}):at&&!(!((vt=Et.options)===null||vt===void 0)&&vt.hideQuestionMarkCTA)&&jsxRuntimeExports.jsx(InfoButton,{disabled:Xt,"aria-label":flattenChildren(Nt.moreInformation).toString(),onClick:at,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:St?0:.1,delay:St?.01:0},children:jsxRuntimeExports.jsx(InfoIcon,{})},"infoButton")})})]}),jsxRuntimeExports.jsx(ModalHeading,{children:jsxRuntimeExports.jsx(AnimatePresence,{children:jsxRuntimeExports.jsx(motion.div,{style:{position:"absolute",top:0,bottom:0,left:52,right:52,display:"flex",justifyContent:"center"},initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:St?0:.17,delay:St?.01:0},children:jsxRuntimeExports.jsx(FitText,{children:Mt()})},`${Et.route}-${At?"signedIn":""}`)})}),jsxRuntimeExports.jsx(InnerContainer$1,{children:Object.keys(o).map(Zt=>{const nr=o[Zt];return jsxRuntimeExports.jsx(Page,{open:Zt===tt,initial:!rt&&Yt!=="entered",enterAnim:Zt===tt?Vt>Bt?"active-scale-up":"active":"",exitAnim:Zt!==tt?Vt{const[st,at]=useTransition({timeout:400,preEnter:!0,initialEntered:o,mountOnEnter:!0,unmountOnExit:!0}),ct=!(st==="exited"||st==="unmounted"),lt=st==="preEnter"||st!=="exiting";return reactExports.useEffect(()=>{at(o)},[o]),ct?jsxRuntimeExports.jsx(PageContainer,{className:`${lt?ot:it}`,style:{animationDuration:tt?"0ms":void 0,animationDelay:tt?"0ms":void 0},children:et}):null},OrDivider=({children:et})=>{const o=useLocales();return jsxRuntimeExports.jsx(TextWithHr,{children:jsxRuntimeExports.jsx("span",{children:et??o.or})})},Graphic=styled(motion.div)` + position: relative; + margin: 16px auto 20px; + height: 190px; + max-width: 295px; + pointer-events: none; + user-select: none; + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + height: 200px; + max-width: 100%; + margin-bottom: 32px; + } +`,LogoGroup=styled(motion.div)` + position: absolute; + inset: 0; + z-index: 2; +`,graphicIn=We` + 0%{ + opacity:0; + transform:scale(0.9); + } + 100%{ + opacity:1; + transform:none; + } +`,GraphicBackground=styled(motion.div)` + z-index: 1; + position: absolute; + inset: 0; + top: -2px; + overflow: hidden; + &:before { + content: ''; + position: absolute; + inset: 0; + background: var(--ck-body-background); + background: radial-gradient( + closest-side, + var(--ck-body-background-transparent, transparent) 18.75%, + var(--ck-body-background) 100% + ); + background-size: 100%; + } + svg { + display: block; + width: 100%; + height: auto; + } + animation: ${graphicIn} 1000ms 100ms ease both; + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + animation: none; + } +`,logoIn=We` + 0%{ + opacity:0; + transform:scale(0) translateY(40%); + } + 100%{ + opacity:1; + transform:none; + } +`,LogoPosition=styled(motion.div)` + position: absolute; + inset: 0; + animation: cubic-bezier(0.455, 0.03, 0.515, 0.955) infinite both; + animation-delay: inherit; +`,LogoInner=styled(motion.div)` + position: absolute; +`,LogoGraphic=styled(motion.div)` + position: relative; + overflow: hidden; + height: 58px; + width: 58px; + border-radius: 13.84px; + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05), 0 2px 20px 0 rgba(0, 0, 0, 0.03); + + svg { + display: block; + width: 100%; + height: 100%; + } +`,float$1=We` + 0%,100%{ transform:none; } + 50%{ transform: translateY(-10%) } +`,FloatWrapper=styled(motion.div)` + position: relative; + animation: cubic-bezier(0.455, 0.03, 0.515, 0.955) infinite both; + animation-name: ${float$1}; + animation-duration: 3600ms; +`,rotate=We` + 0%,100%{ transform:rotate(-3deg); } + 50%{ transform:rotate(3deg); } +`,RotateWrapper=styled(motion.div)` + position: relative; + animation: cubic-bezier(0.455, 0.03, 0.515, 0.955) infinite both; + animation-name: ${rotate}; + animation-duration: 3200ms; +`,Logo$2=styled(motion.div)` + position: absolute; + inset: 0; + + animation: ${logoIn} 750ms cubic-bezier(0.19, 1, 0.22, 1) both; + &:nth-child(1){ z-index:2; animation-delay:0ms; } + &:nth-child(2){ z-index:1; animation-delay:60ms; } + &:nth-child(3){ z-index:1; animation-delay:30ms; } + &:nth-child(4){ z-index:1; animation-delay:90ms; } + &:nth-child(5){ z-index:1; animation-delay:120ms;} + + &:nth-child(1){ ${RotateWrapper}{ animation-delay:0ms; } } + &:nth-child(2){ ${RotateWrapper}{ animation-delay:-600ms; } } + &:nth-child(3){ ${RotateWrapper}{ animation-delay:-1200ms; } } + &:nth-child(4){ ${RotateWrapper}{ animation-delay:-1800ms; } } + &:nth-child(5){ ${RotateWrapper}{ animation-delay:-2400ms; } } + + &:nth-child(1){ ${FloatWrapper}{ animation-delay:-200ms; } } + &:nth-child(2){ ${FloatWrapper}{ animation-delay:-600ms; } } + &:nth-child(3){ ${FloatWrapper}{ animation-delay:-800ms; } } + &:nth-child(4){ ${FloatWrapper}{ animation-delay:-300ms; } } + &:nth-child(5){ ${FloatWrapper}{ animation-delay:-3200ms; } } + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + animation: none !important; + ${RotateWrapper},${FloatWrapper} { + animation: none !important; + } + } + + ${LogoInner} { + transform: translate(-50%, -50%); + } + + &:nth-child(1) ${LogoPosition} { + transform: translate(50%, 50%); + ${LogoGraphic} { + border-radius: 17.2px; + width: 72px; + height: 72px; + } + } + &:nth-child(2) ${LogoPosition} { + transform: translate(21%, 21.5%); + } + &:nth-child(3) ${LogoPosition} { + transform: translate(78%, 14%); + } + &:nth-child(4) ${LogoPosition} { + transform: translate(22.5%, 76%); + } + &:nth-child(5) ${LogoPosition} { + transform: translate(76%, 80%); + } +`;var wave=jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"298",height:"188",viewBox:"0 0 298 188",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{d:"M1 55.2757L21.6438 46.0285C55.5896 30.8228 94.4104 30.8228 128.356 46.0286L169.644 64.5229C203.59 79.7287 242.41 79.7286 276.356 64.5229L297 55.2757M1 44.2118L21.6438 34.9646C55.5896 19.7589 94.4104 19.7589 128.356 34.9646L169.644 53.459C203.59 68.6647 242.41 68.6647 276.356 53.459L297 44.2118M1 33.1477L21.6438 23.9005C55.5896 8.69479 94.4104 8.69479 128.356 23.9005L169.644 42.3949C203.59 57.6006 242.41 57.6006 276.356 42.3949L297 33.1477M1 22.1477L21.6438 12.9005C55.5896 -2.30521 94.4104 -2.30521 128.356 12.9005L169.644 31.3949C203.59 46.6006 242.41 46.6006 276.356 31.3949L297 22.1477M1 66.3398L21.6438 57.0926C55.5896 41.8869 94.4104 41.8869 128.356 57.0926L169.644 75.587C203.59 90.7927 242.41 90.7927 276.356 75.587L297 66.3398M1 77.404L21.6438 68.1568C55.5896 52.9511 94.4104 52.9511 128.356 68.1569L169.644 86.6512C203.59 101.857 242.41 101.857 276.356 86.6512L297 77.404M1 88.4681L21.6438 79.2209C55.5896 64.0152 94.4104 64.0152 128.356 79.2209L169.644 97.7153C203.59 112.921 242.41 112.921 276.356 97.7153L297 88.4681M1 121.66L21.6438 112.413C55.5896 97.2075 94.4104 97.2075 128.356 112.413L169.644 130.908C203.59 146.113 242.41 146.113 276.356 130.908L297 121.66M1 110.596L21.6438 101.349C55.5896 86.1433 94.4104 86.1433 128.356 101.349L169.644 119.843C203.59 135.049 242.41 135.049 276.356 119.843L297 110.596M1 99.5321L21.6438 90.2849C55.5896 75.0792 94.4104 75.0792 128.356 90.2849L169.644 108.779C203.59 123.985 242.41 123.985 276.356 108.779L297 99.5321M1 132.724L21.6438 123.477C55.5896 108.271 94.4104 108.271 128.356 123.477L169.644 141.971C203.59 157.177 242.41 157.177 276.356 141.971L297 132.724M1 143.788L21.6438 134.541C55.5896 119.336 94.4104 119.336 128.356 134.541L169.644 153.036C203.59 168.241 242.41 168.241 276.356 153.036L297 143.788M1 154.853L21.6438 145.605C55.5896 130.4 94.4104 130.4 128.356 145.605L169.644 164.1C203.59 179.305 242.41 179.305 276.356 164.1L297 154.853M1 165.853L21.6438 156.605C55.5896 141.4 94.4104 141.4 128.356 156.605L169.644 175.1C203.59 190.305 242.41 190.305 276.356 175.1L297 165.853",stroke:"url(#paint0_linear_1094_2077)",strokeOpacity:"0.9",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_1094_2077",x1:"1",y1:"112.587",x2:"297.034",y2:"79.6111",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-wave-stop-01)"}),jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-wave-stop-02)",offset:"0.239583"}),jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-wave-stop-03)",offset:"0.515625"}),jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-wave-stop-04)",offset:"0.739583"}),jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-wave-stop-05)",offset:"1"})]})})]});const SpinnerContainer$3=styled(motion.div)` + position: absolute; + right: 16px; + top: 0; + bottom: 0; + display: flex; + align-items: center; + justify-content: center; +`,Arrow=styled.svg` + --x: -3px; + --stroke-width: 2; + position: relative; + top: 1px; + left: -0.5px; + display: inline-block; + vertical-align: middle; + margin-left: 9px; + margin-right: 1px; + transition: all 100ms ease; + transform: translateX(var(--x, -3px)); + color: currentColor; + opacity: 0.4; +`,ArrowChevron=styled.path``,ArrowLine=styled.line` + transition: inherit; + transition-property: transform; + transform-origin: 90% 50%; + transform: scaleX(0.1); +`,DownloadArrow=styled.div` + display: inline-block; + vertical-align: middle; + position: relative; + margin-right: 6px; + color: currentColor; +`,DownloadArrowInner=styled.div` + transform: rotate(90deg); + ${Arrow} { + margin: 0 auto; + } +`,ButtonContainerInner=styled(motion.div)` + display: flex; + align-items: center; + justify-content: center; + inset: 0; + height: 100%; +`,ButtonContainer$1=styled.button` + + ${({disabled:et})=>et&&Ae` + cursor: not-allowed; + pointer-events: none; + ${InnerContainer} { + opacity: 0.4; + } + `} + + ${({$variant:et})=>{if(et==="primary")return Ae` + --color: var(--ck-primary-button-color, var(--ck-body-color)); + --background: var( + --ck-primary-button-background, + var(--ck-body-background-primary) + ); + --box-shadow: var(--ck-primary-button-box-shadow); + --border-radius: var(--ck-primary-button-border-radius); + --font-weight: var(--ck-primary-button-font-weight, 500); + + --hover-color: var(--ck-button-primary-hover-color, var(--color)); + --hover-background: var( + --ck-primary-button-hover-background, + var(--background) + ); + --hover-box-shadow: var( + --ck-primary-button-hover-box-shadow, + var(--box-shadow) + ); + --hover-border-radius: var( + --ck-primary-button-hover-border-radius, + var(--border-radius) + ); + --hover-font-weight: var( + --ck-primary-button-font-weight, + var(--font-weight) + ); + `;if(et==="secondary")return Ae` + --color: var(--ck-secondary-button-color, var(--ck-body-color)); + --background: var( + --ck-secondary-button-background, + var(--ck-body-background-secondary) + ); + --box-shadow: var(--ck-secondary-button-box-shadow); + --border-radius: var(--ck-secondary-button-border-radius); + --font-weight: var(--ck-secondary-button-font-weight, 500); + + --hover-color: var(--ck-secondary-button-hover-color, var(--color)); + --hover-background: var( + --ck-secondary-button-hover-background, + var(--background) + ); + --hover-box-shadow: var( + --ck-secondary-button-hover-box-shadow, + var(--box-shadow) + ); + --hover-border-radius: var( + --ck-secondary-button-hover-border-radius, + var(--border-radius) + ); + --hover-font-weight: var( + --ck-secondary-button-font-weight, + var(--font-weight) + ); + `;if(et==="tertiary")return Ae` + --color: var( + --ck-tertiary-button-color, + var(--ck-secondary-button-color) + ); + --background: var( + --ck-tertiary-button-background, + var(--ck-secondary-button-background) + ); + --box-shadow: var( + --ck-tertiary-button-box-shadow, + var(--ck-secondary-button-box-shadow) + ); + --border-radius: var( + --ck-tertiary-button-border-radius, + var(--ck-secondary-button-border-radius) + ); + --font-weight: var( + --ck-tertiary-button-font-weight, + var(--ck-secondary-button-font-weight) + ); + + --hover-color: var( + --button-tertiary-hover-color, + var(--ck-tertiary-button-color) + ); + --hover-background: var( + --ck-tertiary-button-hover-background, + var(--ck-tertiary-button-background) + ); + --hover-box-shadow: var( + --ck-tertiary-button-hover-box-shadow, + var(--ck-tertiary-button-box-shadow) + ); + --hover-border-radius: var( + --ck-tertiary-button-hover-border-radius, + var(--ck-tertiary-button-border-radius, var(--border-radius)) + ); + --hover-font-weight: var( + --ck-tertiary-button-font-weight, + var(--ck-secondary-button-font-weight) + ); + `}} + + appearance: none; + cursor: pointer; + user-select: none; + min-width: fit-content; + width: 100%; + display:block; + text-align: center; + height: 48px; + margin: 12px 0 0; + line-height: 48px; + padding: 0 4px; + font-size: 16px; + font-weight: var(--font-weight,500); + text-decoration: none; + white-space: nowrap; + transition: 100ms ease; + transition-property: box-shadow, background-color; + color: var(--color); + background: var(--background); + border-radius: var(--border-radius); + box-shadow: var(--box-shadow); + will-change: transform, box-shadow, background-color, color; + + ${DownloadArrow} { + ${Arrow} { + transform: translateX(0); + ${ArrowLine} { + transform: none; + } + ${ArrowChevron} { + } + } + } +} + + @media only screen and (min-width: ${defaultTheme.mobileWidth+1}px) { + &:hover, + &:focus-visible { + color: var(--ck-accent-text-color, var(--hover-color)); + background: var(--ck-accent-color, var(--hover-background)); + border-radius: var(--hover-border-radius); + box-shadow: var(--hover-box-shadow); + + ${Arrow} { + transform: translateX(0); + ${ArrowLine} { + transform: none; + } + ${ArrowChevron} { + } + } + ${DownloadArrow} { + ${Arrow} { + transform: translateX(var(--x)); + ${ArrowLine} { + transform: scaleX(0.1); + } + ${ArrowChevron} { + } + } + } + } + &:active { + box-shadow: var(--ck-secondary-button-active-box-shadow, var(--hover-box-shadow)); + } + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + transition: transform 100ms ease; + transform: scale(1); + font-size: 17px; + &:active { + } + } +`,InnerContainer=styled.div` + transform: translateZ(0); // Shifting fix + position: relative; + display: inline-block; + vertical-align: middle; + max-width: calc(100% - 42px); + transition: opacity 300ms ease; + /* + overflow: hidden; + text-overflow: ellipsis; + */ +`,IconContainer$4=styled(motion.div)` + position: relative; + display: inline-block; + vertical-align: middle; + max-width: 20px; + max-height: 20px; + margin: 0 10px; + &:first-child { + margin-left: 0; + } + &:last-child { + margin-right: 0; + } + ${et=>et.$rounded&&Ae` + overflow: hidden; + border-radius: 5px; + `} + svg { + display: block; + position: relative; + max-width: 100%; + height: auto; + } +`,Spin$1=We` + 0%{ transform: rotate(0deg); } + 100%{ transform: rotate(360deg); } +`,SpinnerContainer$2=styled(motion.div)` + display: flex; + align-items: center; + justify-content: center; + animation: ${Spin$1} 1s linear infinite; + svg { + display: block; + position: relative; + animation: ${Spin$1} 1s ease-in-out infinite; + } +`,transition$2={duration:.4,ease:[.175,.885,.32,.98]},Spinner$4=()=>jsxRuntimeExports.jsx(SpinnerContainer$2,{initial:{opacity:0,rotate:180},animate:{opacity:1,rotate:0},exit:{position:"absolute",opacity:0,rotate:-180,transition:{...transition$2}},transition:{...transition$2,delay:.2},children:jsxRuntimeExports.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("circle",{cx:"9",cy:"9",r:"7",stroke:"currentColor",strokeOpacity:"0.1",strokeWidth:"2.5"}),jsxRuntimeExports.jsx("path",{d:"M16 9C16 5.13401 12.866 2 9 2",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"})]})}),transition$1={duration:.4,ease:[.175,.885,.32,.98]},Button$1=({children:et,variant:o="secondary",disabled:tt,icon:rt,iconPosition:nt="left",roundedIcon:ot,waiting:it,arrow:st,download:at,href:ct,style:lt,onClick:dt})=>{const ht=typeof et=="string"?et:flattenChildren(et).join(""),mt=typeof ct=="string"?ct:flattenChildren(ct).join("");return jsxRuntimeExports.jsx(ButtonContainer$1,{as:ct?"a":void 0,onClick:ft=>{!tt&&dt&&dt(ft)},href:mt,target:ct&&"_blank",rel:ct&&"noopener noreferrer",disabled:tt,$variant:o,style:lt,children:jsxRuntimeExports.jsxs(AnimatePresence,{initial:!1,children:[jsxRuntimeExports.jsxs(ButtonContainerInner,{initial:{opacity:0,y:-10},animate:{opacity:1,y:-1},exit:{position:"absolute",opacity:0,y:10,transition:{...transition$1}},transition:{...transition$1,delay:.2},children:[rt&&nt==="left"&&jsxRuntimeExports.jsx(IconContainer$4,{$rounded:ot,children:rt}),at&&jsxRuntimeExports.jsx(DownloadArrow,{children:jsxRuntimeExports.jsx(DownloadArrowInner,{children:jsxRuntimeExports.jsxs(Arrow,{width:"13",height:"12",viewBox:"0 0 13 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx(ArrowLine,{stroke:"currentColor",x1:"1",y1:"6",x2:"12",y2:"6",strokeWidth:"var(--stroke-width)",strokeLinecap:"round"}),jsxRuntimeExports.jsx(ArrowChevron,{stroke:"currentColor",d:"M7.51431 1.5L11.757 5.74264M7.5 10.4858L11.7426 6.24314",strokeWidth:"var(--stroke-width)",strokeLinecap:"round"})]})})}),jsxRuntimeExports.jsx(InnerContainer,{style:{paddingLeft:st?6:0},children:jsxRuntimeExports.jsx(FitText,{children:et})}),rt&&nt==="right"&&jsxRuntimeExports.jsx(IconContainer$4,{$rounded:ot,children:rt}),st&&jsxRuntimeExports.jsxs(Arrow,{width:"13",height:"12",viewBox:"0 0 13 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx(ArrowLine,{stroke:"currentColor",x1:"1",y1:"6",x2:"12",y2:"6",strokeWidth:"2",strokeLinecap:"round"}),jsxRuntimeExports.jsx(ArrowChevron,{stroke:"currentColor",d:"M7.51431 1.5L11.757 5.74264M7.5 10.4858L11.7426 6.24314",strokeWidth:"2",strokeLinecap:"round"})]})]},ht),it&&jsxRuntimeExports.jsx(SpinnerContainer$3,{children:jsxRuntimeExports.jsx(Spinner$4,{})})]})})},Introduction=()=>{var et,o;const tt=useContext(),rt=useLocales({}),nt=(o=(et=tt.options)===null||et===void 0?void 0:et.walletOnboardingUrl)!==null&&o!==void 0?o:rt.onboardingScreen_ctaUrl;return jsxRuntimeExports.jsxs(PageContent,{children:[jsxRuntimeExports.jsxs(Graphic,{children:[jsxRuntimeExports.jsxs(LogoGroup,{children:[jsxRuntimeExports.jsx(Logo$2,{children:jsxRuntimeExports.jsx(LogoPosition,{children:jsxRuntimeExports.jsx(LogoInner,{children:jsxRuntimeExports.jsx(FloatWrapper,{children:jsxRuntimeExports.jsx(RotateWrapper,{children:jsxRuntimeExports.jsx(LogoGraphic,{children:jsxRuntimeExports.jsx(Logos.Coinbase,{background:!0})})})})})})}),jsxRuntimeExports.jsx(Logo$2,{children:jsxRuntimeExports.jsx(LogoPosition,{children:jsxRuntimeExports.jsx(LogoInner,{children:jsxRuntimeExports.jsx(FloatWrapper,{children:jsxRuntimeExports.jsx(RotateWrapper,{children:jsxRuntimeExports.jsx(LogoGraphic,{children:jsxRuntimeExports.jsx(Logos.MetaMask,{background:!0})})})})})})}),jsxRuntimeExports.jsx(Logo$2,{children:jsxRuntimeExports.jsx(LogoPosition,{children:jsxRuntimeExports.jsx(LogoInner,{children:jsxRuntimeExports.jsx(FloatWrapper,{children:jsxRuntimeExports.jsx(RotateWrapper,{children:jsxRuntimeExports.jsx(LogoGraphic,{children:jsxRuntimeExports.jsx(Logos.Trust,{})})})})})})}),jsxRuntimeExports.jsx(Logo$2,{children:jsxRuntimeExports.jsx(LogoPosition,{children:jsxRuntimeExports.jsx(LogoInner,{children:jsxRuntimeExports.jsx(FloatWrapper,{children:jsxRuntimeExports.jsx(RotateWrapper,{children:jsxRuntimeExports.jsx(LogoGraphic,{children:jsxRuntimeExports.jsx(Logos.Argent,{})})})})})})}),jsxRuntimeExports.jsx(Logo$2,{children:jsxRuntimeExports.jsx(LogoPosition,{children:jsxRuntimeExports.jsx(LogoInner,{children:jsxRuntimeExports.jsx(FloatWrapper,{children:jsxRuntimeExports.jsx(RotateWrapper,{children:jsxRuntimeExports.jsx(LogoGraphic,{children:jsxRuntimeExports.jsx(Logos.ImToken,{})})})})})})})]}),jsxRuntimeExports.jsx(GraphicBackground,{children:wave})]}),jsxRuntimeExports.jsxs(ModalContent,{style:{paddingBottom:18},children:[jsxRuntimeExports.jsx(ModalH1,{$small:!0,children:rt.onboardingScreen_h1}),jsxRuntimeExports.jsx(ModalBody,{children:rt.onboardingScreen_p})]}),jsxRuntimeExports.jsx(Button$1,{href:nt,arrow:!0,children:rt.onboardingScreen_ctaText})]})},imageHeight=208,ImageContainer$1=styled.div` + pointer-events: none; + user-select: none; + height: ${imageHeight}px; + padding: 0 0 12px; + display: flex; + align-items: center; + justify-content: center; + svg { + display: block; + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + display: none; + } +`,ImageContainerInner=styled(motion.div)``,MobileImageContainer=styled.div` + pointer-events: none; + user-select: none; + height: ${imageHeight}px; + padding: 0 0 12px; + display: none; + align-items: center; + justify-content: center; + svg { + display: block; + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + display: flex; + } +`,Slides=styled.div` + position: relative; +`,Slide=styled(motion.div)` + scroll-snap-type: x mandatory; + position: relative; + bottom: 0; + left: 0; + right: 0; + width: 100%; + padding: 0 4px 8px; + /* will-change: transform, opacity; */ + transition: 400ms 50ms cubic-bezier(0.16, 1, 0.3, 1); + transition-property: transform, opacity; + ${et=>!et.$active&&Ae` + pointer-events: none; + position: absolute; + opacity: 0; + transform: scale(0.95); + transition-duration: 300ms; + transition-delay: 0ms; + `} +`,Slider=styled.div` + --background: var(--ck-body-background-secondary); + --background-transparent: var(--ck-body-background-transparent, transparent); + position: relative; + padding: 0 0 4px; + border-radius: 16px; + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + margin: 0 -24px; + ${Slides} { + position: relative; + z-index: 3; + display: flex; + overflow: auto; + scroll-behavior: smooth; + scroll-snap-type: x mandatory; + margin-top: -${imageHeight}px; + padding-top: ${imageHeight}px; + -ms-overflow-style: none; /* Internet Explorer 10+ */ + scrollbar-width: none; /* Firefox */ + &::-webkit-scrollbar { + display: none; /* Safari and Chrome */ + } + } + ${Slide} { + position: relative; + opacity: 1; + transform: none; + flex-shrink: 0; + scroll-snap-align: start; + } + } +`,Dots=styled.div` + position: relative; + top: -1px; + display: flex; + justify-content: center; + pointer-events: auto; +`,Dot=styled.button` + display: flex; + align-items: center; + height: 28px; + padding: 2px; + background: none; + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + padding: 4px; + &:before { + transform: none !important; + } + } + &:before { + content: ''; + display: block; + width: 16px; + height: 3px; + opacity: 0.12; + border-radius: 4px; + background: var(--ck-accent-color, var(--ck-body-color)); + transition: transform 200ms ease, opacity 180ms ease; + } + ${et=>et.$active?Ae` + cursor: default; + &:before { + opacity: 1; + } + `:!et.disabled&&Ae` + cursor: pointer; + &:hover:before { + transform: scaleY(3.5); + } + &:active:before { + } + `} +`,pulseAnim={scale:[.9,1.25,1.6],opacity:[0,.11,0]},pulseTransition={ease:"linear",duration:2,repeat:1/0},Center=styled.div` + position: absolute; + left: 50%; + top: 50%; + transform: translateY(-50%) translateX(-50%); +`,spin=We` + from{ transform: rotate(0deg); } + to{ transform: rotate(360deg); } +`,SpinContainer=styled(motion.div)` + z-index: -1; + position: absolute; + inset: 0; + overflow: hidden; + border-radius: 100%; + animation: ${spin} 16s linear infinite; +`,BgLighten=styled(motion.div)` + overflow: hidden; + border-radius: inherit; + z-index: 0; + position: absolute; + inset: 0; + background: rgba(255, 255, 255, 0.1); +`,MainCircle=styled(motion.div)` + z-index: 2; + position: relative; + border-radius: 50%; + background: var(--ck-body-background); +`,MainCircleInner=styled(motion.div)` + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + border-radius: 50%; +`,Compass=jsxRuntimeExports.jsxs("svg",{width:"34",height:"34",viewBox:"0 0 34 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{d:"M17 34C26.3 34 34 26.2833 34 17C34 7.7 26.2833 0 16.9833 0C7.7 0 0 7.7 0 17C0 26.2833 7.71667 34 17 34ZM9.83333 25.6833C8.68333 26.2333 7.8 25.3333 8.33333 24.2L13.1667 14.3333C13.45 13.75 13.8167 13.3833 14.35 13.1333L24.1833 8.33333C25.4 7.75 26.25 8.65 25.6833 9.81667L20.8833 19.6667C20.6167 20.2 20.2333 20.6 19.6833 20.85L9.83333 25.6833ZM17.0167 19.1333C18.1833 19.1333 19.1333 18.1833 19.1333 17.0167C19.1333 15.85 18.1833 14.9167 17.0167 14.9167C15.8667 14.9167 14.9167 15.85 14.9167 17.0167C14.9167 18.1833 15.8667 19.1333 17.0167 19.1333Z",fill:"var(--ck-graphic-compass-color, var(--ck-body-color))"}),jsxRuntimeExports.jsx("path",{d:"M17 34C26.3 34 34 26.2833 34 17C34 7.7 26.2833 0 16.9833 0C7.7 0 0 7.7 0 17C0 26.2833 7.71667 34 17 34ZM9.83333 25.6833C8.68333 26.2333 7.8 25.3333 8.33333 24.2L13.1667 14.3333C13.45 13.75 13.8167 13.3833 14.35 13.1333L24.1833 8.33333C25.4 7.75 26.25 8.65 25.6833 9.81667L20.8833 19.6667C20.6167 20.2 20.2333 20.6 19.6833 20.85L9.83333 25.6833ZM17.0167 19.1333C18.1833 19.1333 19.1333 18.1833 19.1333 17.0167C19.1333 15.85 18.1833 14.9167 17.0167 14.9167C15.8667 14.9167 14.9167 15.85 14.9167 17.0167C14.9167 18.1833 15.8667 19.1333 17.0167 19.1333Z",fill:"url(#ck-compass-gradient)"}),jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsxs("linearGradient",{id:"ck-compass-gradient",x1:"17",y1:"0",x2:"17",y2:"34",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"rgba(0,0,0,0)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"rgba(0,0,0,0.05)"})]})})]}),Wallet=({inverted:et=!1})=>jsxRuntimeExports.jsxs("svg",{width:"58",height:"50",viewBox:"0 0 58 50",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M57.9332 20.3335V42.1113C57.9332 46.4069 54.451 49.8891 50.1555 49.8891H8.15546C3.85991 49.8891 0.377686 46.4069 0.377686 42.1113V25.0002V7.8891C0.377686 3.59355 3.85991 0.111328 8.15546 0.111328H47.0444C48.7626 0.111328 50.1555 1.50422 50.1555 3.22244C50.1555 4.94066 48.7626 6.33355 47.0443 6.33355H9.71102C7.9928 6.33355 6.59991 7.72644 6.59991 9.44466C6.59991 11.1629 7.9928 12.5558 9.71102 12.5558H50.1555C54.451 12.5558 57.9332 16.038 57.9332 20.3335ZM46.2667 34.3337C48.4145 34.3337 50.1556 32.5926 50.1556 30.4448C50.1556 28.297 48.4145 26.5559 46.2667 26.5559C44.1189 26.5559 42.3778 28.297 42.3778 30.4448C42.3778 32.5926 44.1189 34.3337 46.2667 34.3337Z",fill:et?"var(--ck-graphic-primary-color, var(--ck-body-background))":"var(--ck-graphic-primary-color, var(--ck-body-color))"}),jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_2501_7732",x1:"29.1555",y1:"0.111328",x2:"29.1555",y2:"49.8891",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:et?"var(--ck-body-color-muted)":"var(--ck-body-background-transparent, transparent)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:et?"var(--ck-body-color)":"var(--ck-body-background)"})]})})]}),Send=jsxRuntimeExports.jsx("svg",{width:"41",height:"41",viewBox:"0 0 41 41",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{d:"M35.4446 0.839914L2.14484 10.7065C0.0395033 11.3303 -0.632966 13.9786 0.919705 15.5313L7.9624 22.574C9.47585 24.0874 11.8661 24.273 13.5951 23.0114L25.2866 14.4797C25.5558 14.2832 25.9281 14.3121 26.1638 14.5478C26.3998 14.7838 26.4285 15.1567 26.2313 15.426L17.6874 27.0937C16.4213 28.8228 16.6052 31.2168 18.1206 32.7322L25.1811 39.7926C26.7337 41.3453 29.382 40.6728 30.0058 38.5675L39.8724 5.2677C40.6753 2.55794 38.1544 0.037024 35.4446 0.839914Z",fill:"var(--ck-graphic-secondary-color, white)"})}),Receive=jsxRuntimeExports.jsx("svg",{width:"38",height:"44",viewBox:"0 0 38 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M19 0.875C21.4853 0.875 23.5 2.88972 23.5 5.375V27.761L30.068 21.193C31.8254 19.4357 34.6746 19.4357 36.432 21.193C38.1893 22.9504 38.1893 25.7996 36.432 27.557L22.182 41.807C20.4246 43.5643 17.5754 43.5643 15.818 41.807L1.56802 27.557C-0.18934 25.7996 -0.18934 22.9504 1.56802 21.193C3.32538 19.4357 6.17462 19.4357 7.93198 21.193L14.5 27.761V5.375C14.5 2.88972 16.5147 0.875 19 0.875Z",fill:"var(--ck-graphic-secondary-color, white)"})}),Key$1=({...et})=>{var o;const tt=(o=et==null?void 0:et.id)!==null&&o!==void 0?o:"";return jsxRuntimeExports.jsxs("svg",{...et,width:"81",height:"81",viewBox:"0 0 81 81",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M81 27C81 41.9117 68.9117 54 54 54C51.2722 54 48.6389 53.5955 46.1568 52.8432L36 63H27V72H18V81H4.5C2.01472 81 0 78.9853 0 76.5V64.864C0 63.6705 0.474103 62.5259 1.31802 61.682L28.1568 34.8432C27.4045 32.3611 27 29.7278 27 27C27 12.0883 39.0883 0 54 0C68.9117 0 81 12.0883 81 27ZM60.75 25.875C63.8566 25.875 66.375 23.3566 66.375 20.25C66.375 17.1434 63.8566 14.625 60.75 14.625C57.6434 14.625 55.125 17.1434 55.125 20.25C55.125 23.3566 57.6434 25.875 60.75 25.875Z",fill:`url(#${tt}paint0_linear_2509_6177)`}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M81 27C81 41.9117 68.9117 54 54 54C51.2722 54 48.6389 53.5955 46.1568 52.8432L36 63H27V72H18V81H4.5C2.01472 81 0 78.9853 0 76.5V64.864C0 63.6705 0.474103 62.5259 1.31802 61.682L28.1568 34.8432C27.4045 32.3611 27 29.7278 27 27C27 12.0883 39.0883 0 54 0C68.9117 0 81 12.0883 81 27ZM60.75 25.875C63.8566 25.875 66.375 23.3566 66.375 20.25C66.375 17.1434 63.8566 14.625 60.75 14.625C57.6434 14.625 55.125 17.1434 55.125 20.25C55.125 23.3566 57.6434 25.875 60.75 25.875Z",fill:`url(#${tt}paint1_radial_2509_6177)`,fillOpacity:"0.2"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M44.5658 51.2522C45.1527 50.6653 46.0151 50.4492 46.8095 50.6899C49.0823 51.3788 51.4958 51.75 54 51.75C67.6691 51.75 78.75 40.669 78.75 27C78.75 13.331 67.6691 2.25 54 2.25C40.331 2.25 29.25 13.331 29.25 27C29.25 29.5042 29.6212 31.9177 30.3101 34.1905C30.5508 34.9849 30.3347 35.8473 29.7478 36.4342L2.90901 63.273C2.48705 63.6949 2.25 64.2672 2.25 64.864V76.5C2.25 77.7426 3.25736 78.75 4.5 78.75H15.75V72C15.75 70.7574 16.7574 69.75 18 69.75H24.75V63C24.75 61.7574 25.7574 60.75 27 60.75H35.068L44.5658 51.2522ZM36 63H27V72H18V81H4.5C2.01472 81 0 78.9853 0 76.5V64.864C0 63.6705 0.474103 62.5259 1.31802 61.682L28.1568 34.8432C27.4045 32.3611 27 29.7278 27 27C27 12.0883 39.0883 0 54 0C68.9117 0 81 12.0883 81 27C81 41.9117 68.9117 54 54 54C51.2722 54 48.6389 53.5955 46.1568 52.8432L36 63ZM68.625 20.25C68.625 24.5992 65.0992 28.125 60.75 28.125C56.4008 28.125 52.875 24.5992 52.875 20.25C52.875 15.9008 56.4008 12.375 60.75 12.375C65.0992 12.375 68.625 15.9008 68.625 20.25ZM66.375 20.25C66.375 23.3566 63.8566 25.875 60.75 25.875C57.6434 25.875 55.125 23.3566 55.125 20.25C55.125 17.1434 57.6434 14.625 60.75 14.625C63.8566 14.625 66.375 17.1434 66.375 20.25Z",fill:"black",fillOpacity:"0.1"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M33.4205 47.5795C33.8598 48.0188 33.8598 48.7312 33.4205 49.1705L3.0455 79.5455C2.60616 79.9848 1.89384 79.9848 1.4545 79.5455C1.01517 79.1062 1.01517 78.3938 1.4545 77.9545L31.8295 47.5795C32.2688 47.1402 32.9812 47.1402 33.4205 47.5795Z",fill:"#A5A9AD"}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:`${tt}paint0_linear_2509_6177`,x1:"72",y1:"5.625",x2:"2.25",y2:"78.75",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#D4DFE6"}),jsxRuntimeExports.jsx("stop",{offset:"0.0967282",stopColor:"#C6CACD"}),jsxRuntimeExports.jsx("stop",{offset:"0.526645",stopColor:"#BDBAC4"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"#939CA1"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:`${tt}paint1_radial_2509_6177`,cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(52.875 12.375) rotate(93.2705) scale(39.4392)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"white"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"white"})]})]})]})},VitalikAddress=jsxRuntimeExports.jsxs("svg",{width:"131",height:"14",viewBox:"0 0 131 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{d:"M5.74805 13.2549C8.86816 13.2549 10.7227 10.6973 10.7227 6.63672C10.7227 2.57617 8.85059 0.0625 5.74805 0.0625C2.63672 0.0625 0.755859 2.59375 0.755859 6.64551C0.755859 10.7148 2.61914 13.2549 5.74805 13.2549ZM5.74805 11.4004C4.02539 11.4004 3.04102 9.64258 3.04102 6.63672C3.04102 3.68359 4.04297 1.91699 5.74805 1.91699C7.44434 1.91699 8.4375 3.6748 8.4375 6.64551C8.4375 9.65137 7.46191 11.4004 5.74805 11.4004Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M13.0869 13.1758C13.4561 13.1758 13.6934 13.0439 13.9658 12.6221L15.9697 9.66016H16.0137L18.0264 12.6572C18.2549 13.0088 18.4922 13.1758 18.8965 13.1758C19.4854 13.1758 19.9424 12.7891 19.9424 12.209C19.9424 11.9805 19.8633 11.7695 19.7051 11.541L17.376 8.28906L19.6963 5.16016C19.8896 4.90527 19.9688 4.68555 19.9688 4.43066C19.9688 3.88574 19.5381 3.49902 18.9229 3.49902C18.5361 3.49902 18.2988 3.6748 18.0176 4.10547L16.1191 6.95312H16.0752L14.1328 4.08789C13.8516 3.64844 13.6318 3.49902 13.2012 3.49902C12.6035 3.49902 12.1465 3.91211 12.1465 4.44824C12.1465 4.70312 12.2256 4.92285 12.3838 5.13379L14.7129 8.35059L12.3486 11.5498C12.1641 11.8135 12.0762 12.0156 12.0762 12.2705C12.0762 12.7979 12.498 13.1758 13.0869 13.1758Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M26.2441 13.2549C29.1445 13.2549 31.1924 11.7432 31.1924 9.57227C31.1924 7.9375 30.0146 6.68066 28.3184 6.3291V6.27637C29.7773 5.87207 30.7178 4.7998 30.7178 3.45508C30.7178 1.48633 28.8633 0.0625 26.2441 0.0625C23.625 0.0625 21.7617 1.49512 21.7617 3.44629C21.7617 4.80859 22.7109 5.88965 24.1699 6.27637V6.3291C22.4736 6.67188 21.3047 7.92871 21.3047 9.57227C21.3047 11.7344 23.335 13.2549 26.2441 13.2549ZM26.2441 5.55566C24.9258 5.55566 24.0029 4.78223 24.0029 3.6748C24.0029 2.55859 24.9258 1.77637 26.2441 1.77637C27.5537 1.77637 28.4854 2.5498 28.4854 3.6748C28.4854 4.78223 27.5537 5.55566 26.2441 5.55566ZM26.2441 11.5234C24.7236 11.5234 23.6514 10.6357 23.6514 9.40527C23.6514 8.1748 24.7236 7.28711 26.2441 7.28711C27.7646 7.28711 28.8369 8.16602 28.8369 9.40527C28.8369 10.6357 27.7646 11.5234 26.2441 11.5234Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M36.3164 13.1494C37.7578 13.1494 38.7598 12.4199 39.208 11.3477H39.252V12.0771C39.252 12.7891 39.7266 13.1758 40.3594 13.1758C40.9922 13.1758 41.4404 12.7803 41.4404 12.0771V1.29297C41.4404 0.554688 40.9834 0.141602 40.3418 0.141602C39.7002 0.141602 39.252 0.554688 39.252 1.29297V5.24805H39.1992C38.707 4.21973 37.6523 3.52539 36.3164 3.52539C33.9697 3.52539 32.4492 5.38867 32.4492 8.33301C32.4492 11.2949 33.9697 13.1494 36.3164 13.1494ZM36.9756 11.3564C35.5605 11.3564 34.6904 10.1963 34.6904 8.3418C34.6904 6.49609 35.5693 5.32715 36.9756 5.32715C38.3555 5.32715 39.2607 6.51367 39.2607 8.3418C39.2607 10.1875 38.3555 11.3564 36.9756 11.3564Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M44.0508 13.1494C44.6396 13.1494 44.9736 12.8594 45.1846 12.1738L46.0195 9.76562H50.7568L51.5918 12.1914C51.7939 12.8682 52.1367 13.1494 52.752 13.1494C53.4111 13.1494 53.8857 12.7188 53.8857 12.1035C53.8857 11.9014 53.8418 11.6992 53.7363 11.4092L50.0449 1.38965C49.7285 0.537109 49.2188 0.167969 48.3838 0.167969C47.5576 0.167969 47.0479 0.554688 46.7402 1.39844L43.0576 11.4092C42.9521 11.6816 42.9082 11.9277 42.9082 12.1035C42.9082 12.7451 43.3564 13.1494 44.0508 13.1494ZM46.5557 7.97266L48.3398 2.55859H48.4014L50.2031 7.97266H46.5557Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M60.1172 13.2549C62.8594 13.2549 64.8545 11.4004 64.8545 8.8252C64.8545 6.42578 63.1406 4.66797 60.6973 4.66797C58.9746 4.66797 57.709 5.54688 57.208 6.71582H57.1641V6.58398C57.208 3.66602 58.2275 1.89941 60.1436 1.89941C61.084 1.89941 61.7607 2.26855 62.3496 3.07715C62.7012 3.52539 62.9824 3.73633 63.4307 3.73633C64.0283 3.73633 64.3975 3.34082 64.3975 2.82227C64.3975 2.57617 64.3359 2.35645 64.1953 2.10156C63.5625 0.897461 62.0859 0.0537109 60.1523 0.0537109C56.9268 0.0537109 54.9932 2.57617 54.9932 6.80371C54.9932 8.24512 55.2305 9.45801 55.6963 10.4336C56.5752 12.2881 58.1396 13.2549 60.1172 13.2549ZM60.082 11.4092C58.667 11.4092 57.5508 10.293 57.5508 8.86914C57.5508 7.4541 58.6494 6.41699 60.1084 6.41699C61.5674 6.41699 62.6309 7.4541 62.6221 8.91309C62.6221 10.3018 61.4971 11.4092 60.082 11.4092Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M68.1328 8.83398C68.8447 8.83398 69.416 8.27148 69.416 7.55078C69.416 6.83008 68.8447 6.25879 68.1328 6.25879C67.4121 6.25879 66.8408 6.83008 66.8408 7.55078C66.8408 8.27148 67.4121 8.83398 68.1328 8.83398Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M73.3359 8.83398C74.0479 8.83398 74.6191 8.27148 74.6191 7.55078C74.6191 6.83008 74.0479 6.25879 73.3359 6.25879C72.6152 6.25879 72.0439 6.83008 72.0439 7.55078C72.0439 8.27148 72.6152 8.83398 73.3359 8.83398Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M78.5391 8.83398C79.251 8.83398 79.8223 8.27148 79.8223 7.55078C79.8223 6.83008 79.251 6.25879 78.5391 6.25879C77.8184 6.25879 77.2471 6.83008 77.2471 7.55078C77.2471 8.27148 77.8184 8.83398 78.5391 8.83398Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M83.7422 8.83398C84.4541 8.83398 85.0254 8.27148 85.0254 7.55078C85.0254 6.83008 84.4541 6.25879 83.7422 6.25879C83.0215 6.25879 82.4502 6.83008 82.4502 7.55078C82.4502 8.27148 83.0215 8.83398 83.7422 8.83398Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M92.2148 13.2549C94.957 13.2549 96.9521 11.4004 96.9521 8.8252C96.9521 6.42578 95.2383 4.66797 92.7949 4.66797C91.0723 4.66797 89.8066 5.54688 89.3057 6.71582H89.2617V6.58398C89.3057 3.66602 90.3252 1.89941 92.2412 1.89941C93.1816 1.89941 93.8584 2.26855 94.4473 3.07715C94.7988 3.52539 95.0801 3.73633 95.5283 3.73633C96.126 3.73633 96.4951 3.34082 96.4951 2.82227C96.4951 2.57617 96.4336 2.35645 96.293 2.10156C95.6602 0.897461 94.1836 0.0537109 92.25 0.0537109C89.0244 0.0537109 87.0908 2.57617 87.0908 6.80371C87.0908 8.24512 87.3281 9.45801 87.7939 10.4336C88.6729 12.2881 90.2373 13.2549 92.2148 13.2549ZM92.1797 11.4092C90.7646 11.4092 89.6484 10.293 89.6484 8.86914C89.6484 7.4541 90.7471 6.41699 92.2061 6.41699C93.665 6.41699 94.7285 7.4541 94.7197 8.91309C94.7197 10.3018 93.5947 11.4092 92.1797 11.4092Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M103.377 13.2549C106.497 13.2549 108.352 10.6973 108.352 6.63672C108.352 2.57617 106.479 0.0625 103.377 0.0625C100.266 0.0625 98.3848 2.59375 98.3848 6.64551C98.3848 10.7148 100.248 13.2549 103.377 13.2549ZM103.377 11.4004C101.654 11.4004 100.67 9.64258 100.67 6.63672C100.67 3.68359 101.672 1.91699 103.377 1.91699C105.073 1.91699 106.066 3.6748 106.066 6.64551C106.066 9.65137 105.091 11.4004 103.377 11.4004Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M117.167 13.1758C117.8 13.1758 118.248 12.7715 118.248 12.0596V10.5654H119.127C119.733 10.5654 120.094 10.1875 120.094 9.63379C120.094 9.08887 119.733 8.70215 119.136 8.70215H118.248V1.81152C118.248 0.756836 117.554 0.141602 116.385 0.141602C115.453 0.141602 114.899 0.52832 114.073 1.75879C112.553 3.99121 111.111 6.16211 110.224 7.75293C109.872 8.38574 109.731 8.79883 109.731 9.29102C109.731 10.0469 110.268 10.5654 111.085 10.5654H116.086V12.0596C116.086 12.7715 116.543 13.1758 117.167 13.1758ZM116.121 8.75488H111.788V8.69336C112.816 6.82129 114.073 4.92285 116.086 2.04004H116.121V8.75488Z",fill:"var(--ck-body-color)"}),jsxRuntimeExports.jsx("path",{d:"M126.105 13.2549C128.918 13.2549 130.869 11.4355 130.869 8.78125C130.869 6.35547 129.138 4.6416 126.712 4.6416C125.438 4.6416 124.392 5.13379 123.855 5.9248H123.812L124.146 2.17188H129.27C129.85 2.17188 130.228 1.80273 130.228 1.24023C130.228 0.686523 129.85 0.317383 129.27 0.317383H123.803C122.81 0.317383 122.3 0.72168 122.221 1.72363L121.816 6.51367C121.808 6.56641 121.808 6.60156 121.808 6.6543C121.79 7.26953 122.15 7.78809 122.88 7.78809C123.398 7.78809 123.618 7.67383 124.146 7.14648C124.629 6.67188 125.323 6.34668 126.123 6.34668C127.617 6.34668 128.681 7.38379 128.681 8.84277C128.681 10.3457 127.617 11.4092 126.114 11.4092C124.893 11.4092 124.049 10.8027 123.618 9.77441C123.381 9.30859 123.091 9.12402 122.616 9.12402C122.019 9.12402 121.641 9.49316 121.641 10.082C121.641 10.4072 121.72 10.6709 121.843 10.9434C122.467 12.3232 124.154 13.2549 126.105 13.2549Z",fill:"var(--ck-body-color)"})]}),SlideOne=({layoutId:et})=>jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center"},children:[jsxRuntimeExports.jsx(motion.div,{initial:{rotate:90,scale:.2,x:"100%"},animate:{rotate:0,scale:1,x:0},exit:{rotate:40,scale:.1,x:"70%"},style:{zIndex:4,position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:76,height:76,background:"var(--ck-graphic-secondary-background, #6366F1)",borderRadius:"50%",boxShadow:"var(--ck-graphic-secondary-box-shadow, 0px 2px 10px rgba(99, 102, 241, 0.3))"},children:Receive}),jsxRuntimeExports.jsx(MainCircle,{layoutId:et,style:{position:"relative",zIndex:10,margin:"0 -8px",width:112,height:112},children:jsxRuntimeExports.jsxs(MainCircleInner,{style:{background:"var(--ck-graphic-primary-background, var(--ck-body-background))",boxShadow:"var(--ck-graphic-primary-box-shadow, 0px 3px 15px rgba(0, 0, 0, 0.1))"},initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[jsxRuntimeExports.jsx(BgLighten,{}),jsxRuntimeExports.jsx(motion.div,{style:{zIndex:2,position:"relative"},children:jsxRuntimeExports.jsx(Wallet,{})})]},"SlideOneInner")},et),jsxRuntimeExports.jsx(motion.div,{initial:{rotate:-90,scale:.2,x:"-100%"},animate:{rotate:0,scale:1,x:0},exit:{rotate:-40,scale:.1,x:"-70%"},style:{zIndex:4,position:"relative",width:76,height:76,background:"var(--ck-graphic-secondary-background, #3897FB)",borderRadius:"50%",boxShadow:"var(--ck-graphic-secondary-box-shadow, 0px 2px 10px rgba(56, 151, 251, 0.3))"},children:jsxRuntimeExports.jsx(Center,{children:jsxRuntimeExports.jsx("div",{style:{position:"relative",left:-2,top:3},children:Send})})})]}),SlideTwo=({layoutId:et})=>jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsxs("div",{style:{position:"relative",left:-14},children:[jsxRuntimeExports.jsx(MainCircle,{layoutId:et,style:{zIndex:10,position:"absolute",left:15,top:12,width:32,height:32},children:jsxRuntimeExports.jsx(MainCircleInner,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},style:{background:"var(--ck-graphic-primary-background, var(--ck-body-background))",boxShadow:"var(--ck-graphic-primary-box-shadow, 0px 2px 5px rgba(37, 41, 46, 0.16))"},children:jsxRuntimeExports.jsx(Center,{children:jsxRuntimeExports.jsx(Wallet,{})})},"SlideTwoInner")},et),jsxRuntimeExports.jsxs(motion.div,{initial:{scale:.2},animate:{scale:1},exit:{scale:.2},style:{zIndex:7,position:"relative",display:"flex",alignItems:"center",padding:"21px 56px",paddingRight:52,background:"var(--ck-graphic-primary-background, var(--ck-body-background))",boxShadow:"var(--ck-graphic-primary-box-shadow, 0px 2px 9px rgba(0, 0, 0, 0.07))",borderRadius:"var(--ck-border-radius, 16px)"},children:[jsxRuntimeExports.jsx(BgLighten,{}),jsxRuntimeExports.jsx("div",{style:{position:"relative",zIndex:2,top:1,left:1},children:VitalikAddress})]}),jsxRuntimeExports.jsx(motion.div,{style:{zIndex:8,position:"absolute",top:-16,right:-28},initial:{rotate:90,x:-70,scale:.4},animate:{rotate:0,x:0,scale:1},exit:{rotate:0,x:-70,scale:.4},children:jsxRuntimeExports.jsx(Key$1,{id:et})})]})}),SlideThree=({layoutId:et})=>{const o=Math.random();return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsxs(motion.div,{style:{position:"relative"},children:[jsxRuntimeExports.jsxs(MainCircle,{layoutId:et,initial:{rotate:80},style:{zIndex:10,position:"relative",width:128,height:128},children:[jsxRuntimeExports.jsx(MainCircleInner,{initial:{opacity:0,rotate:100},animate:{opacity:1},exit:{opacity:0},style:{overflow:"hidden",background:`var(--ck-graphic-globe-background, radial-gradient( + 82.42% 82.42% at 50% 86.72%, + rgba(255, 255, 255, 0.2) 0%, + rgba(0, 0, 0, 0) 100% + ), + linear-gradient(180deg, #3897FB 0%, #5004F1 100%))`,boxShadow:"var(--ck-graphic-globe-box-shadow, 0px -6px 20px rgba(56, 151, 251, 0.23))"},children:jsxRuntimeExports.jsx(SpinContainer,{style:et?void 0:{animationPlayState:"paused"},children:jsxRuntimeExports.jsxs("svg",{width:"128",height:"128",viewBox:"0 0 128 128",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsxs("g",{children:[jsxRuntimeExports.jsx("circle",{cx:"30",cy:"141",r:"64",stroke:`url(#networkRadialA-${o})`,strokeWidth:"3"}),jsxRuntimeExports.jsx("circle",{cx:"78.8515",cy:"131.123",r:"54.1005",transform:"rotate(-37.4016 78.8515 131.123)",stroke:`url(#networkRadialB-${o})`,strokeWidth:"3"}),jsxRuntimeExports.jsx("circle",{cx:"63.6053",cy:"2.12794",r:"50.8338",transform:"rotate(134.702 63.6053 2.12794)",stroke:`url(#networkRadialC-${o})`,strokeWidth:"3"}),jsxRuntimeExports.jsx("circle",{cx:"126.658",cy:"56.6577",r:"50.3433",transform:"rotate(-105 126.658 56.6577)",stroke:`url(#networkRadialD-${o})`,strokeWidth:"3"}),jsxRuntimeExports.jsx("circle",{cx:"13.6619",cy:"18.9603",r:"46.0247",transform:"rotate(107.362 13.6619 18.9603)",stroke:`url(#networkRadialE-${o})`,strokeWidth:"3"})]}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("radialGradient",{id:`networkRadialA-${o}`,cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(60.5 84) rotate(104.668) scale(77.0097)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-globe-lines, white)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"var(--ck-graphic-globe-lines, white)",stopOpacity:"0"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:`networkRadialB-${o}`,cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(96.1805 81.6717) rotate(97.125) scale(64.7443)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-globe-lines, white)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"var(--ck-graphic-globe-lines, white)",stopOpacity:"0"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:`networkRadialC-${o}`,cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(96.3816 -36.4455) rotate(114.614) scale(57.7177)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-globe-lines, white)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"var(--ck-graphic-globe-lines, white)",stopOpacity:"0"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:`networkRadialD-${o}`,cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(137.86 7.73234) rotate(92.3288) scale(62.743)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-globe-lines, white)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"var(--ck-graphic-globe-lines, white)",stopOpacity:"0"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:`networkRadialE-${o}`,cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(35.3203 -21.566) rotate(104.513) scale(54.8617)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-globe-lines, white)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"var(--ck-graphic-globe-lines, white)",stopOpacity:"0"})]})]})]})})},"SlideThreeInner"),jsxRuntimeExports.jsxs(motion.div,{exit:{opacity:0},children:[jsxRuntimeExports.jsx(motion.div,{initial:et?void 0:{scale:1.1},animate:et?pulseAnim:void 0,transition:{...pulseTransition},style:{position:"absolute",inset:0,borderRadius:"50%",boxShadow:"0 0 0 2px var(--ck-graphic-globe-lines, rgba(126, 112, 243, 1))"}},"pulseA"),jsxRuntimeExports.jsx(motion.div,{initial:et?void 0:{scale:1.2,opacity:.25},animate:et?pulseAnim:void 0,transition:{...pulseTransition,delay:.5},style:{position:"absolute",inset:0,borderRadius:"50%",boxShadow:"0 0 0 2px var(--ck-graphic-globe-lines, rgba(126, 112, 243, 1))"}},"pulseB")]})]},et),jsxRuntimeExports.jsxs(motion.div,{initial:{rotate:-20,scale:.1,y:-10,x:-10},animate:{rotate:0,scale:1,y:0,x:0},exit:{zIndex:3,scale:.2,y:-25,x:15},style:{zIndex:12,borderRadius:"50%",position:"absolute",bottom:-4,right:-4,width:54,height:54,display:"flex",alignItems:"center",justifyContent:"center",padding:13,background:"var(--ck-graphic-compass-background, var(--ck-body-background))",boxShadow:"var(--ck-graphic-compass-box-shadow, 0px 2px 9px rgba(0, 0, 0, 0.15))"},children:[jsxRuntimeExports.jsx(BgLighten,{}),jsxRuntimeExports.jsx(motion.div,{style:{zIndex:2,position:"absolute"},initial:{rotate:-170},animate:{rotate:0},exit:{rotate:-180,transition:{duration:0}},transition:{type:"spring",stiffness:6,damping:.9,mass:.2},children:Compass})]})]},"SlideThree")})},About=()=>{var et,o;const tt=useLocales({}),rt=useContext(),nt=(o=(et=rt.options)===null||et===void 0?void 0:et.ethereumOnboardingUrl)!==null&&o!==void 0?o:tt.aboutScreen_ctaUrl,[ot,it]=reactExports.useState(!0),[st,at]=reactExports.useState(0),ct=reactExports.useRef(!1),lt=reactExports.useRef(0),dt=[.16,1,.3,1],ht=600;let mt;reactExports.useEffect(()=>()=>clearInterval(mt),[]);const ft=()=>{if(Et.current){const{overflow:It}=getComputedStyle(Et.current);return It!=="visible"}return!1},pt=It=>{it(!1),ft()?gt(It):at(It)},gt=It=>{if(Et.current){const{offsetWidth:Ot}=Et.current;Et.current.scrollLeft=Ot*It,setTimeout(()=>at(It),100)}},yt=()=>{if(!Et.current)return;const{offsetWidth:It,scrollLeft:Ot}=Et.current,Nt=lt.current;lt.current=Ot;const Yt=4;if(Nt-Ot>-Yt&&Nt-Ot{vt()},xt=()=>{const{offsetWidth:It,scrollLeft:Ot}=Et.current,Nt=Math.round(Ot/It);at(Nt)},vt=()=>{ct.current=!0,clearTimeout(mt)},Et=reactExports.useRef(null);reactExports.useEffect(()=>{if(Et.current)return Et.current.addEventListener("scroll",yt),Et.current.addEventListener("touchmove",bt),Et.current.addEventListener("touchend",xt),()=>{Et.current&&(Et.current.removeEventListener("scroll",yt),Et.current.removeEventListener("touchmove",bt),Et.current.removeEventListener("touchend",xt))}},[Et]);const Ct=[jsxRuntimeExports.jsx(SlideOne,{layoutId:"graphicCircle",duration:ht,ease:dt}),jsxRuntimeExports.jsx(SlideTwo,{layoutId:"graphicCircle",duration:ht,ease:dt}),jsxRuntimeExports.jsx(SlideThree,{layoutId:"graphicCircle",duration:ht,ease:dt})],St=[jsxRuntimeExports.jsx(SlideOne,{duration:ht,ease:dt}),jsxRuntimeExports.jsx(SlideTwo,{duration:ht,ease:dt}),jsxRuntimeExports.jsx(SlideThree,{duration:ht,ease:dt})],At=(()=>{var It;switch((It=rt.options)===null||It===void 0?void 0:It.language){case"en-US":case"zh-CN":return 64;default:return 84}})(),kt=[jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalH1,{style:{height:24},$small:!0,children:jsxRuntimeExports.jsx(FitText,{children:tt.aboutScreen_a_h1})}),jsxRuntimeExports.jsx(ModalBody,{style:{height:At},children:jsxRuntimeExports.jsx(FitText,{children:tt.aboutScreen_a_p})})]}),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalH1,{style:{height:24},$small:!0,children:jsxRuntimeExports.jsx(FitText,{children:tt.aboutScreen_b_h1})}),jsxRuntimeExports.jsx(ModalBody,{style:{height:At},children:jsxRuntimeExports.jsx(FitText,{children:tt.aboutScreen_b_p})})]}),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ModalH1,{style:{height:24},$small:!0,children:jsxRuntimeExports.jsx(FitText,{children:tt.aboutScreen_c_h1})}),jsxRuntimeExports.jsx(ModalBody,{style:{height:At},children:jsxRuntimeExports.jsx(FitText,{children:tt.aboutScreen_c_p})})]})];return jsxRuntimeExports.jsxs(PageContent,{children:[jsxRuntimeExports.jsxs(Slider,{children:[jsxRuntimeExports.jsx(ImageContainer$1,{children:jsxRuntimeExports.jsx(MotionConfig,{transition:{duration:ht/1e3,ease:dt},children:jsxRuntimeExports.jsx(AnimatePresence,{initial:!1,onExitComplete:()=>it(!0),children:Ct.map((It,Ot)=>st===Ot&&jsxRuntimeExports.jsx(ImageContainerInner,{style:{position:"absolute"},children:It},Ot))})})}),jsxRuntimeExports.jsx(Slides,{ref:Et,children:jsxRuntimeExports.jsx(AnimatePresence,{children:kt.map((It,Ot)=>jsxRuntimeExports.jsxs(Slide,{$active:st===Ot,children:[jsxRuntimeExports.jsx(MobileImageContainer,{children:jsxRuntimeExports.jsx(MotionConfig,{transition:{duration:0},children:jsxRuntimeExports.jsx(ImageContainerInner,{children:St[Ot]})})}),jsxRuntimeExports.jsx(ModalContent,{style:{gap:8,paddingBottom:0},children:It})]},Ot))})})]}),jsxRuntimeExports.jsx(OrDivider,{children:jsxRuntimeExports.jsx(Dots,{children:kt.map((It,Ot)=>jsxRuntimeExports.jsx(Dot,{$active:st===Ot,onClick:()=>{vt(),pt(Ot)}},Ot))})}),jsxRuntimeExports.jsx(Button$1,{href:nt,arrow:!0,children:tt.aboutScreen_ctaText})]})},Shimmer$1=We` + 0%{ transform: translate(-100%) rotate(-45deg); } + 100%{ transform: translate(100%) rotate(-80deg); } +`,InfoBox=styled.div` + padding: 24px 24px 28px; + border-radius: var(--ck-tertiary-border-radius, 24px); + box-shadow: var(--ck-tertiary-box-shadow, none); + background: var(--ck-body-background-tertiary); + ${ModalBody} { + max-width: none; + } +`,InfoBoxButtons=styled.div` + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; + margin: 5px -8px -12px; + button { + } +`,LearnMoreContainer=styled(motion.div)` + text-align: center; + margin-top: 16px; + margin-bottom: -6px; +`,LearnMoreButton=styled(motion.button)` + appearance: none; + user-select: none; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 10px; + height: 42px; + padding: 0 16px; + border-radius: 6px; + background: none; + color: var(--ck-body-color-muted); + font-size: 15px; + line-height: 18px; + font-weight: 500; + /* will-change: transform; */ + transition: color 200ms ease, transform 100ms ease; + svg { + transition: all 100ms ease-out; + display: block; + position: relative; + top: 2px; + left: 2px; + transform: translateZ(0px); + path, + circle { + transition: all 100ms ease-out; + } + path:last-of-type { + transform-origin: 0 0; + transform: scaleX(1.3) skewY(-12deg); + opacity: 0; + } + circle { + transform: translate(20%, -15%); + } + } + &:hover { + color: var(--ck-body-color-muted-hover); + svg { + path, + circle { + opacity: 1; + transform: none; + } + } + } + &:active { + transform: scale(0.96); + } +`;styled(motion.div)` + display: flex; + flex-direction: column; + gap: 12px; + padding: 0 0 16px; + overflow-y: scroll; + max-height: 20rem; + + &::-webkit-scrollbar { + display: none; + } +`;styled(motion.button)` + cursor: pointer; + user-select: none; + position: relative; + display: flex; + align-items: center; + padding: 0 20px; + width: 100%; + height: 64px; + font-size: 17px; + font-weight: var(--ck-primary-button-font-weight, 500); + line-height: 20px; + text-align: var(--ck-body-button-text-align, left); + transition: 180ms ease; + transition-property: background, color, box-shadow, transform, opacity; + will-change: transform, box-shadow, background-color, color, opacity; + + --fallback-color: var(--ck-primary-button-color); + --fallback-background: var(--ck-primary-button-background); + --fallback-box-shadow: var(--ck-primary-button-box-shadow); + --fallback-border-radius: var(--ck-primary-button-border-radius); + + --color: var(--ck-primary-button-color, var(--fallback-color)); + --background: var(--ck-primary-button-background, var(--fallback-background)); + --box-shadow: var(--ck-primary-button-box-shadow, var(--fallback-box-shadow)); + --border-radius: var( + --ck-primary-button-border-radius, + var(--fallback-border-radius) + ); + + --hover-color: var(--ck-primary-button-hover-color, var(--color)); + --hover-background: var( + --ck-primary-button-hover-background, + var(--background) + ); + --hover-box-shadow: var( + --ck-primary-button-hover-box-shadow, + var(--box-shadow) + ); + --hover-border-radius: var( + --ck-primary-button-hover-border-radius, + var(--border-radius) + ); + + --active-color: var(--ck-primary-button-active-color, var(--hover-color)); + --active-background: var( + --ck-primary-button-active-background, + var(--hover-background) + ); + --active-box-shadow: var( + --ck-primary-button-active-box-shadow, + var(--hover-box-shadow) + ); + --active-border-radius: var( + --ck-primary-button-active-border-radius, + var(--hover-border-radius) + ); + + color: var(--color); + background: var(--background); + box-shadow: var(--box-shadow); + border-radius: var(--border-radius); + + &:disabled { + transition: 180ms ease; + opacity: 0.4; + } + + --bg: var(--background); + &:not(:disabled) { + &:hover { + color: var(--hover-color); + background: var(--hover-background); + box-shadow: var(--hover-box-shadow); + border-radius: var(--hover-border-radius); + --bg: var(--hover-background, var(--background)); + } + &:focus-visible { + transition-duration: 100ms; + color: var(--hover-color); + background: var(--hover-background); + box-shadow: var(--hover-box-shadow); + border-radius: var(--hover-border-radius); + --bg: var(--hover-background, var(--background)); + } + &:active { + color: var(--active-color); + background: var(--active-background); + box-shadow: var(--active-box-shadow); + border-radius: var(--active-border-radius); + --bg: var(--active-background, var(--background)); + } + } +`;styled(motion.span)` + position: relative; + top: var(--ck-recent-badge-top-offset, 0.5px); + display: inline-block; + padding: 10px 7px; + line-height: 0; + font-size: 13px; + font-weight: 400; + border-radius: var(--ck-recent-badge-border-radius, var(--border-radius)); + color: var( + --ck-recent-badge-color, + var(--ck-accent-color, var(--ck-body-color-muted, currentColor)) + ); + background: var(--ck-recent-badge-background, transparent); + overflow: hidden; + span { + display: inline-block; + position: relative; + } + &:before { + z-index: 1; + content: ''; + position: absolute; + inset: 0; + opacity: 0.4; + box-shadow: var(--ck-recent-badge-box-shadow, inset 0 0 0 1px currentColor); + border-radius: inherit; + } + &:after { + z-index: 2; + content: ''; + position: absolute; + inset: -10%; + top: -110%; + aspect-ratio: 1/1; + opacity: 0.7; + background: linear-gradient( + 170deg, + transparent 10%, + var(--ck-recent-badge-background, var(--bg)) 50%, + transparent 90% + ); + animation: ${Shimmer$1} 2s linear infinite; + } +`;styled(motion.span)` + display: flex; + align-items: center; + gap: 9px; + width: 100%; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + padding: 2px 0; + padding-right: 38px; +`;styled(motion.div)` + position: absolute; + right: 20px; + width: 32px; + height: 32px; + overflow: hidden; + svg, + img { + display: block; + position: relative; + pointer-events: none; + overflow: hidden; + border-radius: 27.5%; + width: 100%; + height: 100%; + } +`;var WalletIcon$1=({...et})=>jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"20",height:"19",viewBox:"0 0 20 19",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:[jsxRuntimeExports.jsx("path",{d:"M1.57568 4.60616C1.57568 2.69827 3.12234 1.15161 5.03023 1.15161H15.3939C17.3018 1.15161 18.8484 2.69826 18.8484 4.60616V10.3637C18.8484 12.2716 17.3018 13.8183 15.3939 13.8183H5.03023C3.12234 13.8183 1.57568 12.2716 1.57568 10.3637V4.60616Z",stroke:"currentColor",strokeWidth:"2"}),jsxRuntimeExports.jsx("path",{d:"M1 4.79293C1 2.435 3.31004 0.770014 5.54697 1.51566L12.4561 3.81869C13.8667 4.2889 14.8182 5.60901 14.8182 7.09596V13.6313C14.8182 15.9892 12.5081 17.6542 10.2712 16.9086L3.36212 14.6056C1.95149 14.1353 1 12.8152 1 11.3283V4.79293Z",fill:"var(--ck-body-background)",stroke:"currentColor",strokeWidth:"2"}),jsxRuntimeExports.jsx("circle",{cx:"10.3863",cy:"10.1894",r:"1.32574",fill:"currentColor"})]});const Shimmer=We` + 0%{ transform: translate(-100%) rotate(-45deg); } + 100%{ transform: translate(100%) rotate(-80deg); } +`,ConnectorButton=styled(motion.button)` + display: block; + text-decoration: none; +`,ConnectorLabel=styled(motion.span)``,ConnectorIcon=styled(motion.div)``,styles={desktop:{ConnectorButton:Ae` + cursor: pointer; + user-select: none; + position: relative; + display: flex; + align-items: center; + padding: 0 20px; + width: 100%; + height: 64px; + font-size: 17px; + font-weight: var(--ck-primary-button-font-weight, 500); + line-height: 20px; + text-align: var(--ck-body-button-text-align, left); + transition: 180ms ease; + transition-property: background, color, box-shadow, transform, opacity; + will-change: transform, box-shadow, background-color, color, opacity; + + --fallback-color: var(--ck-primary-button-color); + --fallback-background: var(--ck-primary-button-background); + --fallback-box-shadow: var(--ck-primary-button-box-shadow); + --fallback-border-radius: var(--ck-primary-button-border-radius); + + --color: var(--ck-primary-button-color, var(--fallback-color)); + --background: var( + --ck-primary-button-background, + var(--fallback-background) + ); + --box-shadow: var( + --ck-primary-button-box-shadow, + var(--fallback-box-shadow) + ); + --border-radius: var( + --ck-primary-button-border-radius, + var(--fallback-border-radius) + ); + + --hover-color: var(--ck-primary-button-hover-color, var(--color)); + --hover-background: var( + --ck-primary-button-hover-background, + var(--background) + ); + --hover-box-shadow: var( + --ck-primary-button-hover-box-shadow, + var(--box-shadow) + ); + --hover-border-radius: var( + --ck-primary-button-hover-border-radius, + var(--border-radius) + ); + + --active-color: var(--ck-primary-button-active-color, var(--hover-color)); + --active-background: var( + --ck-primary-button-active-background, + var(--hover-background) + ); + --active-box-shadow: var( + --ck-primary-button-active-box-shadow, + var(--hover-box-shadow) + ); + --active-border-radius: var( + --ck-primary-button-active-border-radius, + var(--hover-border-radius) + ); + + color: var(--color); + background: var(--background); + box-shadow: var(--box-shadow); + border-radius: var(--border-radius); + + &:disabled { + transition: 180ms ease; + opacity: 0.4; + } + + --bg: var(--background); + &:not(:disabled) { + &:hover { + color: var(--hover-color); + background: var(--hover-background); + box-shadow: var(--hover-box-shadow); + border-radius: var(--hover-border-radius); + --bg: var(--hover-background, var(--background)); + } + &:focus-visible { + transition-duration: 100ms; + color: var(--hover-color); + background: var(--hover-background); + box-shadow: var(--hover-box-shadow); + border-radius: var(--hover-border-radius); + --bg: var(--hover-background, var(--background)); + } + &:active { + color: var(--active-color); + background: var(--active-background); + box-shadow: var(--active-box-shadow); + border-radius: var(--active-border-radius); + --bg: var(--active-background, var(--background)); + } + } + `,ConnectorLabel:Ae` + display: flex; + align-items: center; + gap: 9px; + width: 100%; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + padding: 2px 0; + padding-right: 38px; + `,ConnectorIcon:Ae` + position: absolute; + right: 20px; + width: 32px; + height: 32px; + overflow: hidden; + svg, + img { + display: block; + position: relative; + pointer-events: none; + overflow: hidden; + width: 100%; + height: 100%; + } + + &[data-shape='squircle'] { + border-radius: 22.5%; + } + &[data-shape='circle'] { + border-radius: 100%; + } + &[data-shape='square'] { + border-radius: 0; + } + `},mobile:{ConnectorButton:Ae` + text-align: center; + background: none; + max-width: 100%; + overflow: hidden; + `,ConnectorLabel:Ae` + display: block; + text-overflow: ellipsis; + max-width: 100%; + overflow: hidden; + padding: 10px 0 0; + color: var(--ck-body-color); + font-size: 13px; + line-height: 15px; + font-weight: 500; + opacity: 0.75; + `,ConnectorIcon:Ae` + position: relative; + margin: 0 auto; + width: 60px; + height: 60px; + overflow: hidden; + svg, + img { + display: block; + position: relative; + width: 100%; + height: auto; + } + &[data-small='true'] { + svg, + img { + transform: scale(0.8); + } + } + + &[data-shape='squircle'] { + border-radius: 22.5%; + &:before { + content: ''; + z-index: -1; + position: absolute; + inset: 0; + border-radius: inherit; + box-shadow: inset 0 0 0 1px var(--ck-body-background-tertiary); + } + } + &[data-shape='circle'] { + border-radius: 100%; + } + &[data-shape='square'] { + border-radius: 0; + } + `}},RecentlyUsedTag=styled(motion.span)` + position: relative; + top: var(--ck-recent-badge-top-offset, 0.5px); + display: inline-block; + padding: 10px 7px; + line-height: 0; + font-size: 13px; + font-weight: 400; + border-radius: var(--ck-recent-badge-border-radius, var(--border-radius)); + color: var( + --ck-recent-badge-color, + var(--ck-accent-color, var(--ck-body-color-muted, currentColor)) + ); + background: var(--ck-recent-badge-background, transparent); + overflow: hidden; + span { + display: inline-block; + position: relative; + } + &:before { + z-index: 1; + content: ''; + position: absolute; + inset: 0; + opacity: 0.4; + box-shadow: var(--ck-recent-badge-box-shadow, inset 0 0 0 1px currentColor); + border-radius: inherit; + } + &:after { + z-index: 2; + content: ''; + position: absolute; + inset: -10%; + top: -110%; + aspect-ratio: 1/1; + opacity: 0.7; + background: linear-gradient( + 170deg, + transparent 10%, + var(--ck-recent-badge-background, var(--bg)) 50%, + transparent 90% + ); + animation: ${Shimmer} 2s linear infinite; + } +`,ConnectorsContainer=styled.div` + transition: opacity 300ms ease; + min-width: fit-content; + + ${et=>et.$disabled&&Ae` + pointer-events: none; + opacity: 0.4; + `} + + ${et=>et.$mobile?Ae` + display: flex; + align-items: flex-start; + justify-content: space-around; + gap: 22px 6px; + //margin: 0px -10px -20px; + padding: 14px 0px 28px; + + ${ConnectorButton} { + flex-shrink: 0; + width: 80px; + ${styles.mobile.ConnectorButton} + ${ConnectorLabel} { + ${styles.mobile.ConnectorLabel} + ${RecentlyUsedTag} { + display: none; + width: fit-content; + margin: 0 auto; + } + } + ${ConnectorIcon} { + ${styles.mobile.ConnectorIcon} + } + } + `:Ae` + display: flex; + flex-direction: column; + gap: 12px; + + ${ConnectorButton} { + ${styles.desktop.ConnectorButton} + ${ConnectorLabel} { + ${styles.desktop.ConnectorLabel} + } + ${ConnectorIcon} { + ${styles.desktop.ConnectorIcon} + } + } + `} +`;function useChains(){var et;const o=useConfig();return((et=o==null?void 0:o.chains)!==null&&et!==void 0?et:[]).map(rt=>rt)}function useConnect({...et}={}){const o=useContext(),{connect:tt,connectAsync:rt,connectors:nt,...ot}=useConnect$1({...et,mutation:{...et.mutation,onError(it){it.message?it.message!=="User rejected request"&&o.log(it.message,it):o.log("Could not connect.",it)}}});return{connect:({connector:it,chainId:st,mutation:at})=>{var ct;return tt({connector:it,chainId:st??((ct=o.options)===null||ct===void 0?void 0:ct.initialChainId)},at)},connectAsync:async({connector:it,chainId:st,mutation:at})=>{var ct;return rt({connector:it,chainId:st??((ct=o.options)===null||ct===void 0?void 0:ct.initialChainId)},at)},connectors:nt,...ot}}function useWalletConnectUri({enabled:et}={enabled:!0}){const{log:o}=useContext(),[tt,rt]=reactExports.useState(void 0),nt=useWalletConnectConnector(),{isConnected:ot}=useAccount(),{connectAsync:it}=useConnect();return reactExports.useEffect(()=>{if(!et)return;async function st(dt){const{type:ht,data:mt}=dt;o("WC Message",ht,mt),ht==="display_uri"&&rt(mt)}async function at(){o("WC Disconnect"),nt&&ct(nt)}async function ct(dt){const ht=await it({connector:dt});return ht||!1}async function lt(dt){try{await ct(dt)}catch(ht){if(o("catch error"),o(ht),ht.code)switch(ht.code){case 4001:o("error.code - User rejected"),lt(dt);break;default:o("error.code - Unknown Error");break}else o("WalletConnect cannot connect.",ht)}}if(ot)rt(void 0);else{if(!nt||tt)return;if(nt&&!ot)return lt(nt),o("add wc listeners"),nt.emitter.on("message",st),nt.emitter.on("disconnect",at),()=>{o("remove wc listeners"),nt.emitter.off("message",st),nt.emitter.off("disconnect",at)}}},[et,nt,ot]),{uri:tt}}function useChainIsSupported(et){const{chains:o}=useConfig();return et?o.some(tt=>tt.id===et):!1}const Web3Context=React.createContext({connect:{getUri:()=>""},dapp:{chains:[]},account:void 0}),Web3ContextProvider=({enabled:et,children:o})=>{const{uri:tt}=useWalletConnectUri({enabled:et}),{address:rt,chain:nt}=useAccount(),ot=useChainIsSupported(nt==null?void 0:nt.id),it=useChains(),st={connect:{getUri:at=>tt},dapp:{chains:it},account:rt?{chain:nt,chainIsSupported:ot,address:rt}:void 0};return jsxRuntimeExports.jsx(Web3Context.Provider,{value:st,children:o})},useWeb3=()=>React.useContext(Web3Context);function useIsMobile(){const[et,o]=reactExports.useState(isMobile());return reactExports.useEffect(()=>{const tt=()=>{o(isMobile())};return window.addEventListener("resize",tt),()=>window.removeEventListener("resize",tt)},[]),et}const ScrollContainer=styled.div` + position: relative; +`,fadeIn=We` +0%{ opacity:0; } +100%{ opacity:1; } +`,MoreIndicator=styled.div` + z-index: 9; + position: absolute; + left: 0; + right: 0; + bottom: 0.75rem; + display: flex; + justify-content: center; + + transition: opacity 300ms ease; + + span { + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.25rem; + padding: 0.3075rem 0.9375rem 0.375rem; + border-radius: 6rem; + background: var(--ck-tooltip-background); + color: var(--ck-tooltip-color); + font-weight: 500; + font-size: 0.8125rem; + letter-spacing: -0.01rem; + box-shadow: var(--ck-tooltip-shadow); + animation: ${fadeIn} 300ms ease 1000ms both; + + transition: transform 100ms ease; + + &:hover { + transform: scale(1.02); + } + &:active { + transform: scale(0.98); + } + svg { + display: block; + transform: translateX(-0.1875rem); + } + } + + &.hide { + opacity: 0; + pointer-events: none; + } +`,ScrollAreaContainer=styled.div` + --bg: ${({$backgroundColor:et})=>et||"var(--ck-body-background)"}; + --fade-height: 1px; + position: relative; + z-index: 1; + + ${({$mobile:et,$height:o,$mobileDirection:tt})=>et&&tt==="horizontal"?Ae` + overflow-x: scroll; + margin: 0 -24px; + padding: 0 24px; + + &:before, + &:after { + pointer-events: none; + z-index: 10; + content: ''; + display: block; + position: sticky; + top: 0; + bottom: 0; + width: var(--fade-height); + background: var( + --ck-body-divider-secondary, + var(--ck-body-divider) + ); + box-shadow: var(--ck-body-divider-box-shadow); + transition: opacity 300ms ease; + } + &:before { + left: 0; + } + &:after { + right: 0; + } + + &.scroll-start { + &:before { + opacity: 0; + } + } + + &.scroll-end { + &:after { + opacity: 0; + } + } + `:Ae` + max-height: ${o?`${o}px`:"310px"}; + overflow-y: scroll; + padding: 0 10px; + margin: calc(var(--fade-height) * -1) -16px 0 -10px; + + &:before, + &:after { + pointer-events: none; + z-index: 10; + content: ''; + display: block; + position: sticky; + left: 0; + right: 0; + height: var(--fade-height); + background: var( + --ck-body-divider-secondary, + var(--ck-body-divider) + ); + box-shadow: var(--ck-body-divider-box-shadow); + transition: opacity 300ms ease; + } + &:before { + top: 0; + } + &:after { + bottom: 0; + } + + &.scroll-start { + &:before { + opacity: 0; + } + } + + &.scroll-end { + &:after { + opacity: 0; + } + } + `} + + &::-webkit-scrollbar { + width: 6px; + height: 6px; + } + &::-webkit-scrollbar-track { + background: transparent; + } + &::-webkit-scrollbar-thumb { + background: rgba(0, 0, 0, 0); + border-radius: 100px; + } + &:hover::-webkit-scrollbar-thumb { + background: var(--ck-body-color-muted); + } + &::-webkit-scrollbar-thumb:hover { + background: var(--ck-body-color-muted-hover); + } +`,ArrowDown=()=>jsxRuntimeExports.jsx("svg",{width:"11",height:"12",viewBox:"0 0 11 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{d:"M5.49438 1L5.49438 11M5.49438 11L9.5 7M5.49438 11L1.5 7",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round"})}),ScrollArea$2=({children:et,height:o,backgroundColor:tt,mobileDirection:rt})=>{const nt=reactExports.useRef(null),ot=reactExports.useRef(null),it=useIsMobile();return reactExports.useEffect(()=>{const st=nt.current;if(!st)return;st.scrollHeight>st.clientHeight&&ot.current&&ot.current.classList.remove("hide");const at=ct=>{const{scrollTop:lt,scrollHeight:dt,clientHeight:ht,scrollLeft:mt,scrollWidth:ft,clientWidth:pt}=ct.target;ot.current&<>0&&ot.current.classList.add("hide"),lt===0&&mt===0?st.classList.add("scroll-start"):st.classList.remove("scroll-start"),dt-lt===ht&&ft-mt===pt?st.classList.add("scroll-end"):st.classList.remove("scroll-end")};return st.addEventListener("scroll",at),at({target:st}),()=>{st.removeEventListener("scroll",at)}},[nt.current]),jsxRuntimeExports.jsxs(ScrollContainer,{children:[jsxRuntimeExports.jsx(ScrollAreaContainer,{ref:nt,$mobile:it,$height:o,$backgroundColor:tt,$mobileDirection:rt,children:et}),jsxRuntimeExports.jsx(MoreIndicator,{ref:ot,className:"hide",onClick:()=>{nt.current&&nt.current.scrollTo({top:nt.current.scrollHeight,behavior:"smooth"})},children:jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx(ArrowDown,{})," More Available"]})})]})},AlertContainer=styled(motion.div)` + display: flex; + gap: 8px; + position: relative; + border-radius: 9px; + margin: 0 auto; + padding: 10px; + text-align: left; + font-size: 14px; + line-height: 17px; + font-weight: 400; + max-width: 260px; + min-width: 100%; + + border-radius: var(--ck-alert-border-radius, 12px); + color: var(--ck-alert-color, var(--ck-body-color-muted)); + background: var(--ck-alert-background, var(--ck-body-background-secondary)); + box-shadow: var(--ck-alert-box-shadow, var(--ck-body-box-shadow)); + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + padding: 16px; + font-size: 16px; + line-height: 21px; + border-radius: 24px; + text-align: center; + } + + ${et=>{if(et)return Ae` + color: #fff; + background: var(--ck-body-color-danger, red); + `}} +`,IconContainer$3=styled(motion.div)` + width: 24px; + height: 24px; + display: flex; + align-items: center; + justify-content: center; + svg { + display: block; + width: 100%; + height: auto; + } +`,Alert=({children:et,error:o,icon:tt})=>jsxRuntimeExports.jsxs(AlertContainer,{$error:o,children:[tt&&jsxRuntimeExports.jsx(IconContainer$3,{children:tt}),jsxRuntimeExports.jsx("div",{children:et})]});Alert.displayName="Alert";const useLastConnector=()=>{const{storage:et}=useConfig(),[o,tt]=reactExports.useState(null);return reactExports.useEffect(()=>{(async()=>{const ot=await(et==null?void 0:et.getItem("recentConnectorId"));tt(ot??"")})()},[]),{lastConnectorId:o,updateLastConnectorId:nt=>{et==null||et.setItem("recentConnectorId",nt)}}},ConnectorList=()=>{var et;const o=useContext(),tt=useIsMobile(),rt=useWallets(),{lastConnectorId:nt}=useLastConnector(),ot=!((et=o.options)===null||et===void 0)&&et.hideRecentBadge||nt==="walletConnect"?rt:[...rt.filter(it=>nt===it.connector.id),...rt.filter(it=>nt!==it.connector.id)];return jsxRuntimeExports.jsxs(ScrollArea$2,{mobileDirection:"horizontal",children:[ot.length===0&&jsxRuntimeExports.jsx(Alert,{error:!0,children:"No connectors found in ConnectKit config."}),ot.length>0&&jsxRuntimeExports.jsx(ConnectorsContainer,{$mobile:tt,$totalResults:ot.length,children:ot.map(it=>jsxRuntimeExports.jsx(ConnectorItem,{wallet:it,isRecent:it.id===nt},it.id))})]})},ConnectorItem=({wallet:et,isRecent:o})=>{var tt,rt,nt,ot;const{connect:{getUri:it}}=useWeb3(),st=it(),at=useIsMobile(),ct=useContext(),{connect:lt}=useConnect();let dt=!et.isInstalled&&at||et.shouldDeeplinkDesktop&&!at?(tt=et.getWalletConnectDeeplink)===null||tt===void 0?void 0:tt.call(et,st??""):void 0;const ht=at&&isWalletConnectConnector(et.id),mt=(detectBrowser()==="safari"||detectBrowser()==="ios")&&isCoinbaseWalletConnector(et.connector.id);return(ht||mt)&&(dt=void 0),jsxRuntimeExports.jsxs(ConnectorButton,{type:"button",as:dt?"a":void 0,href:dt||void 0,disabled:ct.route!==routes.CONNECTORS,onClick:dt?void 0:()=>{ht?ct.setRoute(routes.MOBILECONNECTORS):(mt&<({connector:et==null?void 0:et.connector}),ct.setRoute(routes.CONNECT),ct.setConnector({id:et.id}))},children:[jsxRuntimeExports.jsx(ConnectorIcon,{"data-small":et.iconShouldShrink,"data-shape":et.iconShape,children:(rt=et.iconConnector)!==null&&rt!==void 0?rt:et.icon}),jsxRuntimeExports.jsxs(ConnectorLabel,{children:[at&&(nt=et.shortName)!==null&&nt!==void 0?nt:et.name,!(!((ot=ct.options)===null||ot===void 0)&&ot.hideRecentBadge)&&o&&jsxRuntimeExports.jsx(RecentlyUsedTag,{children:jsxRuntimeExports.jsx("span",{children:"Recent"})})]})]})},Wallets=()=>{var et,o,tt,rt,nt;const ot=useContext(),it=useLocales({}),st=useIsMobile();return jsxRuntimeExports.jsxs(PageContent,{style:{width:312},children:[jsxRuntimeExports.jsx(ConnectorList,{}),st?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsxs(InfoBox,{children:[jsxRuntimeExports.jsxs(ModalContent,{style:{padding:0,textAlign:"left"},children:[jsxRuntimeExports.jsx(ModalH1,{$small:!0,children:it.connectorsScreen_h1}),jsxRuntimeExports.jsx(ModalBody,{children:it.connectorsScreen_p})]}),jsxRuntimeExports.jsxs(InfoBoxButtons,{children:[!(!((et=ot.options)===null||et===void 0)&&et.hideQuestionMarkCTA)&&jsxRuntimeExports.jsx(Button$1,{variant:"tertiary",onClick:()=>ot.setRoute(routes.ABOUT),children:it.learnMore}),!(!((o=ot.options)===null||o===void 0)&&o.hideNoWalletCTA)&&jsxRuntimeExports.jsx(Button$1,{variant:"tertiary",onClick:()=>ot.setRoute(routes.ONBOARDING),children:it.getWallet})]})]})}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:!(!((tt=ot.options)===null||tt===void 0)&&tt.hideNoWalletCTA)&&jsxRuntimeExports.jsx(LearnMoreContainer,{children:jsxRuntimeExports.jsxs(LearnMoreButton,{onClick:()=>ot.setRoute(routes.ONBOARDING),children:[jsxRuntimeExports.jsx(WalletIcon$1,{})," ",it.connectorsScreen_newcomer]})})}),((rt=ot.options)===null||rt===void 0?void 0:rt.disclaimer)&&jsxRuntimeExports.jsx(Disclaimer,{style:{visibility:"hidden",pointerEvents:"none"},children:jsxRuntimeExports.jsx("div",{children:(nt=ot.options)===null||nt===void 0?void 0:nt.disclaimer})})]})},WalletItem=styled.div` + text-align: center; + transition: opacity 100ms ease; + opacity: ${et=>et.$waiting?.4:1}; +`,WalletIcon=styled.div` + z-index: 9; + position: relative; + margin: 0 auto 10px; + border-radius: 16px; + width: 60px; + height: 60px; + overflow: hidden; + background: rgba(0, 0, 0, 0.04); + ${et=>et.$outline&&` + &:before { + content: ''; + z-index: 2; + position: absolute; + inset: 0; + border-radius: inherit; + box-shadow: inset 0 0 0 1px var(--ck-body-background-tertiary); + }`} + svg { + display: block; + position: relative; + width: 100%; + height: auto; + } +`,WalletLabel=styled.div` + color: var(--ck-body-color); + font-size: 13px; + line-height: 15px; + font-weight: 500; + opacity: 0.75; +`,PulseKeyframes=We` + 0%,100% { opacity:1; } + 50% { opacity:0.5; } +`,WalletList=styled.div` + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 22px 8px; + margin: 0 -10px; + padding: 4px 0 0; + transition: opacity 300ms ease; + ${et=>et.$disabled&&Ae` + pointer-events: none; + opacity: 0.4; + ${WalletItem} { + animation: ${PulseKeyframes} 1s infinite ease-in-out; + } + `} +`,Container$6=styled.div``;function useWalletConnectModal(){const{log:et}=useContext(),{connectAsync:o,connectors:tt}=useConnect(),[rt,nt]=reactExports.useState(!1);return{isOpen:rt,open:async()=>{const ot=document.createElement("style");ot.innerHTML="w3m-modal, wcm-modal{ --wcm-z-index: 2147483647; --w3m-z-index:2147483647; }",document.head.appendChild(ot);const it=tt.find(st=>isWalletConnectConnector(st.id));if(it)try{const at=(await it.getProvider()).rpc.projectId,ct=walletConnect({projectId:at,showQrModal:!0});nt(!0);try{await o({connector:ct})}catch(lt){et("WalletConnect",lt)}nt(!1),document.head.removeChild(ot)}catch(st){et("Could not get WalletConnect provider",st)}else et("No WalletConnect connector available")}}}const IconContainer$2=styled(motion.div)` + transition: all 220ms cubic-bezier(0.175, 0.885, 0.32, 1.1); + display: flex; + align-items: center; + justify-content: center; + width: 16px; + svg { + display: block; + } + svg, + svg path, + svg rect { + transition: inherit; + } + svg path:first-child { + transform-origin: 50% 50%; + fill: var(--bg); + stroke: var(--color); + } + svg rect { + transform-origin: 53% 63%; + fill: var(--bg); + stroke: var(--color); + } + svg path:last-child { + opacity: 0; + stroke: var(--bg); + transform: translate(11.75px, 10px) rotate(90deg) scale(0.6); + } + ${et=>et.$clipboard?Ae` + --color: var(--ck-focus-color) !important; + --bg: var(--ck-body-background); + svg { + transition-delay: 0ms; + path:first-child { + opacity: 0; + transform: rotate(-90deg) scale(0.2); + } + rect { + rx: 10px; + fill: var(--color); + transform: rotate(-90deg) scale(1.45); + } + path:last-child { + transition-delay: 100ms; + opacity: 1; + transform: translate(7.75px, 9.5px); + } + } + `:Ae` + &:hover { + } + &:hover:active { + } + `} +`,CopyToClipboardIcon=({copied:et,small:o})=>jsxRuntimeExports.jsx(IconContainer$2,{$clipboard:et,children:jsxRuntimeExports.jsx(CopyToClipboardIcon$1,{style:{transform:o?"scale(1)":"translateX(3px) scale(1.5)",opacity:o||et?1:.3}})}),Container$5=styled.div` + --color: var(--ck-copytoclipboard-stroke); + --bg: var(--ck-body-background); + transition: all 220ms cubic-bezier(0.175, 0.885, 0.32, 1.1); + + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + + ${et=>et.$disabled?Ae` + cursor: not-allowed; + opacity: 0.4; + `:Ae` + &:hover { + --color: var(--ck-body-color-muted); + } + `} +`,OffsetContainer=styled.div` + display: block; + position: relative; + transition: inherit; + svg { + position: absolute; + left: 100%; + display: block; + top: -1px; + margin: 0; + margin-left: 4px; + } +`,CopyToClipboard=({string:et,children:o,variant:tt})=>{const[rt,nt]=reactExports.useState(!1);let ot;const it=()=>{if(!et)return;const st=et.trim();navigator.clipboard&&navigator.clipboard.writeText(st),nt(!0),clearTimeout(ot),ot=setTimeout(()=>nt(!1),1e3)};return tt==="button"?jsxRuntimeExports.jsx(Button$1,{disabled:!et,onClick:it,icon:jsxRuntimeExports.jsx(CopyToClipboardIcon,{copied:rt}),children:o}):jsxRuntimeExports.jsx(Container$5,{onClick:it,$disabled:!et,children:jsxRuntimeExports.jsxs(OffsetContainer,{children:[o,jsxRuntimeExports.jsx(CopyToClipboardIcon,{copied:rt,small:!0})]})})},MoreIcon=jsxRuntimeExports.jsx("svg",{width:"60",height:"60",viewBox:"0 0 60 60",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{d:"M30 42V19M19 30.5H42",stroke:"var(--ck-body-color-muted)",strokeWidth:"3",strokeLinecap:"round"})}),MobileConnectors=()=>{var et,o;const tt=useContext(),rt=useLocales(),{connect:{getUri:nt}}=useWeb3(),ot=nt(),{open:it,isOpen:st}=useWalletConnectModal(),at=useWallets(),ct=(et=Object.keys(walletConfigs).filter(dt=>{const ht=walletConfigs[dt];return!(at.find(mt=>mt.connector.id===dt)||!ht.getWalletConnectDeeplink)}))!==null&&et!==void 0?et:[],lt=dt=>{var ht;const mt=(ht=dt.getWalletConnectDeeplink)===null||ht===void 0?void 0:ht.call(dt,ot);mt&&(window.location.href=mt)};return jsxRuntimeExports.jsx(PageContent,{style:{width:312},children:jsxRuntimeExports.jsxs(Container$6,{children:[jsxRuntimeExports.jsx(ModalContent,{style:{paddingBottom:0},children:jsxRuntimeExports.jsx(ScrollArea$2,{height:340,children:jsxRuntimeExports.jsxs(WalletList,{$disabled:!ot,children:[ct.sort((dt,ht)=>{var mt,ft,pt,gt;const yt=walletConfigs[dt],bt=walletConfigs[ht],xt=(ft=(mt=yt.name)!==null&&mt!==void 0?mt:yt.shortName)!==null&&ft!==void 0?ft:dt,vt=(gt=(pt=bt.name)!==null&&pt!==void 0?pt:bt.shortName)!==null&>!==void 0?gt:ht;return xt.localeCompare(vt)}).filter(dt=>!(dt==="coinbaseWallet"||dt==="com.coinbase.wallet")).map((dt,ht)=>{const mt=walletConfigs[dt],{name:ft,shortName:pt,iconConnector:gt,icon:yt}=mt;return jsxRuntimeExports.jsxs(WalletItem,{onClick:()=>lt(mt),style:{animationDelay:`${ht*50}ms`},children:[jsxRuntimeExports.jsx(WalletIcon,{$outline:!0,children:gt??yt}),jsxRuntimeExports.jsx(WalletLabel,{children:pt??ft})]},ht)}),jsxRuntimeExports.jsxs(WalletItem,{onClick:it,$waiting:st,children:[jsxRuntimeExports.jsx(WalletIcon,{style:{background:"var(--ck-body-background-secondary)"},children:st?jsxRuntimeExports.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center"},children:jsxRuntimeExports.jsx("div",{style:{width:"50%"},children:jsxRuntimeExports.jsx(Spinner$4,{})})}):MoreIcon}),jsxRuntimeExports.jsx(WalletLabel,{children:rt.more})]})]})})}),((o=tt.options)===null||o===void 0?void 0:o.walletConnectCTA)!=="modal"&&jsxRuntimeExports.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:14,paddingTop:8},children:jsxRuntimeExports.jsx(CopyToClipboard,{variant:"button",string:ot,children:rt.copyToClipboard})})]})})},Content$1=styled(motion.div)` + display: flex; + flex-direction: column; + gap: 6px; + position: relative; + left: 0; + right: 0; + ${ModalContent} { + padding: 0 8px 32px; + gap: 12px; + } +`,dist$1=2,shakeKeyframes=We` + 0%{ transform:none; } + 25%{ transform:translateX(${dist$1}px); } + 50%{ transform:translateX(-${dist$1}px); } + 75%{ transform:translateX(${dist$1}px); } + 100%{ transform:none; } +`,outlineKeyframes=We` + 0%{ opacity:1; } + 100%{ opacity:0; } +`,Container$4=styled(motion.div)` + /* + background: var( + --ck-body-background + ); // To stop the overlay issue during transition for the squircle spinner + */ +`,ConnectingContainer=styled(motion.div)` + display: flex; + align-items: center; + justify-content: center; + margin: 10px auto 16px; + height: 120px; + //transform: scale(1.001); // fixes shifting issue between states +`,ConnectingAnimation=styled(motion.div)` + user-select: none; + position: relative; + --spinner-error-opacity: 0; + &:before { + content: ''; + position: absolute; + inset: 1px; + opacity: 0; + background: var(--ck-body-color-danger); + ${et=>et.$circle&&Ae` + inset: -5px; + border-radius: 50%; + background: none; + box-shadow: inset 0 0 0 3.5px var(--ck-body-color-danger); + `} + } + ${et=>et.$shake&&Ae` + animation: ${shakeKeyframes} 220ms ease-out both; + &:before { + animation: ${outlineKeyframes} 220ms ease-out 750ms both; + } + `} +`,RetryButton=styled(motion.button)` + z-index: 5; + appearance: none; + position: absolute; + right: 2px; + bottom: 2px; + padding: 0; + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 16px; + cursor: pointer; + overflow: hidden; + background: none; + + color: var(--ck-body-background); + transition: color 200ms ease; + box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.15); + + &:before { + z-index: 3; + content: ''; + position: absolute; + inset: 0; + opacity: 0; + transition: opacity 200ms ease; + background: var(--ck-body-color); + } + + &:hover:before { + opacity: 0.1; + } +`,RetryIconContainer=styled(motion.div)` + position: absolute; + inset: 0; + + &:before { + z-index: 1; + content: ''; + position: absolute; + inset: 3px; + border-radius: 16px; + background: conic-gradient( + from 90deg, + currentColor 10%, + var(--ck-body-color) 80% + ); + } + + svg { + z-index: 2; + display: block; + position: relative; + width: 100%; + height: 100%; + } +`,TooltipWindow=styled(motion.div)` + z-index: 2147483647; + position: fixed; + inset: 0; + pointer-events: none; +`,TooltipContainer=styled(motion.div)` + --shadow: var(--ck-tooltip-shadow); + z-index: 2147483647; + position: absolute; + top: 0; + left: 0; + display: flex; + gap: 8px; + width: fit-content; + align-items: center; + justify-content: center; + border-radius: var( + --ck-tooltip-border-radius, + ${et=>et.$size==="small"?11:14}px + ); + border-radius: ; + padding: 10px 16px 10px 12px; + font-size: 14px; + line-height: 19px; + font-weight: 500; + letter-spacing: -0.1px; + color: var(--ck-tooltip-color); + background: var(--ck-tooltip-background); + box-shadow: var(--shadow); + > span { + z-index: 3; + position: relative; + } + > div { + margin: -4px 0; // offset for icon + } + strong { + color: var(--ck-spinner-color); + } + + .ck-tt-logo { + display: inline-block; + vertical-align: text-bottom; + height: 1em; + width: 1.25em; + svg { + display: block; + height: 100%; + transform: translate(0.5px, -1px) scale(1.75); + } + } +`,TooltipTail=styled(motion.div)` + z-index: 2; + position: absolute; + display: flex; + align-items: center; + justify-content: center; + width: ${et=>et.$size==="small"?14:18}px; + right: 100%; + top: 0; + bottom: 0; + overflow: hidden; + &:before { + content: ''; + position: absolute; + box-shadow: var(--shadow); + width: ${et=>et.$size==="small"?14:18}px; + height: ${et=>et.$size==="small"?14:18}px; + transform: translate(75%, 0) rotate(45deg); + background: var(--ck-tooltip-background); + border-radius: ${et=>et.$size==="small"?2:3}px 0 0 0; + } +`,Tooltip=({children:et,message:o,open:tt,xOffset:rt=0,yOffset:nt=0,delay:ot})=>{var it;const st=useContext(),at=useThemeContext();if(!((it=st.options)===null||it===void 0)&&it.hideTooltips)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:et});const[ct,lt]=reactExports.useState(!1),[dt,ht]=reactExports.useState(!1),[mt,ft]=reactExports.useState("small"),[pt,gt]=reactExports.useState(!1),[yt]=reactExports.useState(st.route),bt=reactExports.useRef(null),[xt,vt]=useMeasure({debounce:pt?0:220,offsetSize:!0,scroll:!0}),Et=()=>{let At=!1;const kt=rt+vt.left+vt.width,It=nt+vt.top+vt.height*.5;return(kt>window.innerWidth||kt<0||It>window.innerHeight||It<0)&&(At=!0),At};return(typeof window<"u"?reactExports.useLayoutEffect:reactExports.useEffect)(()=>{if(!bt.current||vt.top+vt.bottom+vt.left+vt.right+vt.height+vt.width===0)return;const At=rt+vt.left+vt.width,kt=nt+vt.top+vt.height*.5;!pt&&At!==0&&kt!==0&>(!0),bt.current.style.left=`${At}px`,bt.current.style.top=`${kt}px`,ft(bt.current.offsetHeight<=40?"small":"large"),ht(Et())},[vt,tt,ct]),reactExports.useEffect(()=>{st.open||lt(!1)},[st.open]),reactExports.useEffect(()=>{lt(!!tt)},[tt]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(motion.div,{ref:xt,style:tt===void 0?{cursor:"help"}:{},onHoverStart:()=>lt(!0),onHoverEnd:()=>lt(!1),onClick:()=>lt(!1),children:et}),jsxRuntimeExports.jsx(Portal$2,{children:jsxRuntimeExports.jsx(AnimatePresence,{children:yt===st.route&&!dt&&ct&&jsxRuntimeExports.jsx(ResetContainer,{$useTheme:at.theme,$useMode:at.mode,$customTheme:at.customTheme,children:jsxRuntimeExports.jsx(TooltipWindow,{children:jsxRuntimeExports.jsxs(TooltipContainer,{role:"tooltip",$size:mt,ref:bt,initial:"collapsed",animate:pt?"open":{},exit:"collapsed",variants:{collapsed:{transformOrigin:"20px 50%",opacity:0,scale:.9,z:.01,y:"-50%",x:20,transition:{duration:.1}},open:{willChange:"opacity,transform",opacity:1,scale:1,z:.01,y:"-50%",x:20,transition:{ease:[.76,0,.24,1],duration:.15,delay:ot||.5}}},children:[o,jsxRuntimeExports.jsx(TooltipTail,{$size:mt})]})})})})})]})},LogoContainer$4=styled(motion.div)` + z-index: 4; + position: relative; + overflow: hidden; + svg { + z-index: 3; + position: relative; + display: block; + } +`,Logo$1=styled(motion.div)` + z-index: 2; + position: absolute; + overflow: hidden; + inset: 6px; + border-radius: 24px; + background: var(--ck-body-background); + svg, + img { + pointer-events: none; + display: block; + width: 100%; + height: 100%; + } +`,SpinnerContainer$1=styled(motion.div)` + position: absolute; + inset: 1px; + overflow: hidden; +`,Spinner$3=styled(motion.div)` + pointer-events: none; + user-select: none; + z-index: 1; + position: absolute; + inset: -25%; + &:before { + content: ''; + position: absolute; + inset: 0; + background: conic-gradient( + from -90deg, + transparent, + transparent, + transparent, + transparent, + transparent, + var(--ck-spinner-color) + ); + animation: rotateSpinner 1200ms linear infinite; + } + @keyframes rotateSpinner { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } + } +`,SquircleSpinner=({logo:et,connecting:o=!0})=>jsxRuntimeExports.jsxs(LogoContainer$4,{transition:{duration:.5,ease:[.175,.885,.32,.98]},children:[jsxRuntimeExports.jsx(Logo$1,{children:et}),jsxRuntimeExports.jsx(SpinnerContainer$1,{children:jsxRuntimeExports.jsx(AnimatePresence,{children:o&&jsxRuntimeExports.jsx(Spinner$3,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0,transition:{duration:0}}},"Spinner")})}),jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"102",height:"102",viewBox:"0 0 102 102",fill:"none",children:[jsxRuntimeExports.jsx("rect",{x:"7.57895",y:"7.57895",width:"86.8421",height:"86.8421",rx:"19.2211",stroke:"black",strokeOpacity:"0.02",strokeWidth:"1.15789"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M0 0H102V102H0V0ZM7 38.284C7 27.5684 7 22.2106 9.01905 18.0892C10.9522 14.1431 14.1431 10.9522 18.0892 9.01905C22.2106 7 27.5684 7 38.284 7H63.716C74.4316 7 79.7894 7 83.9108 9.01905C87.8569 10.9522 91.0478 14.1431 92.9809 18.0892C95 22.2106 95 27.5684 95 38.284V63.716C95 74.4316 95 79.7894 92.9809 83.9108C91.0478 87.8569 87.8569 91.0478 83.9108 92.9809C79.7894 95 74.4316 95 63.716 95H38.284C27.5684 95 22.2106 95 18.0892 92.9809C14.1431 91.0478 10.9522 87.8569 9.01905 83.9108C7 79.7894 7 74.4316 7 63.716V38.284ZM41.5 0.5H41.4325C34.7246 0.499996 29.6023 0.499994 25.5104 0.823325C21.388 1.14906 18.1839 1.80986 15.3416 3.20227C10.0602 5.78959 5.78959 10.0602 3.20227 15.3416C1.80986 18.1839 1.14906 21.388 0.823325 25.5104C0.499994 29.6023 0.499996 34.7246 0.5 41.4325V41.5V55.5938C0.5 55.6808 0.507407 55.766 0.521624 55.849C0.507407 55.9319 0.5 56.0172 0.5 56.1042V60.5V60.5675C0.499996 67.2754 0.499994 72.3977 0.823325 76.4896C1.14906 80.612 1.80986 83.8161 3.20227 86.6584C5.78959 91.9398 10.0602 96.2104 15.3416 98.7977C18.1839 100.19 21.388 100.851 25.5104 101.177C29.6022 101.5 34.7244 101.5 41.432 101.5H41.4324H41.5H43.4227H60.5H60.5675H60.568C67.2756 101.5 72.3977 101.5 76.4896 101.177C80.612 100.851 83.8161 100.19 86.6584 98.7977C91.9398 96.2104 96.2104 91.9398 98.7977 86.6584C100.19 83.8161 100.851 80.612 101.177 76.4896C101.5 72.3978 101.5 67.2756 101.5 60.568V60.5676V60.5V41.5V41.4324V41.432C101.5 34.7244 101.5 29.6022 101.177 25.5104C100.851 21.388 100.19 18.1839 98.7977 15.3416C96.2104 10.0602 91.9398 5.78959 86.6584 3.20227C83.8161 1.80986 80.612 1.14906 76.4896 0.823325C72.3977 0.499994 67.2754 0.499996 60.5675 0.5H60.5H41.5ZM3.5 56.1042C3.5 56.0172 3.49259 55.9319 3.47838 55.849C3.49259 55.766 3.5 55.6808 3.5 55.5938V41.5C3.5 34.7112 3.50109 29.7068 3.814 25.7467C4.1256 21.8032 4.73946 19.0229 5.89635 16.6614C8.19077 11.9779 11.9779 8.19077 16.6614 5.89635C19.0229 4.73946 21.8032 4.1256 25.7467 3.814C29.7068 3.50109 34.7112 3.5 41.5 3.5H60.5C67.2888 3.5 72.2932 3.50109 76.2533 3.814C80.1968 4.1256 82.977 4.73946 85.3386 5.89635C90.022 8.19077 93.8092 11.9779 96.1036 16.6614C97.2605 19.0229 97.8744 21.8032 98.186 25.7467C98.4989 29.7068 98.5 34.7112 98.5 41.5V60.5C98.5 67.2888 98.4989 72.2932 98.186 76.2533C97.8744 80.1968 97.2605 82.9771 96.1036 85.3386C93.8092 90.022 90.022 93.8092 85.3386 96.1036C82.977 97.2605 80.1968 97.8744 76.2533 98.186C72.2932 98.4989 67.2888 98.5 60.5 98.5H43.4227H41.5C34.7112 98.5 29.7068 98.4989 25.7467 98.186C21.8032 97.8744 19.0229 97.2605 16.6614 96.1036C11.9779 93.8092 8.19077 90.022 5.89635 85.3386C4.73946 82.9771 4.1256 80.1968 3.814 76.2533C3.50109 72.2932 3.5 67.2888 3.5 60.5V56.1042Z",fill:"var(--ck-body-background)"})]})]}),BrowserIconContainer=styled(motion.div)` + display: flex; + align-items: center; + justify-content: center; + max-width: 32px; + max-height: 32px; + width: 100%; + height: 100%; + svg { + display: block; + width: 100%; + height: 100%; + } +`,Chrome=jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:20,height:20,viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("g",{filter:"url(#filter0_ii_927_5781)",children:jsxRuntimeExports.jsxs("g",{clipPath:"url(#clip0_927_5781)",children:[jsxRuntimeExports.jsx("path",{d:"M1.58771 0V12.2727H6.06498L10.0002 5.45455H20.0002V0H1.58771Z",fill:"#DB4437"}),jsxRuntimeExports.jsx("path",{d:"M1.58771 0V12.2727H6.06498L10.0002 5.45455H20.0002V0H1.58771Z",fill:"url(#paint0_linear_927_5781)"}),jsxRuntimeExports.jsx("path",{d:"M6.17038 12.2272L1.64538 4.46582L1.57947 4.57946L6.07265 12.284L6.17038 12.2272Z",fill:"black",fillOpacity:"0.15"}),jsxRuntimeExports.jsx("path",{d:"M0 20.0003H9.51932L13.9375 15.5821V12.273H6.0625L0 1.87305V20.0003Z",fill:"#0F9D58"}),jsxRuntimeExports.jsx("path",{d:"M0 20.0003H9.51932L13.9375 15.5821V12.273H6.0625L0 1.87305V20.0003Z",fill:"url(#paint1_linear_927_5781)"}),jsxRuntimeExports.jsx("path",{d:"M13.8412 12.4208L13.7469 12.3662L9.38324 19.9969H9.51392L13.8435 12.4242L13.8412 12.4208Z",fill:"#263238",fillOpacity:"0.15"}),jsxRuntimeExports.jsx("path",{d:"M10.0006 5.45459L13.9381 12.2728L9.51996 20H20.0006V5.45459H10.0006Z",fill:"#FFCD40"}),jsxRuntimeExports.jsx("path",{d:"M10.0006 5.45459L13.9381 12.2728L9.51996 20H20.0006V5.45459H10.0006Z",fill:"url(#paint2_linear_927_5781)"}),jsxRuntimeExports.jsx("path",{d:"M9.9996 5.45459L13.9371 12.2728L9.51892 20H19.9996V5.45459H9.9996Z",fill:"#FFCD40"}),jsxRuntimeExports.jsx("path",{d:"M9.9996 5.45459L13.9371 12.2728L9.51892 20H19.9996V5.45459H9.9996Z",fill:"url(#paint3_linear_927_5781)"}),jsxRuntimeExports.jsx("path",{d:"M1.58691 0V12.2727H6.06419L9.99941 5.45455H19.9994V0H1.58691Z",fill:"#DB4437"}),jsxRuntimeExports.jsx("path",{d:"M1.58691 0V12.2727H6.06419L9.99941 5.45455H19.9994V0H1.58691Z",fill:"url(#paint4_linear_927_5781)"}),jsxRuntimeExports.jsx("path",{d:"M10 5.45459V7.83527L18.9091 5.45459H10Z",fill:"url(#paint5_radial_927_5781)"}),jsxRuntimeExports.jsx("path",{d:"M0 19.9998H9.51932L11.9318 15.9089L13.9375 12.2726H6.0625L0 1.87256V19.9998Z",fill:"#0F9D58"}),jsxRuntimeExports.jsx("path",{d:"M0 19.9998H9.51932L12.1023 15.5112L13.9375 12.2726H6.0625L0 1.87256V19.9998Z",fill:"url(#paint6_linear_927_5781)"}),jsxRuntimeExports.jsx("path",{d:"M1.58771 4.59668L8.09339 11.1012L6.06384 12.2728L1.58771 4.59668Z",fill:"url(#paint7_radial_927_5781)"}),jsxRuntimeExports.jsx("path",{d:"M9.52661 19.9884L11.9084 11.1021L13.938 12.2725L9.52661 19.9884Z",fill:"url(#paint8_radial_927_5781)"}),jsxRuntimeExports.jsx("path",{d:"M10.0003 14.5455C12.5107 14.5455 14.5458 12.5104 14.5458 10C14.5458 7.48966 12.5107 5.45459 10.0003 5.45459C7.48996 5.45459 5.4549 7.48966 5.4549 10C5.4549 12.5104 7.48996 14.5455 10.0003 14.5455Z",fill:"#F1F1F1"}),jsxRuntimeExports.jsx("path",{d:"M9.99995 13.6365C12.0083 13.6365 13.6363 12.0084 13.6363 10.0001C13.6363 7.99183 12.0083 6.36377 9.99995 6.36377C7.99164 6.36377 6.36359 7.99183 6.36359 10.0001C6.36359 12.0084 7.99164 13.6365 9.99995 13.6365Z",fill:"#4285F4"}),jsxRuntimeExports.jsx("path",{d:"M10.0003 5.34082C7.48899 5.34082 5.4549 7.37491 5.4549 9.88628V9.99991C5.4549 7.48855 7.48899 5.45446 10.0003 5.45446H20.0003V5.34082H10.0003Z",fill:"black",fillOpacity:"0.2"}),jsxRuntimeExports.jsx("path",{d:"M13.9318 12.273C13.1455 13.6299 11.6818 14.5458 10 14.5458C8.31818 14.5458 6.85227 13.6299 6.06818 12.273H6.06364L0 1.87305V1.98668L6.06818 12.3867C6.85455 13.7435 8.31818 14.6594 10 14.6594C11.6818 14.6594 13.1455 13.7446 13.9318 12.3867H13.9375V12.273H13.9307H13.9318Z",fill:"white",fillOpacity:"0.1"}),jsxRuntimeExports.jsx("path",{opacity:"0.1",d:"M10.1133 5.45459C10.094 5.45459 10.0758 5.45686 10.0565 5.458C12.5406 5.48868 14.5452 7.50913 14.5452 10C14.5452 12.491 12.5406 14.5114 10.0565 14.5421C10.0758 14.5421 10.094 14.5455 10.1133 14.5455C12.6247 14.5455 14.6588 12.5114 14.6588 10C14.6588 7.48868 12.6247 5.45459 10.1133 5.45459Z",fill:"black"}),jsxRuntimeExports.jsx("path",{d:"M13.9769 12.4204C14.3632 11.7522 14.5871 10.9795 14.5871 10.1522C14.5874 9.68602 14.5157 9.22262 14.3746 8.77832C14.4826 9.16696 14.5451 9.57377 14.5451 9.99764C14.5451 10.8249 14.3212 11.5976 13.9348 12.2658L13.9371 12.2704L9.51892 19.9976H9.65074L13.9769 12.4204Z",fill:"white",fillOpacity:"0.2"}),jsxRuntimeExports.jsx("path",{d:"M10 0.113636C15.5034 0.113636 19.9682 4.56023 20 10.0568C20 10.0375 20.0011 10.0193 20.0011 10C20.0011 4.47727 15.5239 0 10.0011 0C4.47841 0 0 4.47727 0 10C0 10.0193 0.00113639 10.0375 0.00113639 10.0568C0.0318182 4.56023 4.49659 0.113636 10 0.113636Z",fill:"white",fillOpacity:"0.2"}),jsxRuntimeExports.jsx("path",{d:"M10 19.8865C15.5034 19.8865 19.9682 15.4399 20 9.94336C20 9.96268 20.0011 9.98086 20.0011 10.0002C20.0011 15.5229 15.5239 20.0002 10.0011 20.0002C4.47841 20.0002 0 15.5229 0 10.0002C0 9.98086 0.00113639 9.96268 0.00113639 9.94336C0.0318182 15.4399 4.49659 19.8865 10.0011 19.8865H10Z",fill:"black",fillOpacity:"0.15"})]})}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("filter",{id:"filter0_ii_927_5781",x:0,y:"-0.235294",width:20,height:"20.4706",filterUnits:"userSpaceOnUse",colorInterpolationFilters:"sRGB",children:[jsxRuntimeExports.jsx("feFlood",{floodOpacity:0,result:"BackgroundImageFix"}),jsxRuntimeExports.jsx("feBlend",{mode:"normal",in:"SourceGraphic",in2:"BackgroundImageFix",result:"shape"}),jsxRuntimeExports.jsx("feColorMatrix",{in:"SourceAlpha",type:"matrix",values:"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0",result:"hardAlpha"}),jsxRuntimeExports.jsx("feOffset",{dy:"0.235294"}),jsxRuntimeExports.jsx("feGaussianBlur",{stdDeviation:"0.235294"}),jsxRuntimeExports.jsx("feComposite",{in2:"hardAlpha",operator:"arithmetic",k2:-1,k3:1}),jsxRuntimeExports.jsx("feColorMatrix",{type:"matrix",values:"0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.25 0"}),jsxRuntimeExports.jsx("feBlend",{mode:"normal",in2:"shape",result:"effect1_innerShadow_927_5781"}),jsxRuntimeExports.jsx("feColorMatrix",{in:"SourceAlpha",type:"matrix",values:"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0",result:"hardAlpha"}),jsxRuntimeExports.jsx("feOffset",{dy:"-0.235294"}),jsxRuntimeExports.jsx("feGaussianBlur",{stdDeviation:"0.235294"}),jsxRuntimeExports.jsx("feComposite",{in2:"hardAlpha",operator:"arithmetic",k2:-1,k3:1}),jsxRuntimeExports.jsx("feColorMatrix",{type:"matrix",values:"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.12 0"}),jsxRuntimeExports.jsx("feBlend",{mode:"normal",in2:"effect1_innerShadow_927_5781",result:"effect2_innerShadow_927_5781"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_927_5781",x1:"2.42521",y1:"7.61591",x2:"8.39112",y2:"4.13068",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#A52714",stopOpacity:"0.6"}),jsxRuntimeExports.jsx("stop",{offset:"0.66",stopColor:"#A52714",stopOpacity:0})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint1_linear_927_5781",x1:"11.6932",y1:"17.7844",x2:"5.06136",y2:"13.8981",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#055524",stopOpacity:"0.4"}),jsxRuntimeExports.jsx("stop",{offset:"0.33",stopColor:"#055524",stopOpacity:0})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint2_linear_927_5781",x1:"12.9438",y1:"4.75004",x2:"14.6143",y2:"12.0569",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#EA6100",stopOpacity:"0.3"}),jsxRuntimeExports.jsx("stop",{offset:"0.66",stopColor:"#EA6100",stopOpacity:0})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint3_linear_927_5781",x1:"12.9428",y1:"4.75004",x2:"14.6132",y2:"12.0569",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#EA6100",stopOpacity:"0.3"}),jsxRuntimeExports.jsx("stop",{offset:"0.66",stopColor:"#EA6100",stopOpacity:0})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint4_linear_927_5781",x1:"2.42441",y1:"7.61591",x2:"8.39032",y2:"4.13068",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#A52714",stopOpacity:"0.6"}),jsxRuntimeExports.jsx("stop",{offset:"0.66",stopColor:"#A52714",stopOpacity:0})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint5_radial_927_5781",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.56818 5.44891) scale(9.55455)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#3E2723",stopOpacity:"0.2"}),jsxRuntimeExports.jsx("stop",{offset:1,stopColor:"#3E2723",stopOpacity:0})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint6_linear_927_5781",x1:"11.6932",y1:"17.7839",x2:"5.06136",y2:"13.8976",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#055524",stopOpacity:"0.4"}),jsxRuntimeExports.jsx("stop",{offset:"0.33",stopColor:"#055524",stopOpacity:0})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint7_radial_927_5781",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(1.57975 4.60463) scale(8.86818)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#3E2723",stopOpacity:"0.2"}),jsxRuntimeExports.jsx("stop",{offset:1,stopColor:"#3E2723",stopOpacity:0})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint8_radial_927_5781",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.97775 10.0157) scale(9.98523)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#263238",stopOpacity:"0.2"}),jsxRuntimeExports.jsx("stop",{offset:1,stopColor:"#263238",stopOpacity:0})]}),jsxRuntimeExports.jsx("clipPath",{id:"clip0_927_5781",children:jsxRuntimeExports.jsx("rect",{width:20,height:20,rx:10,fill:"white"})})]})]}),FireFox=jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:20,height:20,viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsxs("g",{clipPath:"url(#clip0_927_5847)",children:[jsxRuntimeExports.jsx("path",{d:"M19.011 6.71023C18.5898 5.69685 17.7355 4.60269 17.0665 4.25681C17.5436 5.18063 17.8747 6.17276 18.0481 7.19792L18.0499 7.21417C16.954 4.48315 15.0963 3.38023 13.5782 0.981835C13.5014 0.860539 13.4246 0.738994 13.3498 0.610696C13.3071 0.537418 13.2728 0.471393 13.2431 0.410621C13.1801 0.288713 13.1316 0.159878 13.0985 0.0267267C13.0985 0.0205825 13.0963 0.0146369 13.0923 0.0100242C13.0882 0.00541151 13.0826 0.00245454 13.0765 0.00171737C13.0705 7.85858e-05 13.0642 7.85858e-05 13.0582 0.00171737C13.057 0.00171737 13.055 0.00396821 13.0535 0.0044684C13.052 0.00496859 13.0487 0.00721943 13.0465 0.00821981L13.0502 0.00171737C10.6156 1.42725 9.78901 4.06574 9.71399 5.38624C8.74136 5.45292 7.81141 5.81121 7.04549 6.41437C6.96561 6.34671 6.88212 6.28343 6.79539 6.2248C6.57456 5.45174 6.56514 4.6336 6.76813 3.85566C5.87401 4.28877 5.07954 4.90279 4.43501 5.65884H4.43051C4.04636 5.17191 4.07337 3.5663 4.09538 3.23093C3.98174 3.2766 3.87326 3.33419 3.77176 3.40274C3.43264 3.64477 3.11562 3.91635 2.8244 4.2143C2.49255 4.55075 2.18946 4.91441 1.91831 5.30146V5.30296V5.3012C1.29521 6.18444 0.853213 7.18234 0.617826 8.23731L0.604821 8.30133C0.586564 8.38661 0.52079 8.81377 0.509535 8.90656C0.509535 8.91381 0.508035 8.92056 0.507285 8.92781C0.42244 9.36882 0.369864 9.81542 0.349976 10.2641V10.3141C0.354259 12.7396 1.26772 15.0754 2.91002 16.8604C4.55233 18.6454 6.80415 19.7498 9.22094 19.9556C11.6377 20.1615 14.0439 19.4538 15.9644 17.9723C17.8849 16.4908 19.1803 14.3431 19.5947 11.9532C19.6109 11.8282 19.6242 11.7044 19.6387 11.5781C19.8384 9.92791 19.6222 8.25404 19.01 6.70873L19.011 6.71023ZM7.83928 14.2981C7.88455 14.3198 7.92707 14.3433 7.97358 14.3641L7.98034 14.3684C7.93332 14.3458 7.8863 14.3224 7.83928 14.2981ZM18.0501 7.21692V7.20767L18.0519 7.21792L18.0501 7.21692Z",fill:"url(#paint0_linear_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M19.0109 6.71026C18.5898 5.69688 17.7354 4.60272 17.0664 4.25684C17.5435 5.18066 17.8746 6.17278 18.0481 7.19794V7.20719L18.0498 7.21745C18.797 9.35551 18.689 11.6997 17.7482 13.7599C16.6373 16.1435 13.9493 18.5867 9.7402 18.4667C5.19349 18.3379 1.18699 14.9629 0.439211 10.5437C0.30291 9.84668 0.439211 9.4933 0.507737 8.92684C0.414265 9.36685 0.362102 9.81463 0.351929 10.2643V10.3144C0.356212 12.7399 1.26967 15.0757 2.91198 16.8607C4.55429 18.6456 6.8061 19.7501 9.2229 19.9559C11.6397 20.1617 14.0458 19.4541 15.9664 17.9725C17.8869 16.491 19.1822 14.3434 19.5966 11.9535C19.6129 11.8284 19.6262 11.7046 19.6407 11.5783C19.8403 9.92819 19.6242 8.25431 19.0119 6.70901L19.0109 6.71026Z",fill:"url(#paint1_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M19.0109 6.71026C18.5898 5.69688 17.7354 4.60272 17.0664 4.25684C17.5435 5.18066 17.8746 6.17278 18.0481 7.19794V7.20719L18.0498 7.21745C18.797 9.35551 18.689 11.6997 17.7482 13.7599C16.6373 16.1435 13.9493 18.5867 9.7402 18.4667C5.19349 18.3379 1.18699 14.9629 0.439211 10.5437C0.30291 9.84668 0.439211 9.4933 0.507737 8.92684C0.414265 9.36685 0.362102 9.81463 0.351929 10.2643V10.3144C0.356212 12.7399 1.26967 15.0757 2.91198 16.8607C4.55429 18.6456 6.8061 19.7501 9.2229 19.9559C11.6397 20.1617 14.0458 19.4541 15.9664 17.9725C17.8869 16.491 19.1822 14.3434 19.5966 11.9535C19.6129 11.8284 19.6262 11.7046 19.6407 11.5783C19.8403 9.92819 19.6242 8.25431 19.0119 6.70901L19.0109 6.71026Z",fill:"url(#paint2_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M14.2993 7.84794C14.3203 7.8627 14.3398 7.87745 14.3595 7.89221C14.1161 7.46047 13.813 7.06519 13.4592 6.71802C10.4456 3.70439 12.6696 0.18557 13.0445 0.00550206L13.0483 0C10.6136 1.42553 9.78706 4.06402 9.71204 5.38452C9.82508 5.37677 9.93712 5.36726 10.0527 5.36726C10.9164 5.36893 11.7644 5.59929 12.5103 6.03492C13.2562 6.47055 13.8734 7.09592 14.2993 7.84744V7.84794Z",fill:"url(#paint3_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M10.0577 8.45061C10.0417 8.6917 9.18992 9.52326 8.89206 9.52326C6.13602 9.52326 5.68835 11.1906 5.68835 11.1906C5.8104 12.5947 6.78877 13.7516 7.97146 14.3618C8.02548 14.3898 8.08025 14.4151 8.13502 14.4399C8.22989 14.4819 8.32476 14.5207 8.41963 14.5564C8.82553 14.7 9.25065 14.7821 9.68085 14.7997C14.5127 15.0263 15.448 9.02257 11.9615 7.27942C12.7839 7.1724 13.6168 7.37463 14.2986 7.84688C13.8727 7.09536 13.2555 6.46999 12.5096 6.03436C11.7637 5.59873 10.9158 5.36837 10.052 5.3667C9.93695 5.3667 9.82441 5.3762 9.71136 5.38396C8.73874 5.45064 7.80879 5.80893 7.04286 6.41209C7.19067 6.53714 7.35748 6.7042 7.70886 7.05058C8.36661 7.69857 10.0535 8.36983 10.0572 8.44861L10.0577 8.45061Z",fill:"url(#paint4_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M10.0577 8.45061C10.0417 8.6917 9.18992 9.52326 8.89206 9.52326C6.13602 9.52326 5.68835 11.1906 5.68835 11.1906C5.8104 12.5947 6.78877 13.7516 7.97146 14.3618C8.02548 14.3898 8.08025 14.4151 8.13502 14.4399C8.22989 14.4819 8.32476 14.5207 8.41963 14.5564C8.82553 14.7 9.25065 14.7821 9.68085 14.7997C14.5127 15.0263 15.448 9.02257 11.9615 7.27942C12.7839 7.1724 13.6168 7.37463 14.2986 7.84688C13.8727 7.09536 13.2555 6.46999 12.5096 6.03436C11.7637 5.59873 10.9158 5.36837 10.052 5.3667C9.93695 5.3667 9.82441 5.3762 9.71136 5.38396C8.73874 5.45064 7.80879 5.80893 7.04286 6.41209C7.19067 6.53714 7.35748 6.7042 7.70886 7.05058C8.36661 7.69857 10.0535 8.36983 10.0572 8.44861L10.0577 8.45061Z",fill:"url(#paint5_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M6.59134 6.0923C6.66987 6.14231 6.73464 6.18583 6.79141 6.2251C6.57058 5.45204 6.56117 4.63389 6.76415 3.85596C5.87003 4.28907 5.07556 4.90308 4.43103 5.65913C4.4783 5.65788 5.88432 5.63262 6.59134 6.0923Z",fill:"url(#paint6_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M0.437567 10.5439C1.1856 14.963 5.19185 18.3393 9.73855 18.4668C13.9476 18.5859 16.6361 16.1425 17.7466 13.7601C18.6873 11.6998 18.7954 9.35569 18.0482 7.21762V7.20837C18.0482 7.20111 18.0467 7.19686 18.0482 7.19911L18.0499 7.21537C18.3938 9.46046 17.2519 11.6345 15.4665 13.1076L15.4609 13.1201C11.9821 15.9536 8.6534 14.8292 7.98064 14.3706C7.93363 14.348 7.88661 14.3246 7.83959 14.3003C5.81158 13.3309 4.97352 11.4842 5.15358 9.89862C4.67218 9.90573 4.19905 9.77307 3.79151 9.51672C3.38397 9.26038 3.05952 8.89134 2.85747 8.45433C3.38987 8.1282 3.99692 7.94382 4.62077 7.91878C5.24461 7.89374 5.86448 8.02887 6.42131 8.31128C7.56906 8.83225 8.87507 8.8836 10.0602 8.45433C10.0564 8.37555 8.36954 7.70405 7.71179 7.05631C7.36041 6.70993 7.1936 6.54312 7.04579 6.41782C6.96591 6.35016 6.88243 6.28688 6.7957 6.22825C6.73818 6.18898 6.6734 6.14647 6.59562 6.09545C5.88861 5.63578 4.48258 5.66104 4.43607 5.66229H4.43156C4.04742 5.17535 4.07443 3.56975 4.09644 3.23438C3.9828 3.28005 3.87431 3.33764 3.77282 3.40619C3.4337 3.64822 3.11667 3.91979 2.82546 4.21774C2.49242 4.55325 2.18808 4.91607 1.91562 5.3024V5.3039V5.30215C1.29252 6.18539 0.850521 7.18329 0.615133 8.23825C0.610381 8.25801 0.266002 9.76357 0.435816 10.5444L0.437567 10.5439Z",fill:"url(#paint7_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M13.459 6.71761C13.8128 7.06516 14.1159 7.46087 14.3593 7.89305C14.4126 7.93331 14.4624 7.97333 14.5046 8.01209C16.7022 10.0378 15.5508 12.9014 15.465 13.104C17.2502 11.6332 18.3911 9.45763 18.0485 7.21179C16.952 4.47826 15.0923 3.37535 13.5768 0.976952C13.5 0.855657 13.4232 0.734111 13.3484 0.605813C13.3057 0.532535 13.2714 0.466511 13.2417 0.405738C13.1787 0.283831 13.1302 0.154995 13.0971 0.0218439C13.0971 0.0156997 13.0949 0.0097541 13.0909 0.0051414C13.0868 0.000528701 13.0812 -0.00242828 13.0751 -0.00316545C13.0691 -0.00480423 13.0628 -0.00480423 13.0568 -0.00316545C13.0556 -0.00316545 13.0536 -0.000914601 13.0521 -0.000414413C13.0506 8.57743e-05 13.0473 0.00233662 13.0451 0.00333699C12.6702 0.181154 10.4466 3.70222 13.4602 6.71335L13.459 6.71761Z",fill:"url(#paint8_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M14.5043 8.01315C14.462 7.97439 14.4122 7.93437 14.359 7.8941C14.3392 7.87935 14.3197 7.86459 14.2987 7.84984C13.6169 7.37759 12.784 7.17536 11.9616 7.28238C15.4479 9.02553 14.5125 15.0278 9.68095 14.8027C9.25075 14.785 8.82562 14.703 8.41973 14.5594C8.32486 14.5238 8.22999 14.485 8.13512 14.4428C8.08035 14.4178 8.02558 14.3928 7.97156 14.3648L7.97831 14.369C8.65206 14.829 11.9798 15.9526 15.4586 13.1186L15.4641 13.1061C15.5509 12.9035 16.7023 10.0399 14.5038 8.01415L14.5043 8.01315Z",fill:"url(#paint9_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M5.68842 11.1892C5.68842 11.1892 6.13583 9.52179 8.89212 9.52179C9.18998 9.52179 10.0425 8.69023 10.0578 8.44914C8.8727 8.8784 7.56669 8.82706 6.41894 8.30608C5.86211 8.02367 5.24224 7.88855 4.61839 7.91359C3.99455 7.93863 3.3875 8.123 2.8551 8.44914C3.05715 8.88615 3.3816 9.25518 3.78914 9.51153C4.19668 9.76787 4.66981 9.90053 5.15121 9.89343C4.97165 11.4783 5.80946 13.3247 7.83722 14.2951C7.88249 14.3168 7.925 14.3403 7.97152 14.3611C6.78783 13.7496 5.81046 12.5932 5.68842 11.1899V11.1892Z",fill:"url(#paint10_radial_927_5847)"}),jsxRuntimeExports.jsx("path",{d:"M19.0112 6.71023C18.59 5.69685 17.7357 4.60269 17.0667 4.25681C17.5438 5.18063 17.8749 6.17276 18.0483 7.19792L18.0501 7.21417C16.9542 4.48315 15.0965 3.38023 13.5784 0.981835C13.5016 0.860539 13.4249 0.738994 13.3501 0.610696C13.3073 0.537418 13.2731 0.471393 13.2433 0.410621C13.1803 0.288713 13.1318 0.159878 13.0987 0.0267267C13.0988 0.0205825 13.0966 0.0146369 13.0925 0.0100242C13.0884 0.00541151 13.0828 0.00245454 13.0767 0.00171737C13.0708 7.85859e-05 13.0644 7.85859e-05 13.0585 0.00171737C13.0572 0.00171737 13.0552 0.00396821 13.0537 0.0044684C13.0522 0.00496859 13.049 0.00721943 13.0467 0.00821981L13.0505 0.00171737C10.6158 1.42725 9.78925 4.06574 9.71422 5.38624C9.82726 5.37848 9.9393 5.36898 10.0548 5.36898C10.9186 5.37065 11.7666 5.60101 12.5125 6.03664C13.2584 6.47227 13.8756 7.09764 14.3014 7.84916C13.6196 7.37691 12.7868 7.17468 11.9643 7.2817C15.4506 9.02485 14.5153 15.0271 9.68371 14.802C9.25351 14.7843 8.82838 14.7023 8.42248 14.5587C8.32761 14.5232 8.23275 14.4843 8.13788 14.4421C8.08311 14.4171 8.02834 14.3921 7.97432 14.3641L7.98107 14.3684C7.93405 14.3458 7.88703 14.3224 7.84002 14.2981C7.88528 14.3198 7.9278 14.3433 7.97432 14.3641C6.79062 13.7524 5.81326 12.5959 5.69121 11.1929C5.69121 11.1929 6.13863 9.52554 8.89491 9.52554C9.19277 9.52554 10.0453 8.69398 10.0606 8.45289C10.0568 8.37411 8.36996 7.7026 7.71222 7.05486C7.36084 6.70848 7.19402 6.54167 7.04622 6.41637C6.96634 6.34871 6.88285 6.28543 6.79612 6.2268C6.57529 5.45374 6.56588 4.6356 6.76886 3.85766C5.87474 4.29077 5.08027 4.90479 4.43574 5.66084H4.43124C4.04709 5.17391 4.0741 3.5683 4.09611 3.23293C3.98247 3.2786 3.87399 3.33619 3.77249 3.40474C3.43337 3.64677 3.11635 3.91835 2.82514 4.2163C2.49328 4.55275 2.19019 4.91641 1.91905 5.30345V5.30496V5.30321C1.29595 6.18644 0.853946 7.18434 0.618558 8.23931L0.605554 8.30333C0.587297 8.38861 0.505516 8.82177 0.493762 8.91481C0.418959 9.36194 0.371188 9.81318 0.350708 10.2661V10.3161C0.354992 12.7416 1.26845 15.0774 2.91076 16.8624C4.55307 18.6474 6.80488 19.7518 9.22168 19.9576C11.6385 20.1635 14.0446 19.4558 15.9652 17.9743C17.8857 16.4928 19.181 14.3451 19.5954 11.9552C19.6117 11.8302 19.6249 11.7064 19.6394 11.5801C19.8391 9.92991 19.623 8.25604 19.0107 6.71073L19.0112 6.71023ZM18.0496 7.20817L18.0513 7.21842L18.0496 7.20817Z",fill:"url(#paint11_linear_927_5847)"})]}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_927_5847",x1:"17.728",y1:"3.09786",x2:"1.63621",y2:"18.6237",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{offset:"0.048",stopColor:"#FFF44F"}),jsxRuntimeExports.jsx("stop",{offset:"0.111",stopColor:"#FFE847"}),jsxRuntimeExports.jsx("stop",{offset:"0.225",stopColor:"#FFC830"}),jsxRuntimeExports.jsx("stop",{offset:"0.368",stopColor:"#FF980E"}),jsxRuntimeExports.jsx("stop",{offset:"0.401",stopColor:"#FF8B16"}),jsxRuntimeExports.jsx("stop",{offset:"0.462",stopColor:"#FF672A"}),jsxRuntimeExports.jsx("stop",{offset:"0.534",stopColor:"#FF3647"}),jsxRuntimeExports.jsx("stop",{offset:"0.705",stopColor:"#E31587"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint1_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(17.1052 2.25108) scale(20.2076)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.129",stopColor:"#FFBD4F"}),jsxRuntimeExports.jsx("stop",{offset:"0.186",stopColor:"#FFAC31"}),jsxRuntimeExports.jsx("stop",{offset:"0.247",stopColor:"#FF9D17"}),jsxRuntimeExports.jsx("stop",{offset:"0.283",stopColor:"#FF980E"}),jsxRuntimeExports.jsx("stop",{offset:"0.403",stopColor:"#FF563B"}),jsxRuntimeExports.jsx("stop",{offset:"0.467",stopColor:"#FF3750"}),jsxRuntimeExports.jsx("stop",{offset:"0.71",stopColor:"#F5156C"}),jsxRuntimeExports.jsx("stop",{offset:"0.782",stopColor:"#EB0878"}),jsxRuntimeExports.jsx("stop",{offset:"0.86",stopColor:"#E50080"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint2_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.6024 10.5042) scale(20.2076)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.3",stopColor:"#960E18"}),jsxRuntimeExports.jsx("stop",{offset:"0.351",stopColor:"#B11927",stopOpacity:"0.74"}),jsxRuntimeExports.jsx("stop",{offset:"0.435",stopColor:"#DB293D",stopOpacity:"0.343"}),jsxRuntimeExports.jsx("stop",{offset:"0.497",stopColor:"#F5334B",stopOpacity:"0.094"}),jsxRuntimeExports.jsx("stop",{offset:"0.53",stopColor:"#FF3750",stopOpacity:0})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint3_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(12.1034 -2.25084) scale(14.638)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.132",stopColor:"#FFF44F"}),jsxRuntimeExports.jsx("stop",{offset:"0.252",stopColor:"#FFDC3E"}),jsxRuntimeExports.jsx("stop",{offset:"0.506",stopColor:"#FF9D12"}),jsxRuntimeExports.jsx("stop",{offset:"0.526",stopColor:"#FF980E"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint4_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(7.35173 15.7558) scale(9.62111)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.353",stopColor:"#3A8EE6"}),jsxRuntimeExports.jsx("stop",{offset:"0.472",stopColor:"#5C79F0"}),jsxRuntimeExports.jsx("stop",{offset:"0.669",stopColor:"#9059FF"}),jsxRuntimeExports.jsx("stop",{offset:1,stopColor:"#C139E6"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint5_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(10.5799 8.76923) rotate(-13.5916) scale(5.10194 5.97309)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.206",stopColor:"#9059FF",stopOpacity:0}),jsxRuntimeExports.jsx("stop",{offset:"0.278",stopColor:"#8C4FF3",stopOpacity:"0.064"}),jsxRuntimeExports.jsx("stop",{offset:"0.747",stopColor:"#7716A8",stopOpacity:"0.45"}),jsxRuntimeExports.jsx("stop",{offset:"0.975",stopColor:"#6E008B",stopOpacity:"0.6"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint6_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.35238 1.50057) scale(6.9226)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#FFE226"}),jsxRuntimeExports.jsx("stop",{offset:"0.121",stopColor:"#FFDB27"}),jsxRuntimeExports.jsx("stop",{offset:"0.295",stopColor:"#FFC82A"}),jsxRuntimeExports.jsx("stop",{offset:"0.502",stopColor:"#FFA930"}),jsxRuntimeExports.jsx("stop",{offset:"0.732",stopColor:"#FF7E37"}),jsxRuntimeExports.jsx("stop",{offset:"0.792",stopColor:"#FF7139"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint7_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.8545 -3.00121) scale(29.5361)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.113",stopColor:"#FFF44F"}),jsxRuntimeExports.jsx("stop",{offset:"0.456",stopColor:"#FF980E"}),jsxRuntimeExports.jsx("stop",{offset:"0.622",stopColor:"#FF5634"}),jsxRuntimeExports.jsx("stop",{offset:"0.716",stopColor:"#FF3647"}),jsxRuntimeExports.jsx("stop",{offset:"0.904",stopColor:"#E31587"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint8_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(12.3996 -1.36343) rotate(83.976) scale(21.6445 14.2051)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#FFF44F"}),jsxRuntimeExports.jsx("stop",{offset:"0.06",stopColor:"#FFE847"}),jsxRuntimeExports.jsx("stop",{offset:"0.168",stopColor:"#FFC830"}),jsxRuntimeExports.jsx("stop",{offset:"0.304",stopColor:"#FF980E"}),jsxRuntimeExports.jsx("stop",{offset:"0.356",stopColor:"#FF8B16"}),jsxRuntimeExports.jsx("stop",{offset:"0.455",stopColor:"#FF672A"}),jsxRuntimeExports.jsx("stop",{offset:"0.57",stopColor:"#FF3647"}),jsxRuntimeExports.jsx("stop",{offset:"0.737",stopColor:"#E31587"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint9_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.35233 4.00165) scale(18.4369)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.137",stopColor:"#FFF44F"}),jsxRuntimeExports.jsx("stop",{offset:"0.48",stopColor:"#FF980E"}),jsxRuntimeExports.jsx("stop",{offset:"0.592",stopColor:"#FF5634"}),jsxRuntimeExports.jsx("stop",{offset:"0.655",stopColor:"#FF3647"}),jsxRuntimeExports.jsx("stop",{offset:"0.904",stopColor:"#E31587"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint10_radial_927_5847",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.1041 5.00184) scale(20.1801)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.094",stopColor:"#FFF44F"}),jsxRuntimeExports.jsx("stop",{offset:"0.231",stopColor:"#FFE141"}),jsxRuntimeExports.jsx("stop",{offset:"0.509",stopColor:"#FFAF1E"}),jsxRuntimeExports.jsx("stop",{offset:"0.626",stopColor:"#FF980E"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint11_linear_927_5847",x1:"17.5331",y1:"3.01533",x2:"3.84302",y2:"16.708",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{offset:"0.167",stopColor:"#FFF44F",stopOpacity:"0.8"}),jsxRuntimeExports.jsx("stop",{offset:"0.266",stopColor:"#FFF44F",stopOpacity:"0.634"}),jsxRuntimeExports.jsx("stop",{offset:"0.489",stopColor:"#FFF44F",stopOpacity:"0.217"}),jsxRuntimeExports.jsx("stop",{offset:"0.6",stopColor:"#FFF44F",stopOpacity:0})]}),jsxRuntimeExports.jsx("clipPath",{id:"clip0_927_5847",children:jsxRuntimeExports.jsx("rect",{width:20,height:20,fill:"white"})})]})]}),Brave=jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:20,height:20,viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{d:"M17.2924 5.22043L17.7256 4.15905L16.4982 2.8883C15.8339 2.22404 14.4187 2.61393 14.4187 2.61393L12.8158 0.794434H7.16242L5.55231 2.62115C5.55231 2.62115 4.13715 2.23848 3.47289 2.8883L2.24545 4.15183L2.67866 5.21321L2.13715 6.78721L3.9422 13.6681C4.31765 15.141 4.57036 15.7114 5.63173 16.4623L8.93137 18.7006C9.24906 18.8955 9.63895 19.2349 9.99274 19.2349C10.3465 19.2349 10.7364 18.8955 11.0541 18.7006L14.3538 16.4623C15.4151 15.7114 15.6678 15.141 16.0433 13.6681L17.8483 6.78721L17.2924 5.22043Z",fill:"url(#paint0_linear_927_5861)"}),jsxRuntimeExports.jsx("path",{d:"M13.9711 3.78343C13.9711 3.78343 16.0433 6.28884 16.0433 6.81592C16.0433 7.35744 15.7834 7.49462 15.5234 7.77621L13.9711 9.43686C13.8267 9.58126 13.5162 9.82675 13.6967 10.2527C13.8772 10.686 14.1299 11.2203 13.8411 11.769C13.5523 12.3249 13.0469 12.6932 12.722 12.6354C12.2387 12.4786 11.7777 12.2602 11.3502 11.9856C11.0758 11.8051 10.1949 11.0758 10.1949 10.7943C10.1949 10.5127 11.1047 10 11.278 9.89895C11.444 9.78343 12.2166 9.33577 12.231 9.16249C12.2455 8.9892 12.2455 8.94588 12.0144 8.51267C11.7834 8.07946 11.379 7.50184 11.4368 7.12639C11.509 6.75094 12.1588 6.54877 12.6426 6.36827L14.1372 5.80509C14.2527 5.74733 14.2238 5.69679 13.8772 5.66068C13.5307 5.6318 12.5559 5.50184 12.1155 5.62458C11.6751 5.74733 10.9386 5.93505 10.8664 6.03614C10.8086 6.13722 10.7509 6.13722 10.8159 6.48379L11.2346 8.75816C11.2635 9.04697 11.3213 9.24191 11.018 9.31411C10.7003 9.38632 10.1733 9.50906 9.99276 9.50906C9.81225 9.50906 9.27796 9.38632 8.96749 9.31411C8.65702 9.24191 8.71478 9.04697 8.75088 8.75816C8.77976 8.46935 9.09745 6.82314 9.16243 6.48379C9.23464 6.13722 9.16965 6.13722 9.11189 6.03614C9.03969 5.93505 8.29601 5.74733 7.85558 5.62458C7.42236 5.50184 6.44041 5.6318 6.09384 5.66791C5.74727 5.69679 5.71839 5.74011 5.83391 5.81231L7.3285 6.36827C7.80503 6.54877 8.46929 6.75094 8.53428 7.12639C8.60648 7.50906 8.19493 8.07946 7.95666 8.51267C7.71839 8.94588 7.72561 8.9892 7.74005 9.16249C7.75449 9.33577 8.53428 9.78343 8.69312 9.89895C8.86641 10.0073 9.77615 10.5127 9.77615 10.7943C9.77615 11.0758 8.91695 11.8051 8.62814 11.9856C8.20063 12.2602 7.73957 12.4786 7.2563 12.6354C6.93139 12.6932 6.42597 12.3249 6.12994 11.769C5.84113 11.2203 6.10106 10.686 6.27435 10.2527C6.45485 9.81953 6.1516 9.58848 5.99998 9.43686L4.44763 7.77621C4.19493 7.50906 3.935 7.36466 3.935 6.83036C3.935 6.29606 6.0072 3.79787 6.0072 3.79787L7.97832 4.11556C8.20937 4.11556 8.722 3.92061 9.19132 3.75455C9.66063 3.61014 9.98554 3.5957 9.98554 3.5957C9.98554 3.5957 10.3032 3.5957 10.7798 3.75455C11.2563 3.91339 11.7617 4.11556 11.9928 4.11556C12.231 4.11556 13.9783 3.77621 13.9783 3.77621L13.9711 3.78343ZM12.4188 13.3719C12.5487 13.4441 12.4693 13.6029 12.3465 13.6896L10.5126 15.1192C10.3682 15.2636 10.1372 15.4802 9.98554 15.4802C9.83391 15.4802 9.61009 15.2636 9.45846 15.1192C8.8506 14.6351 8.23683 14.1586 7.61731 13.6896C7.50178 13.6029 7.42236 13.4513 7.54511 13.3719L8.62814 12.7943C9.05864 12.5665 9.51417 12.3897 9.98554 12.2672C10.0938 12.2672 10.7798 12.5127 11.3357 12.7943L12.4188 13.3719Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M14.4332 2.62115L12.8159 0.794434H7.16243L5.55232 2.62115C5.55232 2.62115 4.13716 2.23848 3.4729 2.8883C3.4729 2.8883 5.35016 2.72223 5.99998 3.77638L7.99276 4.11573C8.2238 4.11573 8.73644 3.92079 9.20575 3.75472C9.67507 3.61032 9.99998 3.59588 9.99998 3.59588C9.99998 3.59588 10.3177 3.59588 10.7942 3.75472C11.2707 3.91357 11.7761 4.11573 12.0072 4.11573C12.2455 4.11573 13.9928 3.77638 13.9928 3.77638C14.6426 2.72223 16.5198 2.8883 16.5198 2.8883C15.8556 2.22404 14.4404 2.61393 14.4404 2.61393",fill:"url(#paint1_linear_927_5861)"}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_927_5861",x1:"2.13715",y1:"10.1991",x2:"17.8483",y2:"10.1991",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{offset:"0.4",stopColor:"#FF5500"}),jsxRuntimeExports.jsx("stop",{offset:"0.6",stopColor:"#FF2000"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint1_linear_927_5861",x1:"3.73384",y1:"2.4883",x2:"16.5198",y2:"2.4883",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#FF452A"}),jsxRuntimeExports.jsx("stop",{offset:1,stopColor:"#FF2000"})]})]})]}),Edge=jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:20,height:20,viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsxs("g",{clipPath:"url(#clip0_927_5865)",children:[jsxRuntimeExports.jsx("path",{d:"M18.0547 14.8828C17.7865 15.0222 17.5099 15.1448 17.2266 15.25C16.3293 15.584 15.3792 15.7533 14.4219 15.75C10.7266 15.75 7.50781 13.2109 7.50781 9.94531C7.51262 9.50803 7.63385 9.07993 7.85905 8.70506C8.08424 8.33019 8.40526 8.0221 8.78906 7.8125C5.44531 7.95312 4.58594 11.4375 4.58594 13.4766C4.58594 19.2578 9.90625 19.8359 11.0547 19.8359C11.6719 19.8359 12.6016 19.6562 13.1641 19.4766L13.2656 19.4453C15.4183 18.7014 17.2534 17.2465 18.4688 15.3203C18.5041 15.2618 18.5192 15.1933 18.5119 15.1253C18.5046 15.0574 18.4752 14.9937 18.4282 14.944C18.3812 14.8944 18.3192 14.8615 18.2518 14.8505C18.1843 14.8394 18.1151 14.8508 18.0547 14.8828Z",fill:"url(#paint0_linear_927_5865)"}),jsxRuntimeExports.jsx("path",{opacity:"0.35",d:"M18.0547 14.8828C17.7865 15.0222 17.5099 15.1448 17.2266 15.25C16.3293 15.584 15.3792 15.7533 14.4219 15.75C10.7266 15.75 7.50781 13.2109 7.50781 9.94531C7.51262 9.50803 7.63385 9.07993 7.85905 8.70506C8.08424 8.33019 8.40526 8.0221 8.78906 7.8125C5.44531 7.95312 4.58594 11.4375 4.58594 13.4766C4.58594 19.2578 9.90625 19.8359 11.0547 19.8359C11.6719 19.8359 12.6016 19.6562 13.1641 19.4766L13.2656 19.4453C15.4183 18.7014 17.2534 17.2465 18.4688 15.3203C18.5041 15.2618 18.5192 15.1933 18.5119 15.1253C18.5046 15.0574 18.4752 14.9937 18.4282 14.944C18.3812 14.8944 18.3192 14.8615 18.2518 14.8505C18.1843 14.8394 18.1151 14.8508 18.0547 14.8828Z",fill:"url(#paint1_radial_927_5865)"}),jsxRuntimeExports.jsx("path",{d:"M8.2578 18.8516C7.56239 18.4196 6.95961 17.854 6.48436 17.1875C5.94166 16.4447 5.56809 15.5921 5.38987 14.6896C5.21165 13.787 5.23311 12.8565 5.45272 11.9631C5.67234 11.0697 6.08479 10.2353 6.66115 9.51826C7.23751 8.80123 7.96379 8.21903 8.78905 7.8125C9.03905 7.69531 9.45311 7.49219 10.0078 7.5C10.3981 7.50302 10.7824 7.59627 11.1308 7.77245C11.4791 7.94864 11.7819 8.20299 12.0156 8.51562C12.3299 8.93835 12.5023 9.4498 12.5078 9.97656C12.5078 9.96094 14.4219 3.75781 6.2578 3.75781C2.82811 3.75781 0.00780015 7.00781 0.00780015 9.86719C-0.00584162 11.3776 0.317079 12.8721 0.953112 14.2422C1.99473 16.4602 3.81447 18.2185 6.06689 19.1834C8.3193 20.1483 10.8476 20.2526 13.1719 19.4766C12.3576 19.7337 11.4972 19.811 10.6501 19.7031C9.80297 19.5952 8.98941 19.3047 8.26561 18.8516H8.2578Z",fill:"url(#paint2_linear_927_5865)"}),jsxRuntimeExports.jsx("path",{opacity:"0.41",d:"M8.2578 18.8516C7.56239 18.4196 6.95961 17.854 6.48436 17.1875C5.94166 16.4447 5.56809 15.5921 5.38987 14.6896C5.21165 13.787 5.23311 12.8565 5.45272 11.9631C5.67234 11.0697 6.08479 10.2353 6.66115 9.51826C7.23751 8.80123 7.96379 8.21903 8.78905 7.8125C9.03905 7.69531 9.45311 7.49219 10.0078 7.5C10.3981 7.50302 10.7824 7.59627 11.1308 7.77245C11.4791 7.94864 11.7819 8.20299 12.0156 8.51562C12.3299 8.93835 12.5023 9.4498 12.5078 9.97656C12.5078 9.96094 14.4219 3.75781 6.2578 3.75781C2.82811 3.75781 0.00780015 7.00781 0.00780015 9.86719C-0.00584162 11.3776 0.317079 12.8721 0.953112 14.2422C1.99473 16.4602 3.81447 18.2185 6.06689 19.1834C8.3193 20.1483 10.8476 20.2526 13.1719 19.4766C12.3576 19.7337 11.4972 19.811 10.6501 19.7031C9.80297 19.5952 8.98941 19.3047 8.26561 18.8516H8.2578Z",fill:"url(#paint3_radial_927_5865)"}),jsxRuntimeExports.jsx("path",{d:"M11.9062 11.625C11.8359 11.7031 11.6406 11.8203 11.6406 12.0625C11.6406 12.2656 11.7734 12.4688 12.0156 12.6328C13.1328 13.4141 15.25 13.3047 15.2578 13.3047C16.0907 13.3041 16.9081 13.0802 17.625 12.6562C18.3467 12.2341 18.9456 11.6307 19.3622 10.9057C19.7788 10.1808 19.9986 9.35955 20 8.52344C20.0234 6.77344 19.375 5.60937 19.1172 5.09375C17.4531 1.85937 13.8828 4.89564e-08 10 4.89564e-08C7.37202 -0.00025981 4.84956 1.03398 2.97819 2.87904C1.10682 4.7241 0.0369559 7.23166 0 9.85938C0.0390625 7.00781 2.875 4.70312 6.25 4.70312C6.52344 4.70312 8.08594 4.72656 9.53125 5.48438C10.5466 5.98895 11.3875 6.78627 11.9453 7.77344C12.4219 8.60156 12.5078 9.65625 12.5078 10.0781C12.5078 10.5 12.2969 11.1172 11.8984 11.6328L11.9062 11.625Z",fill:"url(#paint4_radial_927_5865)"}),jsxRuntimeExports.jsx("path",{d:"M11.9062 11.625C11.8359 11.7031 11.6406 11.8203 11.6406 12.0625C11.6406 12.2656 11.7734 12.4688 12.0156 12.6328C13.1328 13.4141 15.25 13.3047 15.2578 13.3047C16.0907 13.3041 16.9081 13.0802 17.625 12.6562C18.3467 12.2341 18.9456 11.6307 19.3622 10.9057C19.7788 10.1808 19.9986 9.35955 20 8.52344C20.0234 6.77344 19.375 5.60937 19.1172 5.09375C17.4531 1.85937 13.8828 4.89564e-08 10 4.89564e-08C7.37202 -0.00025981 4.84956 1.03398 2.97819 2.87904C1.10682 4.7241 0.0369559 7.23166 0 9.85938C0.0390625 7.00781 2.875 4.70312 6.25 4.70312C6.52344 4.70312 8.08594 4.72656 9.53125 5.48438C10.5466 5.98895 11.3875 6.78627 11.9453 7.77344C12.4219 8.60156 12.5078 9.65625 12.5078 10.0781C12.5078 10.5 12.2969 11.1172 11.8984 11.6328L11.9062 11.625Z",fill:"url(#paint5_radial_927_5865)"})]}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_927_5865",x1:"4.58594",y1:"13.8281",x2:"18.5234",y2:"13.8281",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#0C59A4"}),jsxRuntimeExports.jsx("stop",{offset:1,stopColor:"#114A8B"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint1_radial_927_5865",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(12.2813 13.9332) scale(7.45313 7.08047)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.7",stopOpacity:0}),jsxRuntimeExports.jsx("stop",{offset:"0.9",stopOpacity:"0.5"}),jsxRuntimeExports.jsx("stop",{offset:1})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint2_linear_927_5865",x1:"11.9297",y1:"7.78125",x2:"3.23436",y2:"17.2578",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#1B9DE2"}),jsxRuntimeExports.jsx("stop",{offset:"0.2",stopColor:"#1595DF"}),jsxRuntimeExports.jsx("stop",{offset:"0.7",stopColor:"#0680D7"}),jsxRuntimeExports.jsx("stop",{offset:1,stopColor:"#0078D4"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint3_radial_927_5865",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(5.51209 15.5419) rotate(-81.3844) scale(11.202 9.05011)",children:[jsxRuntimeExports.jsx("stop",{offset:"0.8",stopOpacity:0}),jsxRuntimeExports.jsx("stop",{offset:"0.9",stopOpacity:"0.5"}),jsxRuntimeExports.jsx("stop",{offset:1})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint4_radial_927_5865",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(2.02266 3.69656) rotate(92.2906) scale(15.8251 33.7043)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#35C1F1"}),jsxRuntimeExports.jsx("stop",{offset:"0.1",stopColor:"#34C1ED"}),jsxRuntimeExports.jsx("stop",{offset:"0.2",stopColor:"#2FC2DF"}),jsxRuntimeExports.jsx("stop",{offset:"0.3",stopColor:"#2BC3D2"}),jsxRuntimeExports.jsx("stop",{offset:"0.7",stopColor:"#36C752"})]}),jsxRuntimeExports.jsxs("radialGradient",{id:"paint5_radial_927_5865",cx:0,cy:0,r:1,gradientUnits:"userSpaceOnUse",gradientTransform:"translate(18.7547 6.03906) rotate(73.7398) scale(7.60156 6.18159)",children:[jsxRuntimeExports.jsx("stop",{stopColor:"#66EB6E"}),jsxRuntimeExports.jsx("stop",{offset:1,stopColor:"#66EB6E",stopOpacity:0})]}),jsxRuntimeExports.jsx("clipPath",{id:"clip0_927_5865",children:jsxRuntimeExports.jsx("rect",{width:20,height:20,fill:"white"})})]})]});var browsers={Chrome,FireFox,Brave,Edge};const BrowserIcon=React.forwardRef(({browser:et},o)=>{const tt=et??detectBrowser();let rt;switch(tt){case"chrome":rt=browsers.Chrome;break;case"firefox":rt=browsers.FireFox;break;case"edge":rt=browsers.Edge;break}return rt?jsxRuntimeExports.jsx(BrowserIconContainer,{children:rt}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{})});BrowserIcon.displayName="BrowserIcon";const LogoContainer$3=styled(motion.div)` + z-index: 4; + position: relative; + width: 100px; + height: 100px; + svg { + z-index: 3; + position: relative; + display: block; + } +`,Logo=styled(motion.div)` + z-index: 2; + position: absolute; + overflow: hidden; + inset: 6px; + border-radius: 50px; + background: var(--ck-body-background); + display: flex; + align-items: center; + justify-content: center; + svg, + img { + pointer-events: none; + display: block; + margin: 0 auto; + width: 100%; + height: 100%; + ${et=>et.$small&&Ae` + width: 85%; + height: 85%; + `} + } +`,SpinnerContainer=styled(motion.div)` + position: absolute; + inset: -5px; +`,ExpiringSpinner=styled(motion.div)` + pointer-events: none; + user-select: none; + z-index: 1; + position: absolute; + inset: -25%; + background: var(--ck-body-background); + div:first-child { + position: absolute; + left: 50%; + right: 0; + top: 0; + bottom: 0; + overflow: hidden; + &:before { + position: absolute; + content: ''; + inset: 0; + background: var(--ck-spinner-color); + transform-origin: 0% 50%; + animation: rotateExpiringSpinner 5000ms ease-in both; + } + } + div:last-child { + position: absolute; + left: 0; + right: 50%; + top: 0; + bottom: 0; + overflow: hidden; + &:before { + position: absolute; + content: ''; + inset: 0; + background: var(--ck-spinner-color); + transform-origin: 100% 50%; + animation: rotateExpiringSpinner 5000ms ease-out 5000ms both; + } + } + @keyframes rotateExpiringSpinner { + 0% { + transform: rotate(-180deg); + } + 100% { + transform: rotate(0deg); + } + } +`,Spinner$2=styled(motion.div)` + pointer-events: none; + user-select: none; + z-index: 1; + position: absolute; + inset: 0; + svg { + display: block; + position: absolute; + left: 0; + top: 0; + width: 100%; + height: 100%; + animation: rotateSpinner 1200ms linear infinite; + } + @keyframes rotateSpinner { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } + } +`,CircleSpinner=({logo:et,smallLogo:o,connecting:tt=!0,unavailable:rt=!1,countdown:nt=!1})=>jsxRuntimeExports.jsxs(LogoContainer$3,{transition:{duration:.5,ease:[.175,.885,.32,.98]},children:[jsxRuntimeExports.jsx(Logo,{$small:!rt&&o,style:rt?{borderRadius:0}:void 0,children:et}),jsxRuntimeExports.jsx(SpinnerContainer,{children:jsxRuntimeExports.jsxs(AnimatePresence,{children:[tt&&jsxRuntimeExports.jsx(Spinner$2,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0,transition:{duration:nt?1:0}},children:jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"102",height:"102",viewBox:"0 0 102 102",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{d:"M52 100C24.3858 100 2 77.6142 2 50",stroke:"url(#paint0_linear_1943_4139)",strokeWidth:"3.5",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_1943_4139",x1:"2",y1:"48.5",x2:"53",y2:"100",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-spinner-color)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"var(--ck-spinner-color)",stopOpacity:"0"})]})})]})},"Spinner"),nt&&jsxRuntimeExports.jsxs(ExpiringSpinner,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.25},children:[jsxRuntimeExports.jsx("div",{}),jsxRuntimeExports.jsx("div",{})]},"ExpiringSpinner")]})})]}),states$1={CONNECTED:"connected",CONNECTING:"connecting",EXPIRING:"expiring",FAILED:"failed",REJECTED:"rejected",NOTCONNECTED:"notconnected",UNAVAILABLE:"unavailable"},contentVariants$1={initial:{willChange:"transform,opacity",position:"relative",opacity:0,scale:.95},animate:{position:"relative",opacity:1,scale:1,transition:{ease:[.16,1,.3,1],duration:.4,delay:.05,position:{delay:0}}},exit:{position:"absolute",opacity:0,scale:.95,transition:{ease:[.16,1,.3,1],duration:.3}}},ConnectWithInjector=({switchConnectMethod:et,forceState:o})=>{var tt,rt,nt,ot,it,st,at,ct;const{connect:lt}=useConnect({mutation:{onMutate:Ot=>{Ot.connector?St(states$1.CONNECTING):St(states$1.UNAVAILABLE)},onError(Ot){console.error(Ot)},onSettled(Ot,Nt){if(Nt){if(yt(!0),setTimeout(()=>yt(!1),3500),Nt.code)switch(Nt.code){case-32002:St(states$1.NOTCONNECTED);break;case 4001:St(states$1.REJECTED);break;default:St(states$1.FAILED);break}else if(Nt.message)switch(Nt.message){case"User rejected request":St(states$1.REJECTED);break;default:St(states$1.FAILED);break}}setTimeout(dt,100)}}}),{triggerResize:dt,connector:ht}=useContext(),mt=ht.id,ft=useWallet(mt),pt={name:ft==null?void 0:ft.name,shortName:(tt=ft==null?void 0:ft.shortName)!==null&&tt!==void 0?tt:ft==null?void 0:ft.name,icon:(rt=ft==null?void 0:ft.iconConnector)!==null&&rt!==void 0?rt:ft==null?void 0:ft.icon,iconShape:(nt=ft==null?void 0:ft.iconShape)!==null&&nt!==void 0?nt:"circle",iconShouldShrink:ft==null?void 0:ft.iconShouldShrink},[gt,yt]=reactExports.useState(!1);reactExports.useState(9);const xt=detectBrowser(),vt=(ot=ft==null?void 0:ft.downloadUrls)===null||ot===void 0?void 0:ot[xt],Et=ft!=null&&ft.downloadUrls?{name:Object.keys(ft==null?void 0:ft.downloadUrls)[0],label:((it=Object.keys(ft==null?void 0:ft.downloadUrls)[0])===null||it===void 0?void 0:it.charAt(0).toUpperCase())+((st=Object.keys(ft==null?void 0:ft.downloadUrls)[0])===null||st===void 0?void 0:st.slice(1)),url:ft==null?void 0:ft.downloadUrls[Object.keys(ft==null?void 0:ft.downloadUrls)[0]]}:void 0,[Ct,St]=reactExports.useState(o||(ft!=null&&ft.isInstalled?states$1.CONNECTING:states$1.UNAVAILABLE)),At=useLocales({CONNECTORNAME:pt.name,CONNECTORSHORTNAME:(at=pt.shortName)!==null&&at!==void 0?at:pt.name,SUGGESTEDEXTENSIONBROWSER:(ct=Et==null?void 0:Et.label)!==null&&ct!==void 0?ct:"your browser"}),kt=async()=>{ft!=null&&ft.isInstalled&&(ft!=null&&ft.connector)?lt({connector:ft==null?void 0:ft.connector}):St(states$1.UNAVAILABLE)};let It;return reactExports.useEffect(()=>{if(Ct!==states$1.UNAVAILABLE)return It=setTimeout(kt,600),()=>{clearTimeout(It)}},[]),ft?isWalletConnectConnector(ft==null?void 0:ft.connector.id)?jsxRuntimeExports.jsx(PageContent,{children:jsxRuntimeExports.jsxs(Container$4,{children:[jsxRuntimeExports.jsx(ModalHeading,{children:"Invalid State"}),jsxRuntimeExports.jsx(ModalContent,{children:jsxRuntimeExports.jsx(Alert,{children:"WalletConnect does not have an injection flow. This state should never happen."})})]})}):jsxRuntimeExports.jsx(PageContent,{children:jsxRuntimeExports.jsxs(Container$4,{children:[jsxRuntimeExports.jsx(ConnectingContainer,{children:jsxRuntimeExports.jsxs(ConnectingAnimation,{$shake:Ct===states$1.FAILED||Ct===states$1.REJECTED,$circle:pt.iconShape==="circle",children:[jsxRuntimeExports.jsx(AnimatePresence,{children:(Ct===states$1.FAILED||Ct===states$1.REJECTED)&&jsxRuntimeExports.jsx(RetryButton,{"aria-label":"Retry",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},whileTap:{scale:.9},transition:{duration:.1},onClick:kt,children:jsxRuntimeExports.jsx(RetryIconContainer,{children:jsxRuntimeExports.jsx(Tooltip,{open:gt&&(Ct===states$1.FAILED||Ct===states$1.REJECTED),message:At.tryAgainQuestion,xOffset:-6,children:jsxRuntimeExports.jsx(RetryIconCircle,{})})})})}),pt.iconShape==="circle"?jsxRuntimeExports.jsx(CircleSpinner,{logo:Ct===states$1.UNAVAILABLE?jsxRuntimeExports.jsx("div",{style:{transform:"scale(1.14)",position:"relative",width:"100%"},children:pt.icon}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:pt.icon}),smallLogo:pt.iconShouldShrink,connecting:Ct===states$1.CONNECTING,unavailable:Ct===states$1.UNAVAILABLE}):jsxRuntimeExports.jsx(SquircleSpinner,{logo:Ct===states$1.UNAVAILABLE?jsxRuntimeExports.jsx("div",{style:{transform:"scale(1.14)",position:"relative",width:"100%"},children:pt.icon}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:pt.icon}),connecting:Ct===states$1.CONNECTING})]})}),jsxRuntimeExports.jsx(ModalContentContainer,{children:jsxRuntimeExports.jsxs(AnimatePresence,{initial:!1,children:[Ct===states$1.FAILED&&jsxRuntimeExports.jsx(Content$1,{initial:"initial",animate:"animate",exit:"exit",variants:contentVariants$1,children:jsxRuntimeExports.jsxs(ModalContent,{children:[jsxRuntimeExports.jsxs(ModalH1,{$error:!0,children:[jsxRuntimeExports.jsx(AlertIcon,{}),At.injectionScreen_failed_h1]}),jsxRuntimeExports.jsx(ModalBody,{children:At.injectionScreen_failed_p})]})},states$1.FAILED),Ct===states$1.REJECTED&&jsxRuntimeExports.jsx(Content$1,{initial:"initial",animate:"animate",exit:"exit",variants:contentVariants$1,children:jsxRuntimeExports.jsxs(ModalContent,{style:{paddingBottom:28},children:[jsxRuntimeExports.jsx(ModalH1,{children:At.injectionScreen_rejected_h1}),jsxRuntimeExports.jsx(ModalBody,{children:At.injectionScreen_rejected_p})]})},states$1.REJECTED),(Ct===states$1.CONNECTING||Ct===states$1.EXPIRING)&&jsxRuntimeExports.jsx(Content$1,{initial:"initial",animate:"animate",exit:"exit",variants:contentVariants$1,children:jsxRuntimeExports.jsxs(ModalContent,{style:{paddingBottom:28},children:[jsxRuntimeExports.jsx(ModalH1,{children:ft.connector.id==="injected"?At.injectionScreen_connecting_injected_h1:At.injectionScreen_connecting_h1}),jsxRuntimeExports.jsx(ModalBody,{children:ft.connector.id==="injected"?At.injectionScreen_connecting_injected_p:At.injectionScreen_connecting_p})]})},states$1.CONNECTING),Ct===states$1.CONNECTED&&jsxRuntimeExports.jsx(Content$1,{initial:"initial",animate:"animate",exit:"exit",variants:contentVariants$1,children:jsxRuntimeExports.jsxs(ModalContent,{children:[jsxRuntimeExports.jsxs(ModalH1,{$valid:!0,children:[jsxRuntimeExports.jsx(TickIcon,{})," ",At.injectionScreen_connected_h1]}),jsxRuntimeExports.jsx(ModalBody,{children:At.injectionScreen_connected_p})]})},states$1.CONNECTED),Ct===states$1.NOTCONNECTED&&jsxRuntimeExports.jsx(Content$1,{initial:"initial",animate:"animate",exit:"exit",variants:contentVariants$1,children:jsxRuntimeExports.jsxs(ModalContent,{children:[jsxRuntimeExports.jsx(ModalH1,{children:At.injectionScreen_notconnected_h1}),jsxRuntimeExports.jsx(ModalBody,{children:At.injectionScreen_notconnected_p})]})},states$1.NOTCONNECTED),Ct===states$1.UNAVAILABLE&&jsxRuntimeExports.jsx(Content$1,{initial:"initial",animate:"animate",exit:"exit",variants:contentVariants$1,children:vt?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs(ModalContent,{style:{paddingBottom:18},children:[jsxRuntimeExports.jsx(ModalH1,{children:At.injectionScreen_install_h1}),jsxRuntimeExports.jsx(ModalBody,{children:At.injectionScreen_install_p})]}),!ft.isInstalled&&vt&&jsxRuntimeExports.jsx(Button$1,{href:vt,icon:jsxRuntimeExports.jsx(BrowserIcon,{}),children:At.installTheExtension})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs(ModalContent,{style:{paddingBottom:12},children:[jsxRuntimeExports.jsx(ModalH1,{children:At.injectionScreen_unavailable_h1}),jsxRuntimeExports.jsx(ModalBody,{children:At.injectionScreen_unavailable_p})]}),!ft.isInstalled&&Et&&jsxRuntimeExports.jsxs(Button$1,{href:Et==null?void 0:Et.url,icon:jsxRuntimeExports.jsx(BrowserIcon,{browser:Et==null?void 0:Et.name}),children:["Install on ",Et==null?void 0:Et.label]})]})},states$1.UNAVAILABLE)]})})]})}):jsxRuntimeExports.jsx(PageContent,{children:jsxRuntimeExports.jsxs(Container$4,{children:[jsxRuntimeExports.jsx(ModalHeading,{children:"Invalid State"}),jsxRuntimeExports.jsx(ModalContent,{children:jsxRuntimeExports.jsx(Alert,{children:"No connectors match the id given. This state should never happen."})})]})})},QRCodeContainer=styled(motion.div)` + z-index: 3; + position: relative; + overflow: hidden; + height: 0; + padding-bottom: 100% !important; + display: flex; + align-items: center; + justify-content: center; + margin: 1px 0 2px; + border-radius: var(--ck-qr-border-radius, 24px); + background: var(--ck-qr-background, transparent); + box-shadow: 0 0 0 1px var(--ck-qr-border-color); + backface-visibility: hidden; + svg { + display: block; + max-width: 100%; + width: 100%; + height: auto; + } +`,QRCodeContent=styled(motion.div)` + position: absolute; + inset: 13px; + svg { + width: 100% !important; + height: auto !important; + } +`,PlaceholderKeyframes$2=We` + 0%{ background-position: 100% 0; } + 100%{ background-position: -100% 0; } +`,QRPlaceholder=styled(motion.div)` + --color: var(--ck-qr-dot-color); + --bg: var(--ck-qr-background, var(--ck-body-background)); + + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + > div { + z-index: 4; + position: relative; + width: 28%; + height: 28%; + border-radius: 20px; + background: var(--bg); + box-shadow: 0 0 0 7px var(--bg); + } + > span { + z-index: 4; + position: absolute; + background: var(--color); + border-radius: 12px; + width: 13.25%; + height: 13.25%; + box-shadow: 0 0 0 4px var(--bg); + &:before { + content: ''; + position: absolute; + inset: 9px; + border-radius: 3px; + box-shadow: 0 0 0 4px var(--bg); + } + &:nth-child(1) { + top: 0; + left: 0; + } + &:nth-child(2) { + top: 0; + right: 0; + } + &:nth-child(3) { + bottom: 0; + left: 0; + } + } + &:before { + z-index: 3; + content: ''; + position: absolute; + inset: 0; + background: repeat; + background-size: 1.888% 1.888%; + background-image: radial-gradient(var(--color) 41%, transparent 41%); + } + &:after { + z-index: 5; + content: ''; + position: absolute; + inset: 0; + transform: scale(1.5) rotate(45deg); + background-image: linear-gradient( + 90deg, + rgba(255, 255, 255, 0) 50%, + rgba(255, 255, 255, 1), + rgba(255, 255, 255, 0) + ); + background-size: 200% 100%; + animation: ${PlaceholderKeyframes$2} 1000ms linear infinite both; + } +`,LogoContainer$2=styled(motion.div)` + z-index: 6; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + transform: translateY(50%) scale(0.9999); // Shifting fix +`,LogoIcon=styled(motion.div)` + z-index: 6; + position: absolute; + left: 50%; + overflow: hidden; + + transform: translate(-50%, -50%) scale(0.9999); // Shifting fix + + svg { + display: block; + position: relative; + width: 100%; + height: 100%; + } + + ${et=>et.$wcLogo?Ae` + width: 29%; + height: 20.5%; + `:Ae` + width: 28%; + height: 28%; + border-radius: 17px; + &:before { + pointer-events: none; + z-index: 2; + content: ''; + position: absolute; + inset: 0; + border-radius: inherit; + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.02); + } + `} +`,generateMatrix=(et,o)=>{const tt=Array.prototype.slice.call(browser$1.create(et,{errorCorrectionLevel:o}).modules.data,0),rt=Math.sqrt(tt.length);return tt.reduce((nt,ot,it)=>(it%rt===0?nt.push([ot]):nt[nt.length-1].push(ot))&&nt,[])};function QRCode$1({ecl:et="M",size:o=200,uri:tt,clearArea:rt=!1,image:nt,imageBackground:ot="transparent"}){const it=rt?76:0,st=o-10*2,at=reactExports.useMemo(()=>{const ct=[],lt=generateMatrix(tt,et),dt=st/lt.length;if([{x:0,y:0},{x:1,y:0},{x:0,y:1}].forEach(({x:gt,y:yt})=>{const bt=(lt.length-7)*dt*gt,xt=(lt.length-7)*dt*yt;for(let vt=0;vt<3;vt++)ct.push(jsxRuntimeExports.jsx("rect",{fill:vt%2!==0?"var(--ck-qr-background, var(--ck-body-background))":"var(--ck-qr-dot-color)",rx:(vt-2)*-5+(vt===0?2:3),ry:(vt-2)*-5+(vt===0?2:3),width:dt*(7-vt*2),height:dt*(7-vt*2),x:bt+dt*vt,y:xt+dt*vt},`${vt}-${gt}-${yt}`))}),nt){const gt=(lt.length-7)*dt*1,yt=(lt.length-7)*dt*1;ct.push(jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("rect",{fill:ot,rx:-2*-5+2,ry:-2*-5+2,width:dt*(7-0*2),height:dt*(7-0*2),x:gt+dt*0,y:yt+dt*0}),jsxRuntimeExports.jsx("foreignObject",{width:dt*(7-0*2),height:dt*(7-0*2),x:gt+dt*0,y:yt+dt*0,children:jsxRuntimeExports.jsx("div",{style:{borderRadius:-2*-5+2,overflow:"hidden"},children:nt})})]}))}const mt=Math.floor((it+25)/dt),ft=lt.length/2-mt/2,pt=lt.length/2+mt/2-1;return lt.forEach((gt,yt)=>{gt.forEach((bt,xt)=>{lt[yt][xt]&&(yt<7&&xt<7||yt>lt.length-8&&xt<7||yt<7&&xt>lt.length-8||(nt||!(yt>ft&&ytft&&xt{function tt(){o({width:window.innerWidth,height:window.innerHeight})}return window.addEventListener("resize",tt),tt(),()=>window.removeEventListener("resize",tt)},[]),et}function CustomQRCode({value:et,image:o,imageBackground:tt,imagePosition:rt="center",tooltipMessage:nt}){const it=useWindowSize().width>920&&nt?jsxRuntimeExports.jsx(Tooltip,{xOffset:139,yOffset:5,delay:.1,message:nt,children:o}):o;return jsxRuntimeExports.jsx(QRCodeContainer,{children:jsxRuntimeExports.jsxs(QRCodeContent,{children:[o&&jsxRuntimeExports.jsx(LogoContainer$2,{children:jsxRuntimeExports.jsx(LogoIcon,{$wcLogo:rt!=="center",style:{background:rt==="center"?tt:void 0},children:it})}),jsxRuntimeExports.jsx(AnimatePresence,{initial:!1,children:et?jsxRuntimeExports.jsx(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0,position:"absolute",inset:[0,0]},transition:{duration:.2},children:jsxRuntimeExports.jsx(QRCode$1,{uri:et,size:288,ecl:"M",clearArea:!!(rt==="center"&&o)})},et):jsxRuntimeExports.jsxs(QRPlaceholder,{initial:{opacity:.1},animate:{opacity:.1},exit:{opacity:0,position:"absolute",inset:[0,0]},transition:{duration:.2},children:[jsxRuntimeExports.jsx("span",{}),jsxRuntimeExports.jsx("span",{}),jsxRuntimeExports.jsx("span",{}),jsxRuntimeExports.jsx("div",{})]})})]})})}CustomQRCode.displayName="CustomQRCode";const IconContainer$1=styled(motion.div)` + position: relative; + display: flex; + align-items: center; + justify-content: center; + width: 47px; + height: 52px; + min-width: 47px; + min-height: 52px; + svg { + display: block; + max-width: 100%; + height: auto; + } +`,ScanIconWithLogos=({logo:et})=>{const o=[jsxRuntimeExports.jsx(Logos.MetaMask,{background:!0}),jsxRuntimeExports.jsx(Logos.Coinbase,{background:!0}),jsxRuntimeExports.jsx(Logos.Crypto,{}),jsxRuntimeExports.jsx(Logos.ImToken,{}),jsxRuntimeExports.jsx(Logos.Argent,{}),jsxRuntimeExports.jsx(Logos.Trust,{})];return jsxRuntimeExports.jsx(IconContainer$1,{children:jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"47",height:"52",viewBox:"0 0 47 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsxs("g",{mask:"url(#gradient-mask)",children:[jsxRuntimeExports.jsx("path",{d:"M7 14.5C7 11.4624 9.46243 9 12.5 9H31.5C34.5376 9 37 11.4624 37 14.5V47H7V14.5Z",fill:"var(--ck-graphic-scaniconwithlogos-04)"}),et?jsxRuntimeExports.jsx("foreignObject",{x:"13",y:"21",width:"18",height:"18",rx:"5",children:jsxRuntimeExports.jsx("div",{style:{overflow:"hidden",borderRadius:5},children:et})}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("foreignObject",{x:"12",y:"15",width:"9",height:"9",rx:"2.5",children:jsxRuntimeExports.jsx("div",{style:{overflow:"hidden",borderRadius:2.5},children:o[0]})}),jsxRuntimeExports.jsx("foreignObject",{x:"23",y:"15",width:"9",height:"9",rx:"2.5",children:jsxRuntimeExports.jsx("div",{style:{overflow:"hidden",borderRadius:2.5},children:o[1]})}),jsxRuntimeExports.jsx("foreignObject",{x:"12",y:"26",width:"9",height:"9",rx:"2.5",children:jsxRuntimeExports.jsx("div",{style:{overflow:"hidden",borderRadius:2.5},children:jsxRuntimeExports.jsx("div",{style:{overflow:"hidden",borderRadius:2.5},children:o[2]})})}),jsxRuntimeExports.jsx("foreignObject",{x:"23",y:"26",width:"9",height:"9",rx:"2.5",children:jsxRuntimeExports.jsx("div",{style:{overflow:"hidden",borderRadius:2.5},children:o[3]})}),jsxRuntimeExports.jsx("foreignObject",{x:"12",y:"37",width:"9",height:"9",rx:"2.5",children:jsxRuntimeExports.jsx("div",{style:{overflow:"hidden",borderRadius:2.5},children:o[4]})}),jsxRuntimeExports.jsx("foreignObject",{x:"23",y:"37",width:"9",height:"9",rx:"2.5",children:jsxRuntimeExports.jsx("div",{style:{overflow:"hidden",borderRadius:2.5},children:o[5]})})]}),jsxRuntimeExports.jsx("path",{d:"M36 47V13.7143C36 11.1107 33.8893 9 31.2857 9H12.7143C10.1107 9 8 11.1107 8 13.7143V47",stroke:"url(#paint0_linear_924_12568)",strokeWidth:"2"}),jsxRuntimeExports.jsx("path",{d:"M15 10H29C29 11.1046 28.1046 12 27 12H17C15.8954 12 15 11.1046 15 10Z",fill:"var(--ck-graphic-scaniconwithlogos-01)"}),jsxRuntimeExports.jsx("rect",{x:"1",y:"47",width:"43",height:"5",fill:"var(--ck-tooltip-background)"}),jsxRuntimeExports.jsx("rect",{x:"22",y:"1",width:"24",height:"24",rx:"12",fill:"var(--ck-graphic-scaniconwithlogos-03)",stroke:"var(--ck-tooltip-background)",strokeWidth:"2"}),jsxRuntimeExports.jsx("rect",{x:"34.5",y:"10",width:"2.5",height:"2.5",rx:"0.75",fill:"#373737"}),jsxRuntimeExports.jsx("rect",{x:"31",y:"10",width:"2.5",height:"2.5",rx:"0.75",fill:"#373737"}),jsxRuntimeExports.jsx("rect",{x:"31",y:"13.5",width:"2.5",height:"2.5",rx:"0.75",fill:"#373737"}),jsxRuntimeExports.jsx("rect",{x:"34.5",y:"13.5",width:"2.5",height:"2.5",rx:"0.75",fill:"#373737"}),jsxRuntimeExports.jsx("path",{d:"M28.5 10.5V9C28.5 8.17157 29.1716 7.5 30 7.5H31.5",stroke:"#373737",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M36.5 7.5L38 7.5C38.8284 7.5 39.5 8.17157 39.5 9L39.5 10.5",stroke:"#373737",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M39.5 15.5L39.5 17C39.5 17.8284 38.8284 18.5 38 18.5L36.5 18.5",stroke:"#373737",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M31.5 18.5L30 18.5C29.1716 18.5 28.5 17.8284 28.5 17L28.5 15.5",stroke:"#373737",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_924_12568",x1:"22",y1:"8.2549",x2:"22",y2:"47",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-graphic-scaniconwithlogos-01)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"var(--ck-graphic-scaniconwithlogos-02)"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"linear-gradient-mask",x1:"47",y1:"42",x2:"47",y2:"47",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"white"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"black",stopOpacity:"0"})]}),jsxRuntimeExports.jsx("mask",{id:"gradient-mask",children:jsxRuntimeExports.jsx("rect",{x:"0",y:"0",width:"47",height:"52",fill:"url(#linear-gradient-mask)"})})]})]})})},ConnectWithQRCode=({switchConnectMethod:et})=>{var o,tt,rt,nt,ot,it,st,at;const ct=useContext(),lt=ct.connector.id,dt=useWallet(ct.connector.id),{open:ht,isOpen:mt}=useWalletConnectModal(),{connect:{getUri:ft}}=useWeb3(),pt=ft(lt),gt=pt?(tt=(o=dt==null?void 0:dt.getWalletConnectDeeplink)===null||o===void 0?void 0:o.call(dt,pt))!==null&&tt!==void 0?tt:pt:void 0,yt=useLocales({CONNECTORNAME:dt==null?void 0:dt.name});if(!dt)return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["Wallet not found ",ct.connector.id]});const bt=dt==null?void 0:dt.downloadUrls,xt={chrome:bt==null?void 0:bt.chrome,firefox:bt==null?void 0:bt.firefox,brave:bt==null?void 0:bt.brave,edge:bt==null?void 0:bt.edge,safari:bt==null?void 0:bt.safari};detectBrowser();const vt=bt&&Object.keys(bt).length!==0;xt&&(Object.keys(xt)[0],((rt=Object.keys(xt)[0])===null||rt===void 0?void 0:rt.charAt(0).toUpperCase())+((nt=Object.keys(xt)[0])===null||nt===void 0?void 0:nt.slice(1)),xt[Object.keys(xt)[0]]);const Et=isWalletConnectConnector(lt);return jsxRuntimeExports.jsxs(PageContent,{children:[jsxRuntimeExports.jsxs(ModalContent,{style:{paddingBottom:8,gap:14},children:[jsxRuntimeExports.jsx(CustomQRCode,{value:gt,image:dt==null?void 0:dt.icon,tooltipMessage:isWalletConnectConnector(lt)?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ScanIconWithLogos,{}),jsxRuntimeExports.jsx("span",{children:yt.scanScreen_tooltip_walletConnect})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ScanIconWithLogos,{logo:dt==null?void 0:dt.icon}),jsxRuntimeExports.jsx("span",{children:yt.scanScreen_tooltip_default})]})}),Et?jsxRuntimeExports.jsx(OrDivider,{}):vt&&jsxRuntimeExports.jsx(OrDivider,{children:yt.dontHaveTheApp})]}),Et&&jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:14},children:[((ot=ct.options)===null||ot===void 0?void 0:ot.walletConnectCTA)!=="modal"&&jsxRuntimeExports.jsx(CopyToClipboard,{variant:"button",string:gt,children:((it=ct.options)===null||it===void 0?void 0:it.walletConnectCTA)==="link"?yt.copyToClipboard:yt.copyCode}),((st=ct.options)===null||st===void 0?void 0:st.walletConnectCTA)!=="link"&&jsxRuntimeExports.jsx(Button$1,{icon:jsxRuntimeExports.jsx(ExternalLinkIcon,{}),onClick:ht,disabled:mt,waiting:mt,children:((at=ct.options)===null||at===void 0?void 0:at.walletConnectCTA)==="modal"?yt.useWalletConnectModal:yt.useModal})]}),vt&&jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsx(Button$1,{onClick:()=>{ct.setRoute(routes.DOWNLOAD)},download:!0,children:yt.getWalletName})})]})},states={QRCODE:"qrcode",INJECTOR:"injector"},ConnectUsing=()=>{const et=useContext(),o=useWallet(et.connector.id),tt=!(o!=null&&o.isInstalled)&&(o==null?void 0:o.getWalletConnectDeeplink),[rt,nt]=reactExports.useState(tt?states.QRCODE:states.INJECTOR);return reactExports.useEffect(()=>{const ot=async()=>{await(o==null?void 0:o.connector.getProvider())||(nt(states.QRCODE),setTimeout(et.triggerResize,10))};rt===states.INJECTOR&&ot()},[]),o?jsxRuntimeExports.jsxs(AnimatePresence,{children:[rt===states.QRCODE&&jsxRuntimeExports.jsx(motion.div,{initial:"initial",animate:"animate",exit:"exit",variants:contentVariants$2,children:jsxRuntimeExports.jsx(ConnectWithQRCode,{switchConnectMethod:ot=>{nt(states.INJECTOR)}})},states.QRCODE),rt===states.INJECTOR&&jsxRuntimeExports.jsx(motion.div,{initial:"initial",animate:"animate",exit:"exit",variants:contentVariants$2,children:jsxRuntimeExports.jsx(ConnectWithInjector,{switchConnectMethod:ot=>{nt(states.QRCODE)}})},states.INJECTOR)]}):jsxRuntimeExports.jsxs(Alert,{children:["Connector not found ",et.connector.id]})},DownloadApp=()=>{var et,o,tt;const rt=useContext(),nt=useWallet(rt.connector.id),ot=useLocales({CONNECTORNAME:nt==null?void 0:nt.name});if(!nt)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:"Wallet not found"});const it={ios:(et=nt.downloadUrls)===null||et===void 0?void 0:et.ios,android:(o=nt.downloadUrls)===null||o===void 0?void 0:o.android,redirect:(tt=nt.downloadUrls)===null||tt===void 0?void 0:tt.download},st=it.ios&&it.android?ot.downloadAppScreen_iosAndroid:it.ios?ot.downloadAppScreen_ios:ot.downloadAppScreen_android;return jsxRuntimeExports.jsx(PageContent,{children:jsxRuntimeExports.jsxs(ModalContent,{style:{paddingBottom:4,gap:14},children:[it.redirect&&jsxRuntimeExports.jsx(CustomQRCode,{value:it.redirect}),!it.redirect&&jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:"No download link available"}),jsxRuntimeExports.jsx(ModalBody,{style:{fontSize:15,lineHeight:"20px",padding:"0 12px"},children:st})]})})},AvatarContainer=styled(motion.div)` + padding: 18px 0 20px; + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + padding: 16px 0 20px; + } +`,AvatarInner=styled(motion.div)` + position: relative; + display: inline-block; +`,ChainSelectorContainer=styled(motion.div)` + z-index: 3; + position: absolute; + bottom: 0px; + right: -16px; +`,BalanceContainer=styled(motion.div)` + position: relative; +`,Balance$1=styled(motion.div)` + position: relative; +`,PlaceholderKeyframes$1=We` + 0%{ background-position: 100% 0; } + 100%{ background-position: -100% 0; } +`,LoadingBalance=styled(motion.div)` + width: 25%; + margin: 0 auto; + position: relative; + overflow: hidden; + border-radius: 10px; + background: var(--ck-body-background-secondary); + inset: 0; + &:before { + z-index: 4; + content: ''; + position: absolute; + inset: 0; + background-image: linear-gradient( + 90deg, + var(--ck-body-background-transparent) 50%, + var(--ck-body-background), + var(--ck-body-background-transparent) + ); + opacity: 0.75; + background-size: 200% 100%; + animation: ${PlaceholderKeyframes$1} 1000ms linear infinite both; + } +`;function addressToNumber(et){return et.split("").map(o=>o.charCodeAt(0)).reduce((o,tt)=>o+tt)%100/100}const EnsAvatar=styled(motion.div)` + will-change: transform; // Needed for Safari + pointer-events: none; + user-select: none; + position: relative; + overflow: hidden; + margin: 0; + border-radius: ${et=>`${et.$radius}px`}; + width: ${et=>`${et.$size}px`}; + height: ${et=>`${et.$size}px`}; + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08); + &:before { + content: ''; + z-index: 1; + position: absolute; + inset: 0; + border-radius: inherit; + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.02); + } + ${et=>{if(et.$seed){const o=Math.ceil(addressToNumber(et.$seed)*8),tt=`0${o===0?1:o}`;return Ae` + background: var(--ck-ens-${tt}-start); + background: linear-gradient( + 180deg, + var(--ck-ens-${tt}-start) 0%, + var(--ck-ens-${tt}-stop) 100% + ); + `}}} +`,ImageContainer=styled(motion.img)` + display: block; + position: relative; + width: 100%; + height: 100%; + opacity: ${et=>et.$loaded?1:0}; + will-change: opacity; // Needed for Safari + transition: opacity 500ms ease; + transform: scale(1.01); // fixes background color bleeding +`;function useIsMounted(){const[et,o]=reactExports.useState(!1);return reactExports.useEffect(()=>o(!0),[]),et}const ensFallbackConfig=createConfig({chains:[mainnet],transports:{[mainnet.id]:http()}});function useEnsFallbackConfig(){return useChainIsSupported(1)?void 0:ensFallbackConfig}const Avatar=({address:et,name:o,size:tt=96,radius:rt=96})=>{var nt,ot,it;const st=useIsMounted(),at=useContext(),ct=reactExports.useRef(null),[lt,dt]=reactExports.useState(!0),ht=useEnsFallbackConfig(),{data:mt}=useEnsAddress({chainId:1,name:o,config:ht}),{data:ft}=useEnsName({chainId:1,address:(nt=et??mt)!==null&&nt!==void 0?nt:void 0,config:ht}),{data:pt}=useEnsAvatar({chainId:1,name:normalize$2(ft??""),config:ht}),gt={address:mt??et,name:ft??o,avatar:pt??void 0};return reactExports.useEffect(()=>{ct.current&&ct.current.complete&&ct.current.naturalHeight!==0||dt(!1)},[pt]),st?!((ot=at.options)===null||ot===void 0)&&ot.customAvatar?jsxRuntimeExports.jsx("div",{style:{width:tt,height:tt,borderRadius:rt,overflow:"hidden"},children:(it=at.options)===null||it===void 0?void 0:it.customAvatar({address:et??(gt==null?void 0:gt.address),ensName:o??(gt==null?void 0:gt.name),ensImage:gt==null?void 0:gt.avatar,size:tt,radius:rt})}):!gt.name||!gt.avatar?jsxRuntimeExports.jsx(ResetContainer,{style:{pointerEvents:"none"},children:jsxRuntimeExports.jsx(EnsAvatar,{$size:tt,$seed:gt.address,$radius:rt})}):jsxRuntimeExports.jsx(ResetContainer,{style:{pointerEvents:"none"},children:jsxRuntimeExports.jsx(EnsAvatar,{$size:tt,$seed:gt.address,$radius:rt,children:jsxRuntimeExports.jsx(ImageContainer,{ref:ct,src:gt.avatar,alt:gt.name,onLoad:()=>dt(!0),$loaded:lt})})}):jsxRuntimeExports.jsx("div",{style:{width:tt,height:tt,borderRadius:rt}})},KnownChain=({testnet:et,...o})=>jsxRuntimeExports.jsxs("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"black"},children:[jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M20.5611 8.12948C21.0082 7.90729 21.5007 7.79167 22 7.79167C22.4993 7.79167 22.9919 7.90729 23.439 8.12948L23.4408 8.1304L33.0387 12.9293C33.577 13.197 34.031 13.61 34.3478 14.121C34.6649 14.6323 34.833 15.2218 34.8333 15.8234V27.2595C34.833 27.8611 34.6649 28.4511 34.3478 28.9624C34.031 29.4733 33.578 29.8858 33.0398 30.1535L23.4411 34.9528C22.9919 35.1775 22.4963 35.2947 21.994 35.2947C21.4918 35.2947 20.9964 35.1777 20.5472 34.9529L10.9475 30.1531L10.9452 30.1519C10.4071 29.8808 9.95535 29.4646 9.6411 28.9504C9.32739 28.437 9.16312 27.8464 9.16673 27.2448L9.16675 27.2417L10.0004 27.2475H9.16673V27.2448V15.8239C9.16705 15.2223 9.33518 14.6322 9.65222 14.121C9.96906 13.61 10.4221 13.1976 10.9604 12.9298L20.5592 8.1304L20.5611 8.12948ZM21.3031 9.62267L11.8706 14.3389L22 19.4036L32.1294 14.3389L22.697 9.62267C22.4806 9.51531 22.2416 9.45905 22 9.45905C21.7585 9.45905 21.5194 9.51534 21.3031 9.62267ZM10.8341 15.8241C10.8341 15.7785 10.8362 15.733 10.8401 15.6878L21.1663 20.8509V33.3983L11.6955 28.6629C11.4352 28.5315 11.2159 28.3297 11.0638 28.0809C10.9116 27.8318 10.8321 27.5452 10.8341 27.2533L10.8341 27.2475V15.8241ZM22.8337 33.3923L32.2967 28.6608C32.5576 28.5312 32.7772 28.3313 32.9308 28.0836C33.0844 27.836 33.1658 27.5504 33.166 27.259V15.8243C33.1659 15.7786 33.1639 15.7331 33.1599 15.6878L22.8337 20.8509V33.3923Z",fill:"url(#paint0_linear_3546_7073)"}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M10.8341 15.8241C10.8341 15.7785 10.8362 15.733 10.8401 15.6878L21.1663 20.8509V33.3983L11.6955 28.6629C11.4352 28.5315 11.2159 28.3297 11.0638 28.0809C10.9116 27.8318 10.8321 27.5452 10.8341 27.2533L10.8341 27.2475V15.8241Z",fill:"url(#paint1_linear_3546_7073)",fillOpacity:"0.3"}),jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_3546_7073",x1:"22",y1:"7.79167",x2:"22",y2:"35.2947",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"white"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"white",stopOpacity:"0.7"})]}),jsxRuntimeExports.jsxs("linearGradient",{id:"paint1_linear_3546_7073",x1:"22",y1:"7.79167",x2:"22",y2:"35.2947",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"white"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"white",stopOpacity:"0.7"})]})]})]}),UnknownChain=({testnet:et,...o})=>jsxRuntimeExports.jsx(KnownChain,{testnet:!0,...o}),Ethereum=({testnet:et,...o})=>{let tt="var(--ck-chain-ethereum-01, #25292E)",rt="var(--ck-chain-ethereum-02, #ffffff)";return et&&(tt="linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)",rt="#fff"),jsxRuntimeExports.jsxs("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:tt},children:[jsxRuntimeExports.jsx("path",{d:"M21.9967 6.99621L21.7955 7.67987V27.5163L21.9967 27.7171L31.2044 22.2744L21.9967 6.99621Z",fill:rt}),jsxRuntimeExports.jsx("path",{d:"M21.9957 6.99621L12.7878 22.2744L21.9957 27.7171V18.0891V6.99621Z",fill:rt}),jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M21.9959 36.9996L21.9959 36.9997V36.9995L31.2091 24.0243L21.9959 29.4642L12.788 24.0243L21.9957 36.9993L21.9958 36.9997L21.9959 36.9996Z",fill:rt}),jsxRuntimeExports.jsx("path",{d:"M21.996 27.7181L31.2037 22.2753L21.996 18.09V27.7181Z",fill:rt}),jsxRuntimeExports.jsx("path",{d:"M12.7878 22.2753L21.9957 27.7181V18.09L12.7878 22.2753Z",fill:rt})]})},Polygon=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#6F41D8"},children:jsxRuntimeExports.jsx("path",{d:"M29.0015 17.4529C28.4941 17.1572 27.8355 17.1572 27.2773 17.4529L23.3186 19.7271L20.6305 21.2094L16.6719 23.4822C16.1645 23.7792 15.5059 23.7792 14.9476 23.4822L11.8016 21.703C11.2943 21.4074 10.9395 20.8642 10.9395 20.2702V16.7612C10.9395 16.1686 11.2434 15.6255 11.8016 15.3285L14.8954 13.5988C15.4041 13.3018 16.0641 13.3018 16.6224 13.5988L19.7161 15.3285C20.2249 15.6255 20.5796 16.1686 20.5796 16.7612V19.0355L23.2678 17.5024V15.2295C23.2707 14.9343 23.1917 14.6441 23.0395 14.3911C22.8873 14.1381 22.6679 13.9324 22.4056 13.7968L16.6719 10.5353C16.1645 10.2382 15.5059 10.2382 14.9476 10.5353L9.11214 13.7968C8.84992 13.9324 8.63049 14.1381 8.47828 14.3911C8.32607 14.6441 8.24705 14.9343 8.25002 15.2295V21.802C8.25002 22.396 8.55389 22.9391 9.11214 23.2361L14.9476 26.4976C15.455 26.7932 16.115 26.7932 16.6719 26.4976L20.6305 24.2729L23.3186 22.7411L27.2773 20.5177C27.7846 20.2207 28.4433 20.2207 29.0015 20.5177L32.0966 22.2475C32.6054 22.5431 32.9588 23.0863 32.9588 23.6803V27.1893C32.9588 27.7819 32.6563 28.325 32.0966 28.622L29.0029 30.4013C28.4941 30.6983 27.8341 30.6983 27.2773 30.4013L24.1821 28.6715C23.6734 28.3745 23.3186 27.8314 23.3186 27.2387V24.9645L20.6305 26.4976V28.7705C20.6305 29.3631 20.9344 29.9076 21.4926 30.2032L27.3281 33.4647C27.8355 33.7617 28.4941 33.7617 29.0524 33.4647L34.8879 30.2032C35.3953 29.9076 35.75 29.3645 35.75 28.7705V22.198C35.753 21.9028 35.674 21.6126 35.5218 21.3596C35.3695 21.1066 35.1501 20.9009 34.8879 20.7653L29.0029 17.4529H29.0015Z",fill:"white"})}),Optimism=({testnet:et,...o})=>jsxRuntimeExports.jsxs("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#FF0420"},children:[jsxRuntimeExports.jsx("path",{d:"M15.5877 27.8473C14.2777 27.8473 13.2045 27.539 12.3679 26.9226C11.5422 26.2952 11.1294 25.4035 11.1294 24.2477C11.1294 24.0055 11.157 23.7082 11.212 23.356C11.3552 22.5634 11.5588 21.6112 11.823 20.4994C12.5715 17.4722 14.5034 15.9586 17.6187 15.9586C18.4664 15.9586 19.2259 16.1017 19.8974 16.3879C20.5689 16.663 21.0973 17.0814 21.4826 17.6428C21.8678 18.1932 22.0605 18.8537 22.0605 19.6242C22.0605 19.8554 22.033 20.1471 21.9779 20.4994C21.8128 21.4791 21.6146 22.4313 21.3835 23.356C20.9982 24.8641 20.3322 25.9924 19.3855 26.741C18.4388 27.4785 17.1729 27.8473 15.5877 27.8473ZM15.8189 25.4695C16.4354 25.4695 16.9582 25.2879 17.3876 24.9247C17.8279 24.5614 18.1416 24.0055 18.3287 23.257C18.5819 22.2222 18.7746 21.3195 18.9067 20.5489C18.9507 20.3178 18.9727 20.0811 18.9727 19.8389C18.9727 18.8372 18.4498 18.3363 17.4041 18.3363C16.7876 18.3363 16.2592 18.5179 15.8189 18.8812C15.3896 19.2445 15.0813 19.8004 14.8943 20.5489C14.6961 21.2865 14.4979 22.1892 14.2998 23.257C14.2557 23.477 14.2337 23.7082 14.2337 23.9504C14.2337 24.9632 14.7622 25.4695 15.8189 25.4695Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M22.8188 27.6815C22.6977 27.6815 22.6041 27.6429 22.5381 27.5659C22.483 27.4778 22.4665 27.3788 22.4885 27.2687L24.7672 16.5358C24.7892 16.4147 24.8498 16.3156 24.9489 16.2385C25.0479 16.1615 25.1525 16.1229 25.2626 16.1229H29.6548C30.8767 16.1229 31.8564 16.3761 32.5939 16.8825C33.3426 17.3889 33.7168 18.1209 33.7168 19.0786C33.7168 19.3538 33.6838 19.64 33.6177 19.9372C33.3426 21.2032 32.7867 22.1389 31.95 22.7443C31.1244 23.3498 29.9905 23.6525 28.5485 23.6525H26.3194L25.5598 27.2687C25.5377 27.3898 25.4772 27.4888 25.3782 27.5659C25.2791 27.6429 25.1745 27.6815 25.0645 27.6815H22.8188ZM28.6641 21.3738C29.1264 21.3738 29.5282 21.2472 29.8695 20.994C30.2217 20.7408 30.4529 20.3776 30.563 19.9042C30.596 19.717 30.6125 19.552 30.6125 19.4089C30.6125 19.0896 30.519 18.8474 30.3318 18.6823C30.1446 18.5062 29.8255 18.4182 29.3741 18.4182H27.3926L26.7652 21.3738H28.6641Z",fill:"white"})]}),Arbitrum=({testnet:et,...o})=>{const tt=et?"#ffffff":"#28A0F0",rt=et?"#ffffff":"#96BEDC";return jsxRuntimeExports.jsxs("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#2C364F"},children:[!et&&jsxRuntimeExports.jsx("path",{d:"M25.7948 20.5826L28.2683 16.3854L34.9355 26.7696L34.9386 28.7625L34.9168 15.0491C34.9011 14.7137 34.7231 14.407 34.4391 14.2261L22.4357 7.32182C22.1551 7.1838 21.7989 7.18546 21.5187 7.32618C21.4807 7.34524 21.4453 7.36576 21.4113 7.38835L21.3694 7.41467L9.71816 14.1664L9.67298 14.1871C9.61474 14.2137 9.55609 14.2479 9.50076 14.2872C9.27983 14.4456 9.1331 14.68 9.08564 14.9425C9.07859 14.9823 9.0732 15.023 9.07092 15.064L9.08916 26.239L15.2994 16.6138C16.0811 15.3376 17.7847 14.9262 19.3662 14.9488L21.2221 14.9977L10.2862 32.5356L11.5753 33.2778L22.6422 15.0155L27.5338 14.9977L16.4956 33.7209L21.0955 36.3668L21.6451 36.6827C21.8776 36.7772 22.1516 36.7819 22.386 36.6972L34.5581 29.6433L32.2309 30.9918L25.7948 20.5826ZM26.7384 34.175L22.0925 26.8829L24.9287 22.0702L31.0303 31.6876L26.7384 34.175Z",fill:"#2D374B"}),jsxRuntimeExports.jsx("path",{d:"M22.0924 26.8832L26.7385 34.1751L31.0302 31.6879L24.9286 22.0705L22.0924 26.8832Z",fill:tt}),jsxRuntimeExports.jsx("path",{d:"M34.9387 28.7627L34.9356 26.7698L28.2684 16.3856L25.7949 20.5828L32.2312 30.992L34.5584 29.6435C34.7866 29.4582 34.9248 29.1861 34.9393 28.8926L34.9387 28.7627Z",fill:tt}),jsxRuntimeExports.jsx("path",{d:"M7 30.642L10.2863 32.5356L21.2222 14.9976L19.3663 14.9487C17.785 14.9263 16.0814 15.3375 15.2995 16.6137L9.08927 26.239L7 29.449V30.642V30.642Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M27.534 14.9977L22.6423 15.0155L11.5754 33.2778L15.4437 35.5049L16.4955 33.7209L27.534 14.9977Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M37 14.9723C36.9592 13.9493 36.4052 13.013 35.5377 12.4677L23.377 5.47434C22.5187 5.04223 21.4466 5.04161 20.5868 5.47414C20.4852 5.52533 8.76078 12.3251 8.76078 12.3251C8.5985 12.4029 8.44224 12.4955 8.2953 12.6008C7.52081 13.156 7.0487 14.0186 7 14.9661V29.4492L9.08927 26.2392L9.07103 15.0639C9.07352 15.0231 9.0787 14.9827 9.08575 14.9431C9.133 14.6801 9.27994 14.4457 9.50086 14.2872C9.5562 14.2478 21.4806 7.34517 21.5186 7.32611C21.799 7.18538 22.155 7.18373 22.4356 7.32175L34.439 14.226C34.723 14.4069 34.901 14.7137 34.9167 15.049V28.8921C34.9022 29.1856 34.7862 29.4577 34.558 29.643L32.2308 30.9916L31.03 31.6875L26.7383 34.1747L22.3859 36.6969C22.1515 36.7817 21.8773 36.7769 21.645 36.6824L16.4955 33.7206L15.4435 35.5046L20.0713 38.169C20.2243 38.256 20.3607 38.3331 20.4726 38.3961C20.6458 38.4933 20.764 38.5582 20.8056 38.5785C21.1345 38.7383 21.6077 38.8311 22.0342 38.8311C22.4251 38.8311 22.8064 38.7594 23.1672 38.6181L35.8092 31.2971C36.5347 30.7348 36.9617 29.8869 37 28.9686V14.9723Z",fill:rt})]})},Telos=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#571AFF"},children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M26.1834 8.14754C25.6606 8.23504 25.3644 8.50235 24.9216 9.28591C24.5651 9.91722 24.4762 10.0244 24.2024 10.1592L23.9832 10.2668L19.2967 10.286L14.6097 10.3057L14.3875 10.3902C13.7059 10.6492 13.6192 10.7135 11.6291 12.4407C9.72243 14.0953 9.64893 14.1723 9.59249 14.5836C9.54437 14.9362 9.78981 15.6327 10.5191 17.2143C11.2847 18.8737 11.2839 18.8641 10.7444 19.5256C10.2645 20.1136 10.2269 20.2588 10.2041 21.5915C10.1717 23.502 10.2487 27.6023 10.3222 27.8591C10.3572 27.9816 10.7908 29.204 11.2861 30.5755C11.7813 31.9471 12.4192 33.715 12.704 34.5038C13.4281 36.5107 13.4814 36.5986 14.0392 36.7237C14.3066 36.7837 14.3206 36.781 18.9677 35.7258C24.4395 34.4837 23.7264 34.709 25.0739 33.7968C29.8732 30.5475 29.7337 30.66 29.8969 29.9083C30.0583 29.1642 30.1082 29.1379 31.8267 28.8999C34.6122 28.5145 34.6328 28.5083 34.8831 28.0109C35.0182 27.7423 35.7786 23.3406 35.8136 22.6209C35.8504 21.8828 36.042 22.221 33.3816 18.3395C30.022 13.4382 30.2381 13.7777 30.2399 13.4041C30.2407 13.1735 30.3366 12.9736 31.3236 11.1418C31.8236 10.2134 32.2742 9.35241 32.3254 9.22904C32.5236 8.74691 32.4204 8.3921 32.0301 8.21622L31.8267 8.12391L29.1102 8.11822C27.6048 8.11516 26.2997 8.12829 26.1834 8.14754ZM30.0474 9.4876C30.5623 9.72297 30.5382 9.82447 29.5119 11.7398C28.4317 13.7558 28.3157 13.2711 30.7154 16.7707C31.639 18.1173 32.8076 19.8218 33.3124 20.5581C34.6844 22.5592 34.6048 22.1799 34.1831 24.6903C33.7858 27.0602 33.7792 27.0817 33.3759 27.282C33.1506 27.394 33.2276 27.3813 30.8493 27.7117C28.9147 27.9803 28.8543 28.017 28.6719 29.0338C28.5778 29.557 28.4606 29.8169 28.2243 30.0247C28.0808 30.1512 24.8682 32.368 23.9451 32.9778C23.2587 33.4311 23.6861 33.3152 17.7471 34.6574C17.1997 34.7812 16.4079 34.9632 15.987 35.0617C14.4588 35.4195 14.4299 35.4033 13.8804 33.8948C12.9188 31.2528 11.6811 27.7957 11.6194 27.5787C11.5534 27.3463 11.549 27.1202 11.549 24.059V20.7878L11.6501 20.5966C11.7056 20.4912 11.8671 20.2759 12.0088 20.118C12.8418 19.19 12.8383 19.1183 11.8601 16.9907C10.7663 14.612 10.6797 14.9992 12.697 13.2501C14.2418 11.91 14.3048 11.8593 14.5905 11.7237L14.8394 11.6055L19.6983 11.5854C23.5417 11.5692 24.5891 11.5543 24.7103 11.515C25.1465 11.3728 25.4086 11.1094 25.7975 10.4203C26.3851 9.38041 26.3111 9.40797 28.4597 9.41891C29.6996 9.42547 29.9332 9.43554 30.0474 9.4876Z",fill:"#F7F5FC"})}),Aurora=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#6CD544"},children:jsxRuntimeExports.jsx("path",{d:"M22.0006 7.292C22.6198 7.29004 23.2271 7.46144 23.754 7.7868C24.2808 8.11216 24.706 8.57848 24.9816 9.133L34.3566 27.883C34.611 28.3912 34.7312 28.956 34.7058 29.5238C34.6805 30.0915 34.5103 30.6433 34.2116 31.1268C33.9129 31.6103 33.4956 32.0094 32.9992 32.2861C32.5028 32.5629 31.9439 32.7081 31.3756 32.708H12.6256C12.0573 32.7079 11.4985 32.5626 11.0023 32.2858C10.506 32.009 10.0888 31.6099 9.79022 31.1264C9.49163 30.6429 9.3216 30.0912 9.29628 29.5235C9.27096 28.9558 9.39119 28.3911 9.64556 27.883L19.0196 9.133C19.2951 8.57848 19.7203 8.11216 20.2472 7.7868C20.774 7.46144 21.3814 7.29004 22.0006 7.292ZM22.0006 5C20.9561 4.9999 19.9322 5.29059 19.0437 5.83952C18.1551 6.38846 17.4369 7.17394 16.9696 8.108L7.59456 26.858C7.16544 27.7156 6.96271 28.6687 7.00564 29.6268C7.04856 30.5848 7.33572 31.516 7.83982 32.3318C8.34392 33.1476 9.04823 33.821 9.88584 34.288C10.7235 34.755 11.6666 35.0001 12.6256 35H31.3756C32.3345 34.9999 33.2775 34.7547 34.1149 34.2876C34.9524 33.8206 35.6566 33.1472 36.1606 32.3314C36.6645 31.5156 36.9516 30.5845 36.9945 29.6265C37.0374 28.6686 36.8346 27.7156 36.4056 26.858L27.0316 8.108C26.5642 7.17394 25.846 6.38846 24.9574 5.83952C24.0689 5.29059 23.045 4.9999 22.0006 5Z",fill:"white"})}),Avalanche=({testnet:et,...o})=>jsxRuntimeExports.jsxs("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#E84142"},children:[jsxRuntimeExports.jsx("path",{d:"M11.0188 32.1528H15.4825C16.5334 32.1528 17.0589 32.1528 17.5278 32.023C18.042 31.8701 18.511 31.5991 18.9009 31.2261C19.2589 30.885 19.5173 30.4328 20.0269 29.5409L20.0272 29.5404L20.0422 29.5142L25.8314 19.2804C26.3456 18.3821 26.5999 17.93 26.7129 17.4554C26.8372 16.9412 26.8372 16.3988 26.7129 15.8847C26.6007 15.4136 26.3439 14.9648 25.8373 14.0798L25.8258 14.0597L23.56 10.1045C23.0911 9.27958 22.8538 8.86711 22.5543 8.71456C22.2323 8.55071 21.848 8.55071 21.526 8.71456C21.2265 8.86711 20.9892 9.27958 20.5202 10.1045L9.49892 29.5311C9.03561 30.3447 8.80392 30.7517 8.82089 31.0849C8.84349 31.4466 9.02994 31.7743 9.33507 31.9721C9.61756 32.1528 10.0809 32.1528 11.0188 32.1528Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M33.1506 32.1528H26.7547C25.8111 32.1528 25.3365 32.1528 25.0596 31.9721C24.7545 31.7743 24.5681 31.4411 24.5455 31.0794C24.5286 30.7486 24.7621 30.3456 25.2294 29.539L25.2295 29.5388L25.2404 29.5199L28.4328 24.0392C28.9018 23.2313 29.1391 22.8301 29.4329 22.6776C29.7548 22.5137 30.1336 22.5137 30.4555 22.6776C30.7472 22.8261 30.9744 23.2102 31.4241 23.9708L31.4248 23.9719L31.4613 24.0336L34.665 29.5143C34.6806 29.5413 34.696 29.5678 34.7113 29.5939L34.7113 29.594C35.1554 30.3603 35.382 30.7514 35.3657 31.0739C35.3486 31.4353 35.1566 31.7688 34.8515 31.9666C34.5689 32.1528 34.0942 32.1528 33.1506 32.1528Z",fill:"white"})]}),Celo=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#FCFE72"},children:jsxRuntimeExports.jsx("path",{d:"M9 9H34.5183V18.112H30.3564C28.896 14.7687 25.6102 12.4171 21.777 12.4171C16.593 12.4171 12.3948 16.6422 12.3948 21.823C12.3948 27.0039 16.593 31.2654 21.777 31.2654C25.5373 31.2654 28.8231 28.9876 30.2829 25.7172H34.5178V34.682H9V9Z",fill:et?"#ffffff":"black"})}),Gnosis=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#009CB4"},children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.3439 11.8664C17.9374 6.53462 26.7953 6.74397 32.1271 12.3374C32.4738 12.7038 32.8075 13.0832 33.1084 13.4823L22 24.5972L10.8916 13.4823C11.1991 13.0832 11.5262 12.7038 11.8729 12.3374C12.0234 12.1804 12.1804 12.0234 12.3439 11.8664ZM30.6094 13.3972C28.3196 11.0944 25.271 9.83182 22 9.83182C18.729 9.83182 15.6804 11.0944 13.3907 13.3972L22 22.0066L30.6094 13.3972ZM33.9785 14.7446L31.7215 17.0016C33.5402 19.1801 33.2523 22.425 31.0738 24.2437C29.1636 25.84 26.3897 25.84 24.4794 24.2437L22 26.7231L19.5271 24.2502C17.3486 26.0689 14.1037 25.7811 12.285 23.6026C10.6888 21.6923 10.6888 18.9185 12.285 17.0082L11.1271 15.8502L10.028 14.7446C8.7 16.9297 8 19.4418 8 21.9998C8 29.7325 14.2673 35.9998 22 35.9998C29.7327 35.9998 36 29.7325 36 21.9998C36.0065 19.4418 35.3 16.9297 33.9785 14.7446ZM30.6486 18.0747C31.1392 18.7093 31.4075 19.4943 31.4075 20.299C31.4075 21.1037 31.1392 21.8887 30.6486 22.5233C29.4187 24.113 27.1355 24.4074 25.5458 23.1775L30.6486 18.0747ZM18.4542 23.1839C17.8196 23.6745 17.0346 23.9427 16.2299 23.9427C15.4252 23.9427 14.6467 23.6745 14.0056 23.1904C12.4159 21.9605 12.1215 19.6708 13.3514 18.0811L18.4542 23.1839Z",fill:"white"})}),Evmos=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#2D2A25"},children:jsxRuntimeExports.jsx("path",{d:"M18.4916 12.6668C12.9416 14.806 12.4332 20.2846 10.8418 22.8432C9.23155 25.4322 5.54251 26.8607 6.04698 28.1801C6.55143 29.4994 10.2449 28.0824 13.1669 28.9242C16.0543 29.7561 20.0831 33.4862 25.633 31.3469C28.4603 30.2573 30.5076 28.0143 31.449 25.3574C31.5502 25.0723 31.361 24.7673 31.0606 24.7391C30.874 24.7215 30.6948 24.8196 30.6106 24.9877C29.759 26.6908 28.2981 28.0934 26.3864 28.8301C23.2303 30.0465 19.777 29.0915 17.6562 26.6961C17.1746 26.1522 16.7626 25.533 16.4374 24.8487C16.348 24.6603 16.2629 24.4689 16.1875 24.2708C16.1117 24.0728 16.0473 23.8735 15.9881 23.6732C17.6562 22.8925 19.5812 22.0656 21.7635 21.2246C23.903 20.3999 25.8505 19.731 27.5841 19.1958C28.7571 18.8341 29.8322 18.5331 30.8029 18.2871C30.8732 18.2695 30.9423 18.2519 31.0112 18.2347C31.158 18.1982 31.3088 18.2769 31.363 18.4186L31.364 18.4213C31.396 18.5053 31.4236 18.5898 31.4535 18.6743C31.6453 19.2196 31.7892 19.7706 31.8841 20.3229C31.9258 20.5645 32.1888 20.6961 32.4044 20.5799C33.2014 20.1504 33.9302 19.7314 34.5814 19.3283C37.0083 17.8276 38.3538 16.5549 38.0776 15.8336C37.802 15.1119 35.9541 15.0705 33.1503 15.5854C32.2593 15.7491 31.2716 15.9691 30.207 16.2416C30.0229 16.2886 29.8365 16.3375 29.6481 16.3877C28.7522 16.6262 27.8073 16.8995 26.8234 17.2053C24.9936 17.7744 23.0305 18.4561 21.0038 19.2372C19.1078 19.9682 17.3109 20.726 15.6629 21.4812C15.6428 18.2761 17.5725 15.2461 20.7286 14.0297C22.6399 13.293 24.6605 13.3533 26.4285 14.0473C26.6029 14.116 26.8015 14.0684 26.9291 13.9298C27.1331 13.7076 27.0706 13.3537 26.8053 13.2094C24.3353 11.8685 21.319 11.5771 18.4916 12.6668Z",fill:"#FAF1E4"})}),BinanceSmartChain=({testnet:et,...o})=>jsxRuntimeExports.jsxs("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#16181A"},children:[jsxRuntimeExports.jsx("path",{d:"M16.0445 19.6063L21.8705 13.7805L27.6996 19.6093L31.0896 16.2193L21.8705 7L12.6545 16.2163L16.0445 19.6063Z",fill:et?"#fff":"#F3BA2F"}),jsxRuntimeExports.jsx("path",{d:"M13.6505 21.9995L10.2606 18.6096L6.87046 21.9997L10.2604 25.3896L13.6505 21.9995Z",fill:et?"#fff":"#F3BA2F"}),jsxRuntimeExports.jsx("path",{d:"M16.0445 24.3937L21.8705 30.2195L27.6994 24.3909L31.0913 27.779L31.0896 27.7809L21.8705 37L12.6542 27.7839L12.6495 27.7792L16.0445 24.3937Z",fill:et?"#fff":"#F3BA2F"}),jsxRuntimeExports.jsx("path",{d:"M33.4808 25.3911L36.8709 22.001L33.481 18.6111L30.0909 22.0012L33.4808 25.3911Z",fill:et?"#fff":"#F3BA2F"}),jsxRuntimeExports.jsx("path",{d:"M25.3091 21.9982H25.3105L21.8705 18.5582L19.3283 21.1004H19.3281L19.0362 21.3926L18.4336 21.9951L18.4289 21.9999L18.4336 22.0048L21.8705 25.4418L25.3105 22.0018L25.3122 21.9999L25.3091 21.9982Z",fill:et?"#fff":"#F3BA2F"})]}),Canto=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"white"},children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M35 8V36H9L13.875 35.9998V31.0586H9V12.9412H13.875V8H35ZM17.9373 12.9414H30.1247V17.8826H17.9373V12.9414ZM30.1247 26.9414H17.9373V17.8826L13.0623 17.8828V26.9416L17.9373 26.9414V31.8826H30.1247V26.9414Z",fill:"#06FC99"})}),Fantom=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#0911EF"},children:jsxRuntimeExports.jsx("path",{d:"M20.92 9.25864C21.5933 8.91379 22.6178 8.91379 23.2911 9.25864L30.1616 12.7775C30.5671 12.9852 30.7898 13.2947 30.8297 13.6142H30.8363V31.302C30.8274 31.6504 30.6025 31.9966 30.1616 32.2225L23.2911 35.7413C22.6178 36.0862 21.5933 36.0862 20.92 35.7413L14.0495 32.2225C13.6104 31.9976 13.3997 31.6489 13.3893 31.302C13.3883 31.2678 13.3881 31.2393 13.3891 31.2157L13.3891 13.7278C13.3884 13.7086 13.3883 13.6895 13.3889 13.6705L13.3893 13.6142L13.3924 13.6142C13.4229 13.2912 13.6355 12.9896 14.0495 12.7775L20.92 9.25864ZM29.7547 23.4821L23.2911 26.7926C22.6178 27.1374 21.5933 27.1374 20.92 26.7926L14.4706 23.4895V31.2669L20.92 34.5527C21.2842 34.7415 21.6622 34.9254 22.0318 34.9488L22.1056 34.9512C22.4907 34.9524 22.8646 34.7628 23.2438 34.5833L29.7547 31.2387V23.4821ZM11.3214 31.8437C11.3214 32.5212 11.4026 32.9667 11.5639 33.2806C11.6976 33.5407 11.8981 33.7394 12.2643 33.9813L12.2852 33.9951C12.3656 34.0476 12.4541 34.1026 12.5619 34.1672L12.689 34.2427L13.0792 34.4711L12.5195 35.3685L12.0827 35.1126L12.0093 35.0689C11.883 34.9932 11.7783 34.9284 11.6807 34.8645C10.637 34.1822 10.2478 33.4384 10.2401 31.8907L10.24 31.8437H11.3214ZM21.5647 18.7412C21.5147 18.7579 21.4678 18.7772 21.4251 18.7991L14.5546 22.318C14.5474 22.3216 14.5405 22.3253 14.534 22.3289L14.5281 22.3322L14.5389 22.3382L14.5546 22.3464L21.4251 25.8653C21.4678 25.8872 21.5147 25.9065 21.5647 25.9231V18.7412ZM22.6465 18.7412V25.9231C22.6965 25.9065 22.7433 25.8872 22.7861 25.8653L29.6566 22.3464C29.6638 22.3427 29.6707 22.3391 29.6772 22.3355L29.683 22.3322L29.6722 22.3262L29.6566 22.318L22.7861 18.7991C22.7433 18.7772 22.6965 18.7579 22.6465 18.7412ZM29.7547 14.8689L23.5915 18.0256L29.7547 21.1822V14.8689ZM14.4706 14.8763V21.1749L20.6195 18.0256L14.4706 14.8763ZM22.7861 10.1859C22.4288 10.0029 21.7824 10.0029 21.4251 10.1859L14.5546 13.7048C14.5474 13.7085 14.5405 13.7122 14.534 13.7158L14.5281 13.719L14.5389 13.725L14.5546 13.7333L21.4251 17.2522C21.7824 17.4352 22.4288 17.4352 22.7861 17.2522L29.6566 13.7333C29.6638 13.7296 29.6707 13.7259 29.6772 13.7223L29.683 13.719L29.6722 13.7131L29.6566 13.7048L22.7861 10.1859ZM31.7205 9.64552L32.1573 9.90132L32.2307 9.94503C32.357 10.0206 32.4616 10.0856 32.5593 10.1494C33.603 10.8317 33.9922 11.5756 33.9998 13.1231L34 13.1703H32.9186C32.9186 12.4926 32.8373 12.0472 32.6761 11.7334C32.5424 11.4733 32.3419 11.2745 31.9757 11.0327L31.9547 11.0189C31.8744 10.9664 31.7858 10.9113 31.6781 10.8466L31.551 10.7712L31.1608 10.5428L31.7205 9.64552Z",fill:"white"})}),Filecoin=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#0090FF"},children:jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M23.75 19.3069L23.15 22.5069L28.85 23.3069L28.45 24.8069L22.85 24.0069C22.45 25.3069 22.25 26.7069 21.75 27.9069C21.25 29.3069 20.75 30.7069 20.15 32.0069C19.35 33.7069 17.95 34.9069 16.05 35.2069C14.95 35.4069 13.75 35.3069 12.85 34.6069C12.55 34.4069 12.25 34.0069 12.25 33.7069C12.25 33.3069 12.45 32.8069 12.75 32.6069C12.95 32.5069 13.45 32.6069 13.75 32.7069C14.05 33.0069 14.35 33.4069 14.55 33.8069C15.15 34.6069 15.95 34.7069 16.75 34.1069C17.65 33.3069 18.15 32.2069 18.45 31.1069C19.05 28.7069 19.65 26.4069 20.15 24.0069V23.6069L14.85 22.8069L15.05 21.3069L20.55 22.1069L21.25 19.0069L15.55 18.1069L15.75 16.5069L21.65 17.3069C21.85 16.7069 21.95 16.2069 22.15 15.7069C22.65 13.9069 23.15 12.1069 24.35 10.5069C25.55 8.90687 26.95 7.90687 29.05 8.00687C29.95 8.00687 30.85 8.30687 31.45 9.00687C31.55 9.10687 31.75 9.30687 31.75 9.50687C31.75 9.90687 31.75 10.4069 31.45 10.7069C31.05 11.0069 30.55 10.9069 30.15 10.5069C29.85 10.2069 29.65 9.90687 29.35 9.60687C28.75 8.80687 27.85 8.70687 27.15 9.40687C26.65 9.90687 26.15 10.6069 25.85 11.3069C25.15 13.4069 24.65 15.6069 23.95 17.8069L29.45 18.6069L29.05 20.1069L23.75 19.3069Z",fill:"white"})}),IoTeX=({testnet:et,...o})=>jsxRuntimeExports.jsxs("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#00D4D5"},children:[jsxRuntimeExports.jsx("path",{d:"M23.7136 6.875V14.3784L30.2284 10.6315L23.7136 6.875Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.9",d:"M30.2284 10.6316V18.135L36.7418 14.3785L30.2284 10.6316Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.8",d:"M23.7136 14.3784V21.8818L30.2284 18.1349L23.7136 14.3784ZM30.2284 18.1349V25.6383L36.7417 21.8818L30.2284 18.1349Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.8",d:"M23.7136 21.8817V29.385L30.2284 25.6382L23.7136 21.8817Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M30.2284 25.6382V33.1416L36.7418 29.3851L30.2284 25.6382Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.4",d:"M6.87537 14.1253V21.6287L13.3901 17.8722L6.87537 14.1253Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.2",d:"M15.0938 16.9153V24.4186L21.5975 20.6718L15.0938 16.9153Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.3",d:"M10.2648 21.6604V29.1638L16.7781 25.4073L10.2648 21.6604Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.9",d:"M14.5575 27.3226V34.826L21.0612 31.0695L14.5575 27.3226Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.7",d:"M23.66 30.5525V38.0572L30.1637 34.2993L23.66 30.5525Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.9",d:"M16.1786 13.2097V20.7145L22.6824 16.9676L16.1786 13.2097Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.8",d:"M23.7136 6.875V14.3784L17.1989 10.6315L23.7136 6.875Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.6",d:"M16.1786 10.0649V17.5669L9.66248 13.8104L16.1786 10.0649Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.6",d:"M22.6934 13.7775V21.2823L16.1786 17.5244L22.6934 13.7775Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.95",d:"M15.0635 16.9153V24.4186L8.54877 20.6718L15.0635 16.9153Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.6",d:"M23.7136 21.8817V29.385L17.2099 25.6382L23.7136 21.8817Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.55",d:"M10.2648 23.6295V31.1328L3.75 27.375L10.2648 23.6295Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M36.7418 14.3784V21.8818L30.2284 18.1349L36.7418 14.3784Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.95",d:"M30.2284 18.1362V25.6382L23.7136 21.8817L30.2284 18.1362Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.9",d:"M36.7418 21.8817V29.385L30.2284 25.6382L36.7418 21.8817Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.7",d:"M30.2284 25.6382V33.1416L23.7136 29.3851L30.2284 25.6382Z",fill:"white"}),jsxRuntimeExports.jsx("path",{opacity:"0.4",d:"M22.2712 28.7651V36.2684L15.7579 32.5216L22.2712 28.7651Z",fill:"white"}),jsxRuntimeExports.jsx("path",{d:"M30.2284 10.6316V18.135L23.7136 14.3785L30.2284 10.6316Z",fill:"white"})]}),Metis=({testnet:et,...o})=>jsxRuntimeExports.jsx("svg",{...o,"aria-hidden":"true",width:"44",height:"44",viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{background:et?"linear-gradient(180deg, #8995A9 0%, #424D5F 99.48%)":"#2F3140"},children:jsxRuntimeExports.jsx("path",{d:"M37.5175 22.0531C37.4579 19.2923 36.6563 16.5985 35.1968 14.2542C33.7374 11.91 31.674 10.0017 29.223 8.72965C26.772 7.45759 24.0238 6.86863 21.2668 7.02455C18.5098 7.18047 15.8456 8.07553 13.5537 9.61582C11.2617 11.1561 9.42659 13.2849 8.24079 15.7787C7.05498 18.2725 6.56222 21.0396 6.81419 23.7895C7.06617 26.5394 8.05359 29.1708 9.67288 31.4076C11.2922 33.6444 13.4836 35.4042 16.0173 36.5023C16.7657 35.3775 17.3385 34.1453 17.716 32.848C18.0245 32.0632 18.3595 31.2913 18.7067 30.5446C19.5444 30.7955 20.4345 30.8143 21.282 30.5989C22.1295 30.3835 22.9026 29.942 23.5188 29.3215L23.5704 29.2699C22.8136 28.9884 21.9979 28.9032 21.1993 29.022C20.4006 29.1408 19.6451 29.4598 19.0029 29.9494C19.4276 29.0613 19.891 28.1997 20.3667 27.3632C21.189 27.6541 22.075 27.7156 22.9296 27.541C23.7842 27.3665 24.5751 26.9626 25.2175 26.3726L25.2692 26.3209C24.538 26.0116 23.7416 25.8885 22.9513 25.9626C22.1609 26.0368 21.4013 26.3058 20.7404 26.7456C21.216 25.9608 21.7053 25.1889 22.2203 24.468C23.0713 24.6915 23.9672 24.6777 24.811 24.4282C25.6547 24.1787 26.414 23.703 27.0066 23.0526L27.0453 23.001C26.3425 22.7718 25.5958 22.7106 24.8651 22.8224C24.1344 22.9341 23.4401 23.2157 22.838 23.6444C22.8767 23.5928 22.9283 23.5289 22.9664 23.4773C23.2749 23.0784 23.5969 22.6796 23.9177 22.2936C24.8969 21.9731 25.7703 21.3916 26.4436 20.6117C27.117 19.8318 27.5649 18.883 27.7391 17.8674L27.752 17.79H27.7391C26.7194 18.0552 25.7944 18.6007 25.0689 19.3648C24.3434 20.1288 23.8464 21.0808 23.6343 22.1129C23.3258 22.4859 23.0167 22.8603 22.7211 23.2449C22.9706 22.5925 23.0724 21.893 23.0191 21.1966C22.9657 20.5002 22.7586 19.8243 22.4126 19.2176L22.3739 19.2692C21.8489 19.9862 21.5326 20.8345 21.4599 21.7201C21.3873 22.6058 21.5611 23.4942 21.9621 24.2872C21.4729 24.9823 20.9972 25.6897 20.5467 26.4357C20.6918 25.6858 20.6542 24.9118 20.4369 24.1795C20.2196 23.4471 19.8291 22.7779 19.2985 22.2284L19.2727 22.2929C18.9445 23.1107 18.8477 24.0031 18.9929 24.8723C19.1382 25.7415 19.5199 26.5539 20.0962 27.2205C19.6457 28.0054 19.2211 28.816 18.8093 29.6524C18.9344 28.8712 18.8712 28.0715 18.6251 27.3196C18.3789 26.5677 17.9568 25.8855 17.3939 25.3295L17.3681 25.3941C17.0745 26.2514 17.0201 27.1724 17.2105 28.0583C17.401 28.9442 17.8292 29.7614 18.4492 30.4223C18.1774 31.0012 17.9219 31.5774 17.6773 32.1849C17.61 32.1231 17.5313 32.0751 17.4456 32.0435C17.0066 31.916 16.5867 31.7299 16.1974 31.4904C15.8754 31.2994 15.5337 31.144 15.1781 31.027C13.7886 30.5765 13.9945 29.9079 13.2756 28.5564C13.0416 28.2781 12.7931 28.0125 12.5309 27.7607C12.2876 27.603 12.0884 27.386 11.9519 27.1302C11.7934 26.8107 11.6931 26.4656 11.6557 26.1109C11.6514 25.9148 11.5858 25.7249 11.4681 25.5679C11.3504 25.4109 11.1864 25.2948 10.9993 25.2358C8.95338 24.5284 9.86728 21.8778 9.94406 21.5299C9.91262 21.08 9.81271 20.6375 9.64781 20.2178C9.63057 20.1632 9.61763 20.1073 9.60908 20.0506C9.55449 19.776 9.56444 19.4924 9.63813 19.2223C9.71183 18.9521 9.84726 18.7028 10.0338 18.4939C10.2784 18.2493 11.1277 17.8505 11.3078 17.6188C11.4879 17.387 11.6163 17.1295 11.797 16.9114C12.3687 16.3412 13.0291 15.8675 13.7526 15.509C14.3444 15.1876 14.4477 14.364 14.6787 14.1065C15.0647 13.6689 15.6565 13.6689 16.0941 13.283C16.3129 13.09 16.6377 12.9867 16.8415 12.7815C17.8692 11.8403 19.1644 11.2423 20.5474 11.0706C21.5064 10.9924 22.4717 11.0795 23.4012 11.3281C23.5358 11.3507 23.669 11.3809 23.8001 11.4185C25.9228 11.4959 28.4709 11.9328 29.397 12.8338C29.8555 13.2744 30.1961 13.8229 30.3877 14.4293C30.5382 14.8988 30.7456 15.3481 31.0054 15.7672L31.5714 16.6933C31.932 17.2773 32.0475 17.9801 31.8928 18.6489C31.7885 18.974 31.7795 19.3223 31.8669 19.6525C32.1655 20.1031 32.5152 20.5177 32.9093 20.8878C33.0658 21.0427 33.2382 21.1807 33.4236 21.2995C33.8592 21.5594 34.2802 21.8429 34.6848 22.1489C34.698 22.2729 34.6775 22.3982 34.6254 22.5115C34.5732 22.6247 34.4914 22.7218 34.3885 22.7924C34.0284 23.1137 33.3333 23.6159 33.3333 23.6159C33.3584 23.758 33.4016 23.8964 33.4617 24.0276C33.5643 24.2077 33.796 24.4911 33.7192 24.735C33.6424 24.9789 33.1403 25.1855 33.2816 25.4552C33.423 25.7386 33.7831 25.8154 33.6805 26.0729C33.5779 26.3175 33.0757 26.7524 33.1274 26.9352C33.179 27.1179 33.5908 28.8377 32.6382 29.1353C31.4592 29.3685 30.2627 29.5019 29.0614 29.5342C28.8675 29.5454 28.6797 29.6055 28.5155 29.709C28.3513 29.8125 28.216 29.956 28.1223 30.126C27.9399 30.4661 27.8222 30.837 27.7751 31.22C27.4275 32.5896 26.9671 33.928 26.3985 35.2215C26.3985 35.2215 26.3597 35.2989 26.3081 35.4144C26.1833 35.6687 26.1048 35.9432 26.0764 36.2251C26.1573 36.4321 26.2799 36.6204 26.4365 36.7782C26.519 36.8726 26.6271 36.9411 26.7477 36.9753C26.8683 37.0096 26.9962 37.0081 27.116 36.9711C30.1997 35.8965 32.8655 33.8757 34.7332 31.197C36.601 28.5182 37.5754 25.3182 37.5175 22.0531Z",fill:et?"#ffffff":"#00DACC"})});var Chains={UnknownChain,Ethereum,Polygon,Optimism,Arbitrum,Aurora,Avalanche,Celo,Telos,Gnosis,Evmos,BinanceSmartChain,Foundry:KnownChain,Sepolia:KnownChain,Taraxa:KnownChain,zkSync:KnownChain,Flare:KnownChain,Canto,Fantom,Filecoin,Metis,IoTeX};const chainConfigs=[{id:1,name:"Ethereum",logo:jsxRuntimeExports.jsx(Chains.Ethereum,{}),rpcUrls:{alchemy:{http:["https://eth-mainnet.g.alchemy.com/v2"],webSocket:["wss://eth-mainnet.g.alchemy.com/v2"]},infura:{http:["https://mainnet.infura.io/v3"],webSocket:["wss://mainnet.infura.io/ws/v3"]}}},{id:3,name:"Rinkeby",logo:jsxRuntimeExports.jsx(Chains.Ethereum,{testnet:!0}),rpcUrls:{}},{id:4,name:"Ropsten",logo:jsxRuntimeExports.jsx(Chains.Ethereum,{testnet:!0})},{id:5,name:"Görli",logo:jsxRuntimeExports.jsx(Chains.Ethereum,{testnet:!0})},{id:42,name:"Kovan",logo:jsxRuntimeExports.jsx(Chains.Ethereum,{testnet:!0})},{id:10,name:"Optimism",logo:jsxRuntimeExports.jsx(Chains.Optimism,{})},{id:69,name:"Optimism Kovan",logo:jsxRuntimeExports.jsx(Chains.Optimism,{testnet:!0})},{id:420,name:"Optimism Goerli",logo:jsxRuntimeExports.jsx(Chains.Optimism,{testnet:!0})},{id:137,name:"Polygon",logo:jsxRuntimeExports.jsx(Chains.Polygon,{})},{id:80001,name:"Polygon Mumbai",logo:jsxRuntimeExports.jsx(Chains.Polygon,{testnet:!0})},{id:31337,name:"Hardhat",logo:jsxRuntimeExports.jsx(Chains.Ethereum,{testnet:!0})},{id:1337,name:"Localhost",logo:jsxRuntimeExports.jsx(Chains.Ethereum,{testnet:!0})},{id:42161,name:"Arbitrum",logo:jsxRuntimeExports.jsx(Chains.Arbitrum,{}),rpcUrls:{alchemy:{http:["https://arb-mainnet.g.alchemy.com/v2"],webSocket:["wss://arb-mainnet.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-mainnet.infura.io/v3"],webSocket:["wss://arbitrum-mainnet.infura.io/ws/v3"]}}},{id:421611,name:"Arbitrum Rinkeby",logo:jsxRuntimeExports.jsx(Chains.Arbitrum,{testnet:!0})},{id:421613,name:"Arbitrum Goerli",logo:jsxRuntimeExports.jsx(Chains.Arbitrum,{testnet:!0}),rpcUrls:{alchemy:{http:["https://arb-goerli.g.alchemy.com/v2"],webSocket:["wss://arb-goerli.g.alchemy.com/v2"]},infura:{http:["https://arbitrum-goerli.infura.io/v3"],webSocket:["wss://arbitrum-goerli.infura.io/ws/v3"]}}},{id:40,name:"Telos",logo:jsxRuntimeExports.jsx(Chains.Telos,{})},{id:41,name:"Telos Testnet",logo:jsxRuntimeExports.jsx(Chains.Telos,{testnet:!0})},{id:1313161554,name:"Aurora",logo:jsxRuntimeExports.jsx(Chains.Aurora,{})},{id:1313161555,name:"Aurora Testnet",logo:jsxRuntimeExports.jsx(Chains.Aurora,{testnet:!0})},{id:43114,name:"Avalanche",logo:jsxRuntimeExports.jsx(Chains.Avalanche,{})},{id:43113,name:"Avalanche Fuji",logo:jsxRuntimeExports.jsx(Chains.Avalanche,{testnet:!0})},{id:31337,name:"Foundry",logo:jsxRuntimeExports.jsx(Chains.Foundry,{testnet:!0})},{id:100,name:"Gnosis",logo:jsxRuntimeExports.jsx(Chains.Gnosis,{})},{id:9001,name:"Evmos",logo:jsxRuntimeExports.jsx(Chains.Evmos,{})},{id:9e3,name:"Evmos Testnet",logo:jsxRuntimeExports.jsx(Chains.Evmos,{testnet:!0})},{id:56,name:"BNB Smart Chain",logo:jsxRuntimeExports.jsx(Chains.BinanceSmartChain,{})},{id:97,name:"Binance Smart Chain Testnet",logo:jsxRuntimeExports.jsx(Chains.BinanceSmartChain,{testnet:!0})},{id:11155111,name:"Sepolia",logo:jsxRuntimeExports.jsx(Chains.Sepolia,{})},{id:841,name:"Taraxa",logo:jsxRuntimeExports.jsx(Chains.Taraxa,{})},{id:842,name:"Taraxa Testnet",logo:jsxRuntimeExports.jsx(Chains.Taraxa,{testnet:!0})},{id:324,name:"zkSync",logo:jsxRuntimeExports.jsx(Chains.zkSync,{})},{id:280,name:"zkSync Testnet",logo:jsxRuntimeExports.jsx(Chains.zkSync,{testnet:!0})},{id:42220,name:"Celo",logo:jsxRuntimeExports.jsx(Chains.Celo,{})},{id:44787,name:"Celo Alfajores",logo:jsxRuntimeExports.jsx(Chains.Celo,{testnet:!0})},{id:7700,name:"Canto",logo:jsxRuntimeExports.jsx(Chains.Canto,{})},{id:250,name:"Fantom",logo:jsxRuntimeExports.jsx(Chains.Fantom,{})},{id:4002,name:"Fantom Testnet",logo:jsxRuntimeExports.jsx(Chains.Fantom,{testnet:!0})},{id:14,name:"Flare",logo:jsxRuntimeExports.jsx(Chains.Flare,{})},{id:114,name:"Coston2",logo:jsxRuntimeExports.jsx(Chains.Flare,{})},{id:314,name:"Filecoin",logo:jsxRuntimeExports.jsx(Chains.Filecoin,{})},{id:3141,name:"Filecoin Hyperspace",logo:jsxRuntimeExports.jsx(Chains.Filecoin,{testnet:!0})},{id:314159,name:"Filecoin Calibration",logo:jsxRuntimeExports.jsx(Chains.Filecoin,{testnet:!0})},{id:1088,name:"Metis",logo:jsxRuntimeExports.jsx(Chains.Metis,{})},{id:599,name:"Metis Goerli",logo:jsxRuntimeExports.jsx(Chains.Metis,{testnet:!0})},{id:4689,name:"IoTeX",logo:jsxRuntimeExports.jsx(Chains.IoTeX,{})},{id:4690,name:"IoTeX Testnet",logo:jsxRuntimeExports.jsx(Chains.IoTeX,{testnet:!0})}],SwitchNetworksContainer=styled.div` + display: flex; + flex-direction: column; + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + flex-direction: column-reverse; + } +`,ChainIcon=styled(motion.div)` + display: block; + position: relative; + border-radius: 12px; + overflow: hidden; + width: 24px; + height: 24px; + min-width: 24px; + min-height: 24px; + background: var(--ck-body-background); + svg { + border-radius: inherit; + display: block; + position: relative; + transform: translate3d(0, 0, 0); + width: 100%; + height: auto; + } + ${et=>et.$empty&&Ae` + display: flex; + align-items: center; + justify-content: center; + &:before { + content: '?'; + color: var(--ck-body-color-muted); + font-weight: bold; + font-family: var(--ck-font-family); + } + `} + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + border-radius: 16px; + width: 32px; + height: 32px; + } +`,ChainLogoContainer=styled(motion.div)` + position: relative; +`,ChainLogoSpinner=styled(motion.div)` + position: absolute; + inset: -6px; + animation: rotateSpinner 1200ms linear infinite; + pointer-events: none; + svg { + display: block; + position: relative; + transform: translate3d(0, 0, 0); + width: 100%; + height: auto; + } + @keyframes rotateSpinner { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } + } +`,ChainButtonContainer=styled.div` + position: relative; + margin: -8px -8px; + &:after { + border-radius: var(--border-radius, 0); + z-index: 2; + content: ''; + pointer-events: none; + position: absolute; + inset: 0 2px; + box-shadow: inset 0 16px 8px -12px var(--background, var(--ck-body-background)), + inset 0 -16px 8px -12px var(--background, var(--ck-body-background)); + } +`,ChainButtons=styled(motion.div)` + padding: 8px; + overflow-x: hidden; + overflow-y: auto; + max-height: 242px; + + -ms-overflow-style: none; /* Internet Explorer 10+ */ + scrollbar-width: none; /* Firefox */ + &::-webkit-scrollbar { + display: none; /* Safari and Chrome */ + } + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + padding: 8px 14px; + margin: 2px -2px 0; + max-height: 60vh; + } +`,ChainButton=styled(motion.button)` + appearance: none; + cursor: pointer; + user-select: none; + position: relative; + display: flex; + align-items: center; + justify-content: space-between; + width: 100%; + border-radius: 11px; + margin: 0 0 1px; + padding: 8px 0; + padding-right: 154px; + font-size: 15px; + line-height: 18px; + font-weight: 500; + text-decoration: none; + color: var(--ck-body-color); + background: none; + white-space: nowrap; + transition: transform 100ms ease, background-color 100ms ease; + transform: translateZ(0px); + &:before { + content: ''; + background: currentColor; + position: absolute; + z-index: -1; + inset: 0 var(--ck-dropdown-active-inset, -8px); + border-radius: var(--ck-dropdown-active-border-radius, 12px); + opacity: 0; + transition: opacity 180ms ease; + } + &:after { + content: ''; + position: absolute; + z-index: -1; + inset: 0 var(--ck-dropdown-active-inset, -8px); + border-radius: 12px; + opacity: 0; + transition: opacity 180ms ease; + outline: 2px solid var(--ck-focus-color); + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + font-size: 17px; + padding: 8px 0; + } + @media only screen and (min-width: ${defaultTheme.mobileWidth}px) { + &:hover { + &:before { + transition-duration: 80ms; + opacity: 0.05; + } + } + } + &:active { + transform: scale(0.99) translateZ(0px); + } + &:disabled { + //opacity: 0.4; + pointer-events: none; + } + &:focus-visible { + outline: none !important; + &:after { + opacity: 1; + } + } + ${et=>et.$variant==="secondary"&&Ae` + padding: 12px 4px; + margin: 0 0 8px; + &:last-child { + margin-bottom: 0; + } + &:before { + opacity: 0.05; + } + &:hover:before { + opacity: 0.1; + } + `} +`,ChainButtonStatus=styled(motion.div)` + position: absolute; + top: 0; + bottom: 0; + right: 0; + display: flex; + align-items: center; + justify-content: center; + + color: var(--ck-body-color-muted); + font-size: 15px; + line-height: 18px; + font-weight: 500; + padding-right: 4px; + span { + display: block; + position: relative; + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + font-size: 17px; + padding: 0; + } +`,ChainButtonBg=styled(motion.div)` + position: absolute; + z-index: -1; + inset: 0 var(--ck-dropdown-active-inset, -8px); + background: var(--ck-dropdown-active-background, rgba(26, 136, 248, 0.1)); + box-shadow var(--ck-dropdown-active-box-shadow); + border-radius: var(--ck-dropdown-active-border-radius, 12px); + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + inset: 0 var(--ck-dropdown-active-inset, -8px); + } +`,Spinner$1=jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"36",height:"36",viewBox:"0 0 36 36",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M2 16.75C2.69036 16.75 3.25 17.3096 3.25 18V19C3.25 26.5939 9.40609 32.75 17 32.75V35.25C8.02537 35.25 0.75 27.9746 0.75 19V18C0.75 17.3096 1.30964 16.75 2 16.75Z",fill:"url(#paint0_linear_1288_18701)"}),jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_1288_18701",x1:"2",y1:"19.4884",x2:"16.8752",y2:"33.7485",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-spinner-color)"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"var(--ck-spinner-color)",stopOpacity:"0"})]})})]}),ChainSelectList=({variant:et})=>{const{connector:o,chain:tt}=useAccount(),{chains:rt,isPending:nt,switchChain:ot,error:it}=useSwitchChain(),[st,at]=reactExports.useState(void 0),ct=useLocales({}),lt=isMobile(),dt=(it==null?void 0:it.code)===4902,ht=dt||!ot,mt=pt=>{ot&&(at(pt),ot({chainId:pt}))},{triggerResize:ft}=useContext();return jsxRuntimeExports.jsxs(SwitchNetworksContainer,{style:{marginBottom:ot!==void 0?-8:0},children:[jsxRuntimeExports.jsx(ChainButtonContainer,{children:jsxRuntimeExports.jsx(ChainButtons,{children:rt.map(pt=>{var gt;const bt={...chainConfigs.find(xt=>xt.id===pt.id),...pt};return jsxRuntimeExports.jsxs(ChainButton,{$variant:et,disabled:ht||bt.id===(tt==null?void 0:tt.id)||nt&&st===bt.id,onClick:()=>mt==null?void 0:mt(bt.id),style:{opacity:ht&&bt.id!==(tt==null?void 0:tt.id)?.4:void 0},children:[jsxRuntimeExports.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"flex-start",gap:12,color:bt.id===(tt==null?void 0:tt.id)?"var(--ck-dropdown-active-color, inherit)":"inherit"},children:[jsxRuntimeExports.jsxs(ChainLogoContainer,{children:[jsxRuntimeExports.jsx(ChainLogoSpinner,{initial:{opacity:0},animate:{opacity:nt&&st===bt.id?1:0},transition:{ease:[.76,0,.24,1],duration:.15,delay:.1},children:jsxRuntimeExports.jsx(motion.div,{animate:lt&&isCoinbaseWalletConnector(o==null?void 0:o.id)&&nt&&st===bt.id?{opacity:[1,0],transition:{delay:4,duration:3}}:{opacity:1},children:Spinner$1},`${bt==null?void 0:bt.id}-${bt==null?void 0:bt.name}`)}),jsxRuntimeExports.jsx(ChainIcon,{children:(gt=bt.logo)!==null&>!==void 0?gt:jsxRuntimeExports.jsx(Chains.UnknownChain,{})})]}),bt.name]}),et!=="secondary"&&jsxRuntimeExports.jsx(ChainButtonStatus,{children:jsxRuntimeExports.jsxs(AnimatePresence,{initial:!1,exitBeforeEnter:!0,children:[bt.id===(tt==null?void 0:tt.id)&&jsxRuntimeExports.jsx(motion.span,{style:{color:"var(--ck-dropdown-active-color, var(--ck-focus-color))",display:"block",position:"relative"},initial:{opacity:0,x:-4},animate:{opacity:1,x:0},exit:{opacity:0,x:4,transition:{duration:.1,delay:0}},transition:{ease:[.76,0,.24,1],duration:.3,delay:.2},children:ct.connected},"connectedText"),nt&&st===bt.id&&jsxRuntimeExports.jsx(motion.span,{style:{color:"var(--ck-dropdown-pending-color, inherit)",display:"block",position:"relative"},initial:{opacity:0,x:-4},animate:{opacity:1,x:0},exit:{opacity:0,x:4},transition:{ease:[.76,0,.24,1],duration:.3,delay:.1},children:jsxRuntimeExports.jsx(motion.span,{animate:lt&&isCoinbaseWalletConnector(o==null?void 0:o.id)&&{opacity:[1,0],transition:{delay:4,duration:4}},children:ct.approveInWallet})},"approveText")]})}),et==="secondary"?jsxRuntimeExports.jsx(ChainButtonBg,{initial:!1,animate:{opacity:bt.id===(tt==null?void 0:tt.id)?1:0},transition:{duration:.3,ease:"easeOut"}}):bt.id===(tt==null?void 0:tt.id)&&jsxRuntimeExports.jsx(ChainButtonBg,{layoutId:"activeChain",layout:"position",transition:{duration:.3,ease:"easeOut"}})]},`${bt==null?void 0:bt.id}-${bt==null?void 0:bt.name}`)})})}),jsxRuntimeExports.jsx(AnimatePresence,{children:dt&&jsxRuntimeExports.jsx(motion.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{ease:[.76,0,.24,1],duration:.3},onAnimationStart:ft,onAnimationComplete:ft,children:jsxRuntimeExports.jsx("div",{style:{paddingTop:10,paddingBottom:8},children:jsxRuntimeExports.jsxs(Alert,{children:[ct.warnings_walletSwitchingUnsupported," ",ct.warnings_walletSwitchingUnsupportedResolve]})})})})]})},DropdownWindow=styled(motion.div)` + z-index: 2147483647; + position: fixed; + inset: 0; +`,DropdownOverlay=styled(motion.div)` + position: absolute; + inset: 0; +`,DropdownContainer=styled(motion.div)` + --shadow: 0px 2px 15px rgba(0, 0, 0, 0.15); + --background: var(--ck-dropdown-background, var(--ck-tooltip-background)); + --border-radius: var( + --ck-dropdown-border-radius, + var(--ck-tooltip-border-radius, 12px) + ); + + pointer-events: auto; + z-index: 2147483647; + position: absolute; + top: 0; + left: 0; + width: 100%; + max-width: fit-content; + padding: 14px 16px 16px; + color: var(--ck-dropdown-color, var(--ck-tooltip-color)); + background: var(--background); + box-shadow: var( + --ck-dropdown-box-shadow, + var(--ck-tooltip-shadow, var(--shadow)) + ); + border-radius: var(--border-radius); +`,DropdownHeading=styled(motion.div)` + padding: 0 0 6px; + font-size: 14px; + line-height: 20px; + font-weight: 400; + user-select: none; + color: var(--ck-dropdown-color, var(--ck-tooltip-color)); +`,ChainSelectDropdown=({children:et,open:o,onClose:tt,offsetX:rt=0,offsetY:nt=8})=>{var ot,it,st;const at=useContext(),ct=useThemeContext(),lt=useLocales(),[dt,ht]=reactExports.useState({x:0,y:0});useLockBodyScroll(o);const mt=reactExports.useRef(null);reactExports.useEffect(()=>{const Ct=St=>{var At,kt,It;if(o&&(St.key==="Escape"&&tt(),St.key==="ArrowDown"||St.key==="ArrowUp")){if(!mt.current)return;St.preventDefault();const Ot=(At=mt.current)===null||At===void 0?void 0:At.querySelectorAll(` + a[href]:not(:disabled), + button:not(:disabled), + textarea:not(:disabled), + input[type="text"]:not(:disabled), + input[type="radio"]:not(:disabled), + input[type="checkbox"]:not(:disabled), + select:not(:disabled) + `),Nt=Ot[0],Yt=Ot[Ot.length-1];if(St.key==="ArrowUp")if(document.activeElement===Nt)Yt.focus();else{let Ft=(kt=document==null?void 0:document.activeElement)===null||kt===void 0?void 0:kt.previousSibling;for(Ft||(Ft=Yt);Ft.disabled;)Ft=Ft.previousSibling;Ft.focus()}else if(document.activeElement===Yt)Nt.focus();else{let Ft=(It=document==null?void 0:document.activeElement)===null||It===void 0?void 0:It.nextSibling;for(Ft||(Ft=Nt);Ft.disabled;)Ft=Ft.nextSibling;Ft.focus()}}};return document.addEventListener("keydown",Ct),()=>{document.removeEventListener("keydown",Ct)}},[o]);const ft=reactExports.useRef(null),pt=reactExports.useCallback(Ct=>{Ct&&(ft.current=Ct,bt())},[o]),[gt,yt]=useMeasure({debounce:120,offsetSize:!0,scroll:!0}),bt=()=>{if(!ft.current||yt.top+yt.bottom+yt.left+yt.right+yt.height+yt.width===0)return;let Ct=yt.left+rt,St=yt.top+yt.height+nt;ft.current.style.left=`${Ct}px`,ft.current.style.top=`${St}px`};(typeof window<"u"?reactExports.useLayoutEffect:reactExports.useEffect)(bt,[ft.current,yt,o]),reactExports.useEffect(bt,[o,ft.current]);const vt=tt,Et=tt;return reactExports.useEffect(()=>(bt(),window.addEventListener("scroll",vt),window.addEventListener("resize",Et),()=>{window.removeEventListener("scroll",vt),window.removeEventListener("resize",Et)}),[]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{ref:gt,children:et}),jsxRuntimeExports.jsx(AnimatePresence,{children:o&&jsxRuntimeExports.jsx(Portal$2,{children:jsxRuntimeExports.jsx(ResetContainer,{$useTheme:(ot=ct.theme)!==null&&ot!==void 0?ot:at.theme,$useMode:(it=ct.mode)!==null&&it!==void 0?it:at.mode,$customTheme:(st=ct.customTheme)!==null&&st!==void 0?st:at.customTheme,children:jsxRuntimeExports.jsx(FocusTrap,{children:jsxRuntimeExports.jsxs(DropdownWindow,{ref:mt,children:[jsxRuntimeExports.jsx(DropdownOverlay,{onClick:tt}),jsxRuntimeExports.jsxs(DropdownContainer,{ref:pt,style:{left:dt.x,top:dt.y},initial:"collapsed",animate:"open",exit:"collapsed",variants:{collapsed:{transformOrigin:"0 0",opacity:0,scale:.96,z:.01,y:-4,x:0,transition:{duration:.1}},open:{transformOrigin:"0 0",willChange:"opacity,transform",opacity:1,scale:1,z:.01,y:0,x:0,transition:{ease:[.76,0,.24,1],duration:.15}}},children:[jsxRuntimeExports.jsx(DropdownHeading,{children:lt.switchNetworks}),jsxRuntimeExports.jsx(ChainSelectList,{})]})]})})})})})]})},ChainContainer=styled.div` + --bg: transparent; + --color: #333; + ${et=>typeof et.size=="string"?Ae` + --width: ${et.size}; + --height: ${et.size}; + `:Ae` + --width: ${et.size>=0?`${et.size}px`:"24px"}; + --height: ${et.size>=0?`${et.size}px`:"24px"}; + `}; + ${et=>typeof et.radius=="string"?Ae` + --radius: ${et.radius}; + `:Ae` + --radius: ${et.radius>=0?`${et.radius}px`:"24px"}; + `}; + display: block; + position: relative; + width: var(--width); + height: var(--height); + min-width: var(--width); + min-height: var(--height); + border-radius: var(--radius); + background: var(--ck-body-background-secondary); + pointer-events: none; + user-select: none; + svg { + display: block; + width: 100%; + height: auto; + } + > div { + display: flex; + align-items: center; + justify-content: center; + } +`,LogoContainer$1=styled(motion.div)` + display: block; + position: absolute; + inset: 0; + overflow: hidden; + border-radius: inherit; + user-select: none; + display: flex; + align-items: center; + justify-content: center; + svg { + display: block; + width: 100%; + height: auto; + } +`,Spin=We` + 0%{ transform: rotate(0deg); } + 100%{ transform: rotate(360deg); } +`,LoadingContainer=styled(motion.div)` + position: absolute; + inset: 0; + animation: ${Spin} 1s linear infinite; + svg { + display: block; + position: absolute; + inset: 0; + } +`,Unsupported=styled(motion.div)` + z-index: 2; + position: absolute; + top: 0; + right: 0; + width: 40%; + height: 40%; + min-width: 13px; + min-height: 13px; + color: var(--ck-body-color-danger, red); + svg { + display: block; + position: relative; + top: -30%; + right: -30%; + } +`,Spinner=jsxRuntimeExports.jsxs("svg",{"aria-hidden":"true",width:"36",height:"36",viewBox:"0 0 36 36",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.3592 30.1654C10.0472 29.4491 8.85718 28.524 7.83713 27.424C6.81708 26.324 5.98425 25.0677 5.36889 23.7054C5.20157 23.335 5.05033 22.9567 4.91578 22.5717C4.51465 21.4237 4.26735 20.2308 4.17794 19.0239C4.16599 18.8626 4.13894 18.7041 4.09809 18.5507C3.85023 17.6197 3.09399 16.8738 2.11531 16.7999C0.975331 16.7138 -0.0310983 17.5702 0.0141657 18.7125C0.0223289 18.9185 0.0340286 19.1243 0.049253 19.3298C0.165374 20.8971 0.486545 22.4464 1.00749 23.9373C1.10424 24.2142 1.20764 24.4884 1.31755 24.7596C2.13617 26.7799 3.31595 28.6371 4.80146 30.239C6.28696 31.841 8.04998 33.1573 10.0029 34.1258C10.2651 34.2558 10.5307 34.3796 10.7995 34.4969C12.247 35.1287 13.7676 35.5656 15.3217 35.7995C15.5255 35.8301 15.7298 35.8573 15.9346 35.881C17.0703 36.0122 18.0001 35.0731 18.0001 33.9299C18.0001 32.9484 17.3133 32.1381 16.4036 31.8208C16.2537 31.7685 16.0977 31.7296 15.9377 31.7056C14.7411 31.5255 13.5702 31.1891 12.4556 30.7026C12.0818 30.5394 11.716 30.3601 11.3592 30.1654Z",fill:"url(#paint0_linear_1288_1870)"}),jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsxs("linearGradient",{id:"paint0_linear_1288_1870",x1:"2",y1:"19.4884",x2:"16.8752",y2:"33.7485",gradientUnits:"userSpaceOnUse",children:[jsxRuntimeExports.jsx("stop",{stopColor:"var(--ck-connectbutton-balance-color,currentColor)",stopOpacity:"0.7"}),jsxRuntimeExports.jsx("stop",{offset:"1",stopColor:"var(--ck-connectbutton-balance-color,currentColor)",stopOpacity:"0"})]})})]}),Chain=({id:et,unsupported:o,radius:tt="50%",size:rt=24})=>{var nt;const ot=useChainIsSupported(et),it=o??!ot,st=chainConfigs.find(ct=>ct.id===et);return useIsMounted()?jsxRuntimeExports.jsx(ChainContainer,{size:rt,radius:tt,children:jsxRuntimeExports.jsxs(AnimatePresence,{initial:!1,children:[it&&jsxRuntimeExports.jsx(Unsupported,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:jsxRuntimeExports.jsxs("svg",{width:"13",height:"12",viewBox:"0 0 13 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntimeExports.jsx("path",{d:"M2.61317 11.2501H9.46246C10.6009 11.2501 11.3256 10.3506 11.3256 9.3549C11.3256 9.05145 11.255 8.73244 11.0881 8.43303L7.65903 2.14708C7.659 2.14702 7.65897 2.14696 7.65893 2.1469C7.65889 2.14682 7.65884 2.14673 7.65879 2.14664C7.31045 1.50746 6.6741 1.17871 6.04 1.17871C5.41478 1.17871 4.763 1.50043 4.41518 2.14968L0.993416 8.43476C0.828865 8.72426 0.75 9.04297 0.75 9.3549C0.75 10.3506 1.47471 11.2501 2.61317 11.2501Z",fill:"currentColor",stroke:"var(--ck-body-background, #fff)",strokeWidth:"1.5"}),jsxRuntimeExports.jsx("path",{d:"M6.03258 7.43916C5.77502 7.43916 5.63096 7.29153 5.62223 7.02311L5.55675 4.96973C5.54802 4.69684 5.74446 4.5 6.02821 4.5C6.3076 4.5 6.51277 4.70131 6.50404 4.9742L6.43856 7.01864C6.42546 7.29153 6.2814 7.43916 6.03258 7.43916ZM6.03258 9.11676C5.7401 9.11676 5.5 8.9065 5.5 8.60677C5.5 8.30704 5.7401 8.09678 6.03258 8.09678C6.32506 8.09678 6.56515 8.30256 6.56515 8.60677C6.56515 8.91097 6.32069 9.11676 6.03258 9.11676Z",fill:"white"})]})}),et?jsxRuntimeExports.jsx(LogoContainer$1,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.3},children:(nt=st==null?void 0:st.logo)!==null&&nt!==void 0?nt:jsxRuntimeExports.jsx(Chains.UnknownChain,{})},`${st==null?void 0:st.id}-${st==null?void 0:st.name}-${et}`):jsxRuntimeExports.jsx(LoadingContainer,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.3},children:Spinner},"loading")]})}):jsxRuntimeExports.jsx("div",{style:{width:rt,height:rt}})},Container$3=styled(motion.div)``,SwitchChainButton=styled(motion.button)` + --color: var( + --ck-dropdown-button-color, + var(--ck-button-primary-color, var(--ck-body-color)) + ); + --background: var( + --ck-dropdown-button-background, + var(--ck-secondary-button-background, var(--ck-body-background-secondary)) + ); + --box-shadow: var( + --ck-dropdown-button-box-shadow, + var( + --ck-secondary-button-box-shadow, + var(--ck-button-primary-box-shadow), + none + ) + ); + + --hover-color: var(--ck-dropdown-button-hover-color, var(--color)); + --hover-background: var( + --ck-dropdown-button-hover-background, + var(--background) + ); + --hover-box-shadow: var( + --ck-dropdown-button-hover-box-shadow, + var(--box-shadow) + ); + + --active-color: var(--ck-dropdown-button-active-color, var(--hover-color)); + --active-background: var( + --ck-dropdown-button-active-background, + var(--hover-background) + ); + --active-box-shadow: var( + --ck-dropdown-button-active-box-shadow, + var(--hover-box-shadow) + ); + + appearance: none; + user-select: none; + position: relative; + display: flex; + align-items: center; + justify-content: space-between; + border-radius: 15px; + width: 52px; + height: 30px; + padding: 2px 6px 2px 3px; + font-size: 16px; + line-height: 19px; + font-weight: 500; + text-decoration: none; + white-space: nowrap; + transform: translateZ(0px); + + transition: 100ms ease; + transition-property: transform, background-color, box-shadow, color; + + color: var(--color); + background: var(--background); + box-shadow: var(--box-shadow); + + svg { + position: relative; + display: block; + } + + ${et=>et.disabled?Ae` + width: auto; + padding: 3px; + position: relative; + left: -22px; + `:Ae` + cursor: pointer; + + @media only screen and (min-width: ${defaultTheme.mobileWidth+1}px) { + &:hover, + &:focus-visible { + color: var(--hover-color); + background: var(--hover-background); + box-shadow: var(--hover-box-shadow); + } + &:active { + color: var(--active-color); + background: var(--active-background); + box-shadow: var(--active-box-shadow); + } + } + `} +`,ChevronDown=({...et})=>jsxRuntimeExports.jsx("svg",{"aria-hidden":"true",width:"11",height:"6",viewBox:"0 0 11 6",fill:"none",xmlns:"http://www.w3.org/2000/svg",...et,children:jsxRuntimeExports.jsx("path",{d:"M1.5 1L5.5 5L9.5 1",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),ChainSelector=()=>{const et=useContext(),[o,tt]=reactExports.useState(!1),{chain:rt}=useAccount(),{chains:nt}=useSwitchChain(),ot=useLocales({CHAIN:rt==null?void 0:rt.name}),it=isMobile()||(window==null?void 0:window.innerWidth){et.open||tt(!1)},[et.open]);const st=nt.length<=1;return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsx(Container$3,{children:jsxRuntimeExports.jsx(ChainSelectDropdown,{offsetX:-12,open:!it&&o,onClose:()=>tt(!1),children:jsxRuntimeExports.jsxs(SwitchChainButton,{"aria-label":flattenChildren(ot.switchNetworks).toString(),disabled:st,onClick:()=>{it?et.setRoute(routes.SWITCHNETWORKS):tt(!o)},children:[st?jsxRuntimeExports.jsx(Tooltip,{message:ot.chainNetwork,xOffset:-6,delay:.01,children:jsxRuntimeExports.jsx(Chain,{id:rt==null?void 0:rt.id})}):jsxRuntimeExports.jsx(Chain,{id:rt==null?void 0:rt.id}),!st&&jsxRuntimeExports.jsx(ChevronDown,{style:{top:1,left:-3}})]})})})})},Profile=({closeModal:et})=>{var o,tt,rt;const nt=useContext(),ot=useThemeContext(),it=useLocales(),{reset:st}=useConnect$1(),{disconnect:at}=useDisconnect(),{address:ct,isConnected:lt,connector:dt,chain:ht}=useAccount(),mt=useEnsFallbackConfig(),{data:ft}=useEnsName({chainId:1,address:ct,config:mt}),{data:pt}=useBalance({address:ct}),[gt,yt]=reactExports.useState(!1);reactExports.useEffect(()=>{lt||nt.setOpen(!1)},[lt]),reactExports.useEffect(()=>{if(gt)return et?et():nt.setOpen(!1),()=>{at(),st()}},[gt,at,st]);const bt=["web95","rounded","minimal"].includes((tt=(o=ot.theme)!==null&&o!==void 0?o:nt.theme)!==null&&tt!==void 0?tt:"")?"....":void 0;return jsxRuntimeExports.jsxs(PageContent,{children:[jsxRuntimeExports.jsxs(ModalContent,{style:{paddingBottom:22,gap:6},children:[jsxRuntimeExports.jsx(AvatarContainer,{children:jsxRuntimeExports.jsxs(AvatarInner,{children:[jsxRuntimeExports.jsx(ChainSelectorContainer,{children:jsxRuntimeExports.jsx(ChainSelector,{})}),jsxRuntimeExports.jsx(Avatar,{address:ct})]})}),jsxRuntimeExports.jsx(ModalH1,{children:jsxRuntimeExports.jsx(CopyToClipboard,{string:ct,children:ft??truncateEthAddress(ct,bt)})}),!((rt=nt==null?void 0:nt.options)===null||rt===void 0)&&rt.hideBalance?null:jsxRuntimeExports.jsx(ModalBody,{children:jsxRuntimeExports.jsx(BalanceContainer,{children:jsxRuntimeExports.jsxs(AnimatePresence,{exitBeforeEnter:!0,initial:!1,children:[pt&&jsxRuntimeExports.jsxs(Balance$1,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},children:[nFormatter(Number(pt==null?void 0:pt.formatted))," ",pt==null?void 0:pt.symbol]},`chain-${ht==null?void 0:ht.id}`),!pt&&jsxRuntimeExports.jsx(LoadingBalance,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},children:" "})]})})})]}),!isSafeConnector(dt==null?void 0:dt.id)&&jsxRuntimeExports.jsx(Button$1,{onClick:()=>yt(!0),icon:jsxRuntimeExports.jsx(DisconnectIcon,{}),children:it.disconnect})]})},SwitchNetworks=()=>{const{reset:et}=useConnect$1(),{disconnect:o}=useDisconnect(),{connector:tt,chain:rt}=useAccount(),nt=useChainIsSupported(rt==null?void 0:rt.id),ot=useLocales({}),it=()=>{o(),et()};return jsxRuntimeExports.jsx(PageContent,{style:{width:278},children:jsxRuntimeExports.jsxs(ModalContent,{style:{padding:0,marginTop:-10},children:[!nt&&jsxRuntimeExports.jsxs(ModalBody,{children:[ot.warnings_chainUnsupported," ",ot.warnings_chainUnsupportedResolve]}),jsxRuntimeExports.jsx("div",{style:{padding:"6px 8px"},children:jsxRuntimeExports.jsx(ChainSelectList,{variant:"secondary"})}),!nt&&!isSafeConnector(tt==null?void 0:tt.id)&&jsxRuntimeExports.jsxs("div",{style:{paddingTop:12},children:[jsxRuntimeExports.jsx(OrDivider,{}),jsxRuntimeExports.jsx(Button$1,{icon:jsxRuntimeExports.jsx(DisconnectIcon,{}),variant:"secondary",onClick:it,children:ot.disconnect})]})]})})},spinKeyframes=We` + from{ transform: rotate(0deg); } + to{ transform: rotate(360deg); } +`,lineKeyframes=We` + from{ background-position: 0 0; } + to{ background-position: 100% 0; } +`,ContentContainer=styled.div` + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + margin: 5px auto 24px; + padding: 16px 16px; + border-radius: var(--ck-tertiary-border-radius, 24px); + box-shadow: var(--ck-tertiary-box-shadow, none); + background: var(--ck-body-background-tertiary); + } +`,LogoContainer=styled(motion.div)` + z-index: 2; + overflow: hidden; + position: relative; + display: flex; + align-items: center; + justify-content: center; + width: 52px; + height: 52px; + border-radius: 100%; + transition: inherit; + background: var(--ck-body-background-secondary); + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.04); + svg, + img { + display: block; + width: 100%; + height: 100%; + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + width: 64px; + height: 64px; + } +`,StatusIcon=styled(motion.div)` + z-index: 2; + position: relative; + display: flex; + align-items: center; + justify-content: center; + width: 52px; + height: 52px; + color: currentColor; + border-radius: 100%; + transition: inherit; + svg { + z-index: 3; + position: relative; + transform: scale(0.89); + transition: inherit; + opacity: 0.5; + } + &:before { + z-index: 1; + content: ''; + position: absolute; + inset: 10px; + border-radius: inherit; + border: 1px dashed var(--border-color); + background: var(--ck-body-background); + transition: inherit; + animation: ${spinKeyframes} 10s linear infinite; + } + &:after { + z-index: 2; + content: ''; + position: absolute; + inset: 0; + border-radius: inherit; + background: #34c759; + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.04); + transform: scale(0); + transition: inherit; + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + width: 64px; + height: 64px; + svg { + transform: scale(1.1); + } + } +`,StatusGraphicBgSvg=styled(motion.svg)` + display: block; + position: relative; + margin: 0 auto; + transition: inherit; + overflow: visible; + rect { + stroke: var(--border-color); + rx: var(--ck-border-radius); + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + display: none; + } +`,StatusGraphic=styled(motion.div)` + --border-color: var(--ck-siwe-border, var(--ck-body-divider)); + --border-size: 0; + --border-style: dashed; + + user-select: none; + pointer-events: none; + position: relative; + display: flex; + align-items: center; + justify-content: center; + gap: 14px; + width: 100%; + margin: 12px auto; + padding: 42px 32px; + transition: all 320ms cubic-bezier(0.175, 0.885, 0.32, 1.1); + border: var(--border-size) var(--border-style) var(--border-color); + border-radius: var(--ck-border-radius); + + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + --border-size: 1px; + margin: 0 auto 20px; + padding: 38px 0; + gap: 18px; + + div { + // easier than wrapping in another styled component + padding-bottom: 10px; + } + } + + > div { + z-index: 2; + position: relative; + transition: inherit; + } + + &:before, + &:after { + z-index: 1; + content: ''; + position: absolute; + top: 50%; + left: 50%; + width: 120px; + height: 1px; + margin-left: -60px; + transition: inherit; + animation: ${lineKeyframes} 10s linear infinite; + background: linear-gradient( + 90deg, + var(--border-color), + var(--border-color) 50%, + transparent 50%, + transparent 100% + ); + background-size: 6px 1px; + } + + &:after { + background: var(--border-color); + transform: scaleX(0); + } + + ${({$connected:et})=>et&&Ae` + &:before { + opacity: 0; + } + &:after { + transform: none; + } + ${StatusGraphicBgSvg} { + rect { + stroke-dasharray: 0 0; + } + } + ${LogoContainer} { + transform: scale(0.62); + } + ${StatusIcon} { + svg { + transform: scale(1.5); + opacity: 1; + color: #fff; + } + &:before { + transform: scale(0); + } + &:after { + transform: scale(1); + } + } + @media only screen and (max-width: ${defaultTheme.mobileWidth}px) { + --border-size: 1px; + --border-style: solid; + ${StatusIcon} { + svg { + transform: scale(1.75); + } + } + } + `}; +`,SIWEButton=({showSignOutButton:et,onSignIn:o,onSignOut:tt})=>{const rt=useIsMounted(),nt=useLocales(),{setOpen:ot}=useModal(),{isSignedIn:it,isReady:st,isLoading:at,isRejected:ct,isSuccess:lt,isError:dt,signIn:ht,signOut:mt,error:ft}=useSIWE({onSignIn:yt=>o==null?void 0:o(yt),onSignOut:()=>tt==null?void 0:tt()}),{address:pt}=useAccount();function gt(){return lt?nt.signedIn:ct?nt.tryAgain:at?nt.awaitingConfirmation:dt?ft??"Unknown Error":nt.signIn}return rt?et&&it?jsxRuntimeExports.jsx(Button$1,{style:{margin:0},onClick:mt,icon:jsxRuntimeExports.jsx(DisconnectIcon,{}),children:nt.signOut},"button"):pt?jsxRuntimeExports.jsx(Button$1,{style:{margin:0},arrow:it?!1:!at&&!ct,onClick:!at&&!lt?ht:void 0,disabled:at,waiting:at,icon:ct&&jsxRuntimeExports.jsx(motion.div,{initial:{rotate:-270},animate:{rotate:0},transition:{duration:1,ease:[.175,.885,.32,.98]},children:jsxRuntimeExports.jsx(RetryIcon,{style:{opacity:.4}})}),children:gt()},"button"):jsxRuntimeExports.jsx(Button$1,{style:{margin:0},onClick:()=>ot(!0),arrow:!0,children:nt.walletNotConnected},"button"):jsxRuntimeExports.jsx(Button$1,{style:{margin:0},disabled:!0},"loading")},LazyImage=({src:et,alt:o,width:tt,height:rt})=>{const nt=reactExports.useRef(null),[ot,it]=reactExports.useState(!0);return reactExports.useEffect(()=>{nt.current&&nt.current.complete&&nt.current.naturalHeight!==0||it(!1)},[et]),jsxRuntimeExports.jsx("div",{style:{width:tt,height:rt,background:"rgba(0,0,0,0.02)",boxShadow:"inset 0 0 0 1px rgba(0,0,0,0.02)"},children:jsxRuntimeExports.jsx("img",{ref:nt,src:et,alt:o,width:tt,height:rt,onLoad:()=>it(!0),style:{transition:"opacity 0.2s ease",opacity:ot?1:0}})})},transition={duration:.2,ease:[.26,.08,.25,1]},copyTransition={duration:.16,ease:[.26,.08,.25,1]},SignInWithEthereum=()=>{var et,o;const tt=useContext(),{isSignedIn:rt,reset:nt}=useSIWE(),ot=isMobile(),[it,st]=reactExports.useState(rt?"signedIn":"signedOut"),at=useLocales({}),ct=it==="signedIn"?{heading:at.signInWithEthereumScreen_signedIn_heading,h1:at.signInWithEthereumScreen_signedIn_h1,p:at.signInWithEthereumScreen_signedIn_p,button:at.signInWithEthereumScreen_signedIn_button}:{heading:at.signInWithEthereumScreen_signedOut_heading,h1:at.signInWithEthereumScreen_signedOut_h1,p:at.signInWithEthereumScreen_signedOut_p,button:at.signInWithEthereumScreen_signedOut_button};reactExports.useEffect(()=>{rt&&st("signedIn")},[]),reactExports.useEffect(()=>{rt||st("signedOut")},[rt]);const{address:lt}=useAccount(),ht=(()=>{const ft={svg:null,default:null},pt=document.getElementsByTagName("link");return Array.from(pt).forEach(gt=>{(gt.getAttribute("rel")==="icon"||gt.getAttribute("rel")==="shortcut icon")&>.getAttribute("href")&&(gt.getAttribute("type")==="image/svg+xml"?ft.svg=gt.getAttribute("href"):ft.default=gt.getAttribute("href"))}),ft})(),mt=(o=(et=getAppIcon())!==null&&et!==void 0?et:ht.svg)!==null&&o!==void 0?o:ht.default;return jsxRuntimeExports.jsx(PageContent,{style:{width:278},children:jsxRuntimeExports.jsxs(ModalContent,{style:{padding:0,marginTop:-10},children:[jsxRuntimeExports.jsx(ContentContainer,{children:jsxRuntimeExports.jsx(AnimatePresence,{exitBeforeEnter:!0,children:jsxRuntimeExports.jsx(motion.div,{initial:ot?!1:{opacity:0,scale:.94},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.94},transition:copyTransition,children:jsxRuntimeExports.jsx(ModalBody,{style:{height:42},children:jsxRuntimeExports.jsx(FitText,{children:ct.h1})})},flattenChildren(ct.h1).toString())})}),jsxRuntimeExports.jsxs(StatusGraphic,{$connected:rt,children:[jsxRuntimeExports.jsx("div",{style:{position:"absolute",inset:0},children:jsxRuntimeExports.jsx(StatusGraphicBgSvg,{width:"262",height:"134",viewBox:"0 0 262 134",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx(motion.rect,{x:"0",y:"0",rx:"12",width:"262",height:"134",strokeDasharray:"3 3",animate:{strokeDashoffset:[0,-6]},transition:{duration:.4,ease:"linear",repeat:1/0}})})}),jsxRuntimeExports.jsx(motion.div,{initial:ot?!1:{opacity:0,x:50,scale:.8},animate:{opacity:1,x:0,scale:1},transition,children:jsxRuntimeExports.jsx(LogoContainer,{children:jsxRuntimeExports.jsx(Avatar,{address:lt,size:64})})},"avatarImage"),jsxRuntimeExports.jsx(motion.div,{initial:ot?!1:{scale:.6},animate:{scale:1},transition:{...transition},children:jsxRuntimeExports.jsx(StatusIcon,{children:jsxRuntimeExports.jsx(TickIcon,{})})},"tickIcon"),jsxRuntimeExports.jsx(motion.div,{initial:ot?!1:{opacity:0,x:-40,scale:.8},animate:{opacity:1,x:0,scale:1},transition:{...transition},children:jsxRuntimeExports.jsx(LogoContainer,{children:mt?jsxRuntimeExports.jsx(LazyImage,{src:mt,alt:"app"}):jsxRuntimeExports.jsx(Chains.UnknownChain,{})})},"appLogo")]},"status"),jsxRuntimeExports.jsx(AnimatePresence,{exitBeforeEnter:!0,children:jsxRuntimeExports.jsx(motion.div,{style:{paddingBottom:ot?24:12},initial:ot?!1:{opacity:0,scale:.94},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.94},transition:copyTransition,children:jsxRuntimeExports.jsx(ModalBody,{style:{height:42,marginTop:-1,marginBottom:-3},children:jsxRuntimeExports.jsx(FitText,{children:ct.p})})},flattenChildren(ct.p).toString())}),jsxRuntimeExports.jsx(SIWEButton,{showSignOutButton:it==="signedIn",onSignIn:()=>{setTimeout(()=>{tt.setOpen(!1)},1e3)}})]})})},customThemeDefault$1={},ConnectModal$1=({mode:et="auto",theme:o="auto",customTheme:tt=customThemeDefault$1,lang:rt="en-US"})=>{var nt;const ot=useContext(),{isConnected:it,chain:st}=useAccount(),at=useChainIsSupported(st==null?void 0:st.id),ct=!(!((nt=ot.options)===null||nt===void 0)&&nt.enforceSupportedChains&&it&&!at),lt=ct&&ot.route!==routes.CONNECTORS&&ot.route!==routes.PROFILE,dt=ct&&ot.route!==routes.PROFILE,ht=()=>{ot.route===routes.SIGNINWITHETHEREUM||ot.route===routes.SWITCHNETWORKS?ot.setRoute(routes.PROFILE):ot.route===routes.DOWNLOAD?ot.setRoute(routes.CONNECT):ot.setRoute(routes.CONNECTORS)},mt={onboarding:jsxRuntimeExports.jsx(Introduction,{}),about:jsxRuntimeExports.jsx(About,{}),download:jsxRuntimeExports.jsx(DownloadApp,{}),connectors:jsxRuntimeExports.jsx(Wallets,{}),mobileConnectors:jsxRuntimeExports.jsx(MobileConnectors,{}),connect:jsxRuntimeExports.jsx(ConnectUsing,{}),profile:jsxRuntimeExports.jsx(Profile,{}),switchNetworks:jsxRuntimeExports.jsx(SwitchNetworks,{}),signInWithEthereum:jsxRuntimeExports.jsx(SignInWithEthereum,{})};function ft(){ot.setOpen(!1)}return reactExports.useEffect(()=>{var pt;it?(ot.route!==routes.PROFILE||ot.route!==routes.SIGNINWITHETHEREUM)&&(ot.signInWithEthereum&&!(!((pt=ot.options)===null||pt===void 0)&&pt.disableSiweRedirect)?ot.setRoute(routes.SIGNINWITHETHEREUM):ft()):ft()},[it]),reactExports.useEffect(()=>ot.setMode(et),[et]),reactExports.useEffect(()=>ot.setTheme(o),[o]),reactExports.useEffect(()=>ot.setCustomTheme(tt),[tt]),reactExports.useEffect(()=>ot.setLang(rt),[rt]),reactExports.useEffect(()=>{const pt=getAppName();if(!pt||!ot.open)return;const gt=document.createElement("meta");return gt.setAttribute("property","og:title"),gt.setAttribute("content",pt),document.head.prepend(gt),()=>{document.head.removeChild(gt)}},[ot.open]),jsxRuntimeExports.jsx(ConnectKitThemeProvider,{theme:o,customTheme:tt,mode:et,children:jsxRuntimeExports.jsx(Modal,{open:ot.open,pages:mt,pageId:ot.route,onClose:ct?ft:void 0,onInfo:dt?()=>ot.setRoute(routes.ABOUT):void 0,onBack:lt?ht:void 0})})};function useGoogleFont(et){reactExports.useEffect(()=>{if(!et)return;et=et.replace(/ /g,"+");const o=document.createElement("link");o.href="https://fonts.googleapis.com",o.rel="preconnect";const tt=document.createElement("link");tt.href="https://fonts.gstatic.com",tt.rel="preconnect",tt.crossOrigin="true";const rt=document.createElement("link");return rt.href=`https://fonts.googleapis.com/css2?family=${et}:wght@400;500;600&display=swap`,rt.rel="stylesheet",document.head.appendChild(o),document.head.appendChild(tt),document.head.appendChild(rt),()=>{document.head.removeChild(o),document.head.removeChild(tt),document.head.removeChild(rt)}},[et])}function useThemeFont(et){var o;const rt=(o={web95:"Lato",retro:"Nunito",midnight:"Inter",minimal:"Inter",rounded:"Nunito"}[et])!==null&&o!==void 0?o:null;useGoogleFont(rt??"")}const useConnectCallback=({onConnect:et,onDisconnect:o})=>{useAccountEffect({onConnect:({address:tt,connector:rt,isReconnected:nt})=>{nt||et==null||et({address:tt,connectorId:rt==null?void 0:rt.id})},onDisconnect:()=>o==null?void 0:o()})},routes={ONBOARDING:"onboarding",ABOUT:"about",CONNECTORS:"connectors",MOBILECONNECTORS:"mobileConnectors",CONNECT:"connect",DOWNLOAD:"download",PROFILE:"profile",SWITCHNETWORKS:"switchNetworks",SIGNINWITHETHEREUM:"signInWithEthereum"},Context=reactExports.createContext(null),ConnectKitProvider=({children:et,theme:o="auto",mode:tt="auto",customTheme:rt,options:nt,onConnect:ot,onDisconnect:it,debugMode:st=!1})=>{var at,ct,lt,dt;if(!React.useContext(WagmiContext))throw Error("ConnectKitProvider must be within a WagmiProvider");if(React.useContext(Context))throw new Error("Multiple, nested usages of ConnectKitProvider detected. Please use only one.");useConnectCallback({onConnect:ot,onDisconnect:it});const ht=useChains(),mt=useConnector("injected"),ft={language:"en-US",hideBalance:!1,hideTooltips:!1,hideQuestionMarkCTA:!1,hideNoWalletCTA:!1,walletConnectCTA:"link",hideRecentBadge:!1,avoidLayoutShift:!0,embedGoogleFonts:!1,truncateLongENSAddress:!0,walletConnectName:void 0,reducedMotion:!1,disclaimer:null,bufferPolyfill:!0,customAvatar:void 0,initialChainId:(at=ht==null?void 0:ht[0])===null||at===void 0?void 0:at.id,enforceSupportedChains:!1,ethereumOnboardingUrl:void 0,walletOnboardingUrl:void 0,disableSiweRedirect:!1},pt=Object.assign({},ft,nt);typeof window<"u"&&pt.bufferPolyfill&&(window.Buffer=(ct=window.Buffer)!==null&&ct!==void 0?ct:buffer.Buffer);const[gt,yt]=reactExports.useState(o),[bt,xt]=reactExports.useState(tt),[vt,Et]=reactExports.useState(rt??{}),[Ct,St]=reactExports.useState("en-US"),[At,kt]=reactExports.useState(!1),[It,Ot]=reactExports.useState({id:""}),[Nt,Yt]=reactExports.useState(routes.CONNECTORS),[Ft,Ht]=reactExports.useState(""),[Qt,Vt]=reactExports.useState(0);pt.embedGoogleFonts&&useThemeFont(o),reactExports.useEffect(()=>yt(o),[o]),reactExports.useEffect(()=>St(pt.language||"en-US"),[pt.language]),reactExports.useEffect(()=>Ht(null),[Nt,At]);const{chain:Bt,isConnected:Wt}=useAccount(),jt=useChainIsSupported(Bt==null?void 0:Bt.id);reactExports.useEffect(()=>{Wt&&pt.enforceSupportedChains&&!jt&&(kt(!0),Yt(routes.SWITCHNETWORKS))},[Wt,jt,Bt,Nt,At]),reactExports.useEffect(()=>{isFamily()&&(mt==null||mt.connect())},[mt]);const Xt=st?console.log:()=>{},Kt={theme:gt,setTheme:yt,mode:bt,setMode:xt,customTheme:rt,setCustomTheme:Et,lang:Ct,setLang:St,open:At,setOpen:kt,route:Nt,setRoute:Yt,connector:It,setConnector:Ot,signInWithEthereum:(dt=(lt=React.useContext(SIWEContext))===null||lt===void 0?void 0:lt.enabled)!==null&&dt!==void 0?dt:!1,onConnect:ot,options:pt,errorMessage:Ft,debugMode:st,log:Xt,displayError:(Pt,Gt)=>{Ht(Pt),console.log("---------CONNECTKIT DEBUG---------"),console.log(Pt),Gt&&console.table(Gt),console.log("---------/CONNECTKIT DEBUG---------")},resize:Qt,triggerResize:()=>Vt(Pt=>Pt+1)};return reactExports.createElement(Context.Provider,{value:Kt},jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsx(Web3ContextProvider,{enabled:At,children:jsxRuntimeExports.jsxs(Le,{theme:defaultTheme$1,children:[et,jsxRuntimeExports.jsx(ConnectModal$1,{lang:Ct,theme:gt,mode:tt,customTheme:vt})]})})}))},useContext=()=>{const et=React.useContext(Context);if(!et)throw Error("ConnectKit Hook must be inside a Provider.");return et},safeRoutes={disconnected:[routes.CONNECTORS,routes.ABOUT,routes.ONBOARDING,routes.MOBILECONNECTORS,routes.ONBOARDING],connected:[routes.PROFILE,routes.SWITCHNETWORKS,routes.SIGNINWITHETHEREUM]},allRoutes=[...safeRoutes.connected,...safeRoutes.disconnected],useModal=({onConnect:et,onDisconnect:o}={})=>{const tt=useContext();useConnectCallback({onConnect:et,onDisconnect:o});const{isConnected:rt}=useAccount(),{signIn:nt}=useSIWE(),ot=()=>{tt.setOpen(!1)},it=()=>{tt.setOpen(!0)},st=at=>{let ct=at;allRoutes.includes(at)?rt?safeRoutes.connected.includes(at)||(ct=routes.PROFILE,tt.log(`Route ${at} is not a valid route when connected, navigating to ${ct} instead.`)):safeRoutes.disconnected.includes(at)||(ct=routes.CONNECTORS,tt.log(`Route ${at} is not a valid route when disconnected, navigating to ${ct} instead.`)):(ct=rt?routes.PROFILE:routes.CONNECTORS,tt.log(`Route ${at} is not a valid route, navigating to ${ct} instead.`)),tt.setRoute(ct),it()};return{open:tt.open,setOpen:at=>{at?st(rt?routes.PROFILE:routes.CONNECTORS):ot()},openAbout:()=>st(routes.ABOUT),openOnboarding:()=>st(routes.ONBOARDING),openProfile:()=>st(routes.PROFILE),openSwitchNetworks:()=>st(routes.SWITCHNETWORKS),openSIWE:at=>{st(routes.SIGNINWITHETHEREUM),at&&nt()}}},TextContainer=styled(motion.div)` + top: 0; + bottom: 0; + left: 0; + display: inline-flex; + align-items: center; + justify-content: center; + white-space: nowrap; +`;styled(motion.div)` + position: relative; + width: 24px; + height: 24px; + border-radius: 12px; + overflow: hidden; + svg { + display: block; + } +`;const IconContainer=styled(motion.div)` + pointer-events: none; + user-select: none; + position: relative; + width: 24px; + height: 24px; + margin-right: 8px; +`,UnsupportedNetworkContainer=styled(motion.div)` + z-index: 1; + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + border-radius: 100%; + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.02); + background: var(--ck-body-color-danger, red); + color: #fff; + svg { + display: block; + position: relative; + top: -1px; + } +`,Container$2=styled(motion.div)` + display: flex; + align-items: center; + justify-content: flex-start; + position: relative; + height: 40px; + padding: 0; + line-height: 0; + letter-spacing: -0.2px; + font-size: var(--ck-connectbutton-font-size, 16px); + font-weight: var(--ck-connectbutton-font-weight, 500); + text-align: center; + transition: 100ms ease; + transition-property: color, background, box-shadow, border-radius; + + color: var(--color); + background: var(--background); + box-shadow: var(--box-shadow); + border-radius: var(--border-radius); + + &.primary { + --color: var(--ck-connectbutton-color); + --background: var(--ck-connectbutton-background); + --box-shadow: var(--ck-connectbutton-box-shadow); + --border-radius: var(--ck-connectbutton-border-radius, 12px); + + --hover-color: var(--ck-connectbutton-hover-color, var(--color)); + --hover-background: var( + --ck-connectbutton-hover-background, + var(--background) + ); + --hover-box-shadow: var( + --ck-connectbutton-hover-box-shadow, + var(--box-shadow) + ); + --hover-border-radius: var( + --ck-connectbutton-hover-border-radius, + var(--border-radius) + ); + + --active-color: var(--ck-connectbutton-active-color, var(--hover-color)); + --active-background: var( + --ck-connectbutton-active-background, + var(--hover-background) + ); + --active-box-shadow: var( + --ck-connectbutton-active-box-shadow, + var(--hover-box-shadow) + ); + --active-border-radius: var( + --ck-connectbutton-active-border-radius, + var(--hover-border-radius) + ); + } + &.secondary { + --color: var(--ck-connectbutton-balance-color); + --background: var(--ck-connectbutton-balance-background); + --box-shadow: var(--ck-connectbutton-balance-box-shadow); + --border-radius: var( + --ck-connectbutton-balance-border-radius, + var(--ck-connectbutton-border-radius, 12px) + ); + + --hover-color: var(--ck-connectbutton-balance-hover-color, var(--color)); + --hover-background: var( + --ck-connectbutton-balance-hover-background, + var(--background) + ); + --hover-box-shadow: var( + --ck-connectbutton-balance-hover-box-shadow, + var(--box-shadow) + ); + --hover-border-radius: var( + --ck-connectbutton-balance-hover-border-radius, + var(--border-radius) + ); + + --active-color: var( + --ck-connectbutton-balance-active-color, + var(--hover-color) + ); + --active-background: var( + --ck-connectbutton-balance-active-background, + var(--hover-background) + ); + --active-box-shadow: var( + --ck-connectbutton-balance-active-box-shadow, + var(--hover-box-shadow) + ); + --active-border-radius: var( + --ck-connectbutton-balance-active-border-radius, + var(--hover-border-radius) + ); + } +`,ThemeContainer=styled.button` + all: initial; + appearance: none; + user-select: none; + position: relative; + padding: 0; + margin: 0; + background: none; + border-radius: var(--ck-border-radius); + + &:disabled { + pointer-events: none; + opacity: 0.3; + } + + display: flex; + flex-wrap: nowrap; + background: none; + cursor: pointer; + * { + cursor: pointer; + } + &:hover { + ${Container$2} { + color: var(--hover-color, var(--color)); + background: var(--hover-background, var(--background)); + box-shadow: var(--hover-box-shadow, var(--box-shadow)); + border-radius: var(--hover-border-radius, var(--border-radius)); + } + } + &:active { + ${Container$2} { + color: var(--active-color, var(--hover-color, var(--color))); + background: var( + --active-background, + var(--hover-background, var(--background)) + ); + box-shadow: var( + --active-box-shadow, + var(--hover-box-shadow, var(--box-shadow)) + ); + border-radius: var( + --active-border-radius, + var(--hover-border-radius, var(--border-radius)) + ); + } + } + &:focus-visible { + outline: 2px solid var(--ck-family-brand); + } +`,ThemedButton=({children:et,variant:o="primary",autoSize:tt=!0,duration:rt=.3,style:nt})=>{const[ot,it]=useMeasure();return jsxRuntimeExports.jsx(Container$2,{className:o,initial:!1,animate:tt?{width:it.width>10?it.width:"auto"}:void 0,transition:{duration:rt,ease:[.25,1,.5,1],delay:.01},style:nt,children:jsxRuntimeExports.jsx("div",{ref:ot,style:{whiteSpace:"nowrap",width:"fit-content",position:"relative",padding:"0 12px"},children:et})})},Container$1=styled(motion.div)` + display: flex; + align-items: center; + justify-content: center; + gap: 8px; +`,PlaceholderKeyframes=We` + 0%,100%{ opacity: 0.1; transform: scale(0.75); } + 50%{ opacity: 0.75; transform: scale(1.2) } +`,PulseContainer=styled.div` + pointer-events: none; + user-select: none; + padding: 0 5px; + span { + display: inline-block; + vertical-align: middle; + margin: 0 2px; + width: 3px; + height: 3px; + border-radius: 4px; + background: currentColor; + animation: ${PlaceholderKeyframes} 1000ms ease infinite both; + } +`,Balance=({hideIcon:et,hideSymbol:o})=>{const tt=useIsMounted(),[rt,nt]=reactExports.useState(!0),{address:ot,chain:it}=useAccount();useChains();const st=useChainIsSupported(it==null?void 0:it.id),at=useQueryClient(),{data:ct}=useBlockNumber({watch:!0}),{data:lt,queryKey:dt}=useBalance({address:ot,chainId:it==null?void 0:it.id});reactExports.useEffect(()=>{(ct??0%5===0)&&at.invalidateQueries({queryKey:dt})},[ct,dt]);const ht=chainConfigs.find(ft=>ft.id===(it==null?void 0:it.id)),mt=`${!tt||(lt==null?void 0:lt.formatted)===void 0?"balance-loading":`balance-${ht==null?void 0:ht.id}-${lt==null?void 0:lt.formatted}`}`;return reactExports.useEffect(()=>{nt(!1)},[]),jsxRuntimeExports.jsx("div",{style:{position:"relative"},children:jsxRuntimeExports.jsx(AnimatePresence,{initial:!1,children:jsxRuntimeExports.jsx(motion.div,{initial:(lt==null?void 0:lt.formatted)!==void 0&&rt?{opacity:1}:{opacity:0,position:"absolute",top:0,left:0,bottom:0},animate:{opacity:1,position:"relative"},exit:{opacity:0,position:"absolute",top:0,left:0,bottom:0},transition:{duration:.4,ease:[.25,1,.5,1],delay:.4},children:!ot||!tt||(lt==null?void 0:lt.formatted)===void 0?jsxRuntimeExports.jsxs(Container$1,{children:[!et&&jsxRuntimeExports.jsx(Chain,{id:it==null?void 0:it.id}),jsxRuntimeExports.jsx("span",{style:{minWidth:32},children:jsxRuntimeExports.jsxs(PulseContainer,{children:[jsxRuntimeExports.jsx("span",{style:{animationDelay:"0ms"}}),jsxRuntimeExports.jsx("span",{style:{animationDelay:"50ms"}}),jsxRuntimeExports.jsx("span",{style:{animationDelay:"100ms"}})]})})]}):st?jsxRuntimeExports.jsxs(Container$1,{children:[!et&&jsxRuntimeExports.jsx(Chain,{id:it==null?void 0:it.id}),jsxRuntimeExports.jsx("span",{style:{minWidth:32},children:nFormatter(Number(lt==null?void 0:lt.formatted))}),!o&&` ${lt==null?void 0:lt.symbol}`]}):jsxRuntimeExports.jsxs(Container$1,{children:[!et&&jsxRuntimeExports.jsx(Chain,{id:it==null?void 0:it.id}),jsxRuntimeExports.jsx("span",{style:{minWidth:32},children:"???"})]})},mt)})})},contentVariants={initial:{zIndex:2,opacity:0,x:"-100%"},animate:{opacity:1,x:.1,transition:{duration:.4,ease:[.25,1,.5,1]}},exit:{zIndex:1,opacity:0,x:"-100%",pointerEvents:"none",position:"absolute",transition:{duration:.4,ease:[.25,1,.5,1]}}},addressVariants={initial:{zIndex:2,opacity:0,x:"100%"},animate:{x:.2,opacity:1,transition:{duration:.4,ease:[.25,1,.5,1]}},exit:{zIndex:1,x:"100%",opacity:0,pointerEvents:"none",position:"absolute",transition:{duration:.4,ease:[.25,1,.5,1]}}},textVariants={initial:{opacity:0},animate:{opacity:1,transition:{duration:.3,ease:[.25,1,.5,1]}},exit:{position:"absolute",opacity:0,transition:{duration:.3,ease:[.25,1,.5,1]}}},ConnectButtonRenderer=({children:et})=>{const o=useIsMounted(),tt=useContext(),{open:rt,setOpen:nt}=useModal(),{address:ot,isConnected:it,chain:st}=useAccount(),at=useChainIsSupported(st==null?void 0:st.id),ct=useEnsFallbackConfig(),{data:lt}=useEnsName({chainId:1,address:ot,config:ct});function dt(){nt(!1)}function ht(){nt(!0),tt.setRoute(it?routes.PROFILE:routes.CONNECTORS)}return!et||!o?null:jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:et({show:ht,hide:dt,chain:st,unsupported:!at,isConnected:!!ot,isConnecting:rt,address:ot,truncatedAddress:ot?truncateEthAddress(ot):void 0,ensName:lt==null?void 0:lt.toString()})})};ConnectButtonRenderer.displayName="ConnectKitButton.Custom";function ConnectKitButtonInner({label:et,showAvatar:o,separator:tt}){var rt;const nt=useLocales({}),ot=useContext(),{isSignedIn:it}=useSIWE(),{address:st,chain:at}=useAccount(),ct=useChainIsSupported(at==null?void 0:at.id),lt=useEnsFallbackConfig(),{data:dt}=useEnsName({chainId:1,address:st,config:lt}),ht=nt.connectWallet;return jsxRuntimeExports.jsx(AnimatePresence,{initial:!1,children:st?jsxRuntimeExports.jsxs(TextContainer,{initial:"initial",animate:"animate",exit:"exit",variants:addressVariants,style:{height:40},children:[o&&jsxRuntimeExports.jsxs(IconContainer,{children:[jsxRuntimeExports.jsxs(AnimatePresence,{initial:!1,children:[it&&jsxRuntimeExports.jsx(motion.div,{style:{zIndex:2,position:"absolute",bottom:0,right:0},initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:jsxRuntimeExports.jsx(AuthIcon,{})}),!ct&&jsxRuntimeExports.jsx(UnsupportedNetworkContainer,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:jsxRuntimeExports.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntimeExports.jsx("path",{d:"M1.68831 13.5H12.0764C13.1026 13.5 13.7647 12.7197 13.7647 11.763C13.7647 11.4781 13.6985 11.1863 13.5462 10.9149L8.34225 1.37526C8.02445 0.791754 7.45505 0.5 6.88566 0.5C6.31627 0.5 5.73364 0.791754 5.42246 1.37526L0.225108 10.9217C0.0728291 11.1863 0 11.4781 0 11.763C0 12.7197 0.662083 13.5 1.68831 13.5ZM6.88566 8.8048C6.49503 8.8048 6.27655 8.5809 6.26331 8.1738L6.16399 5.0595C6.15075 4.64562 6.44869 4.34708 6.87904 4.34708C7.30278 4.34708 7.61396 4.6524 7.60071 5.06628L7.5014 8.16701C7.48154 8.5809 7.26305 8.8048 6.88566 8.8048ZM6.88566 11.3492C6.44207 11.3492 6.07792 11.0303 6.07792 10.5757C6.07792 10.1211 6.44207 9.80219 6.88566 9.80219C7.32926 9.80219 7.69341 10.1143 7.69341 10.5757C7.69341 11.0371 7.32264 11.3492 6.88566 11.3492Z",fill:"currentColor"})})})]}),jsxRuntimeExports.jsx(Avatar,{size:24,address:st})]}),jsxRuntimeExports.jsx("div",{style:{position:"relative",paddingRight:o?1:0},children:jsxRuntimeExports.jsx(AnimatePresence,{initial:!1,children:dt?jsxRuntimeExports.jsx(TextContainer,{initial:"initial",animate:"animate",exit:"exit",variants:textVariants,style:{position:dt?"relative":"absolute"},children:!((rt=ot.options)===null||rt===void 0)&&rt.truncateLongENSAddress?truncateENSAddress(dt,20):dt},"ckEnsName"):jsxRuntimeExports.jsxs(TextContainer,{initial:"initial",animate:"animate",exit:"exit",variants:textVariants,style:{position:dt?"absolute":"relative"},children:[truncateEthAddress(st,tt)," "]},"ckTruncatedAddress")})})]},"connectedText"):jsxRuntimeExports.jsx(TextContainer,{initial:"initial",animate:"animate",exit:"exit",variants:contentVariants,style:{height:40},children:et||ht},"connectWalletText")})}function ConnectKitButton({label:et,showBalance:o=!1,showAvatar:tt=!0,theme:rt,mode:nt,customTheme:ot,onClick:it}){var st;const at=useIsMounted(),ct=useContext(),{isConnected:lt,address:dt,chain:ht}=useAccount(),mt=useChainIsSupported(ht==null?void 0:ht.id);function ft(){ct.setOpen(!0),ct.setRoute(lt?routes.PROFILE:routes.CONNECTORS)}const pt=["web95","rounded","minimal"].includes((st=rt??ct.theme)!==null&&st!==void 0?st:"")?"....":void 0;if(!at)return null;const gt=o&&mt,yt=dt&>return jsxRuntimeExports.jsx(ResetContainer,{$useTheme:rt??ct.theme,$useMode:nt??ct.mode,$customTheme:ot??ct.customTheme,children:jsxRuntimeExports.jsxs(ThemeContainer,{onClick:()=>{it?it(ft):ft()},children:[gt&&jsxRuntimeExports.jsx(AnimatePresence,{initial:!1,children:yt&&jsxRuntimeExports.jsx(motion.div,{initial:{opacity:0,x:"100%",width:0,marginRight:0},animate:{opacity:1,x:0,width:"auto",marginRight:-24,transition:{duration:.4,ease:[.25,1,.5,1]}},exit:{opacity:0,x:"100%",width:0,marginRight:0,transition:{duration:.4,ease:[.25,1,.5,1]}},children:jsxRuntimeExports.jsx(ThemedButton,{variant:"secondary",theme:rt??ct.theme,mode:nt??ct.mode,customTheme:ot??ct.customTheme,style:{overflow:"hidden"},children:jsxRuntimeExports.jsx(motion.div,{style:{paddingRight:24},children:jsxRuntimeExports.jsx(Balance,{hideSymbol:!0})})})},"balance")}),jsxRuntimeExports.jsx(ThemedButton,{theme:rt??ct.theme,mode:nt??ct.mode,customTheme:ot??ct.customTheme,style:gt&&o&&dt&&(rt==="retro"||ct.theme==="retro")?{boxShadow:"var(--ck-connectbutton-balance-connectbutton-box-shadow)",borderRadius:"var(--ck-connectbutton-balance-connectbutton-border-radius)",overflow:"hidden"}:{overflow:"hidden"},children:jsxRuntimeExports.jsx(ConnectKitButtonInner,{separator:pt,showAvatar:tt,label:et})})]})})}ConnectKitButton.Custom=ConnectButtonRenderer;const dist=8,shake=We` + 0%{ transform:none; } + 25%{ transform:translateX(${dist}px); } + 50%{ transform:translateX(-${dist}px); } + 75%{ transform:translateX(${dist}px); } + 100%{ transform:none; } +`,cursorIn=We` + 0%{ transform:translate(500%,100%); opacity:0; } + 60%{ transform:translate(25%,-20%); opacity:1; } + 70%{ transform:translate(25%,-20%); } + 85%{ transform:translate(25%,-20%) scale(0.9); } + 100%{ transform:translate(25%,-20%) scale(1); opacity:1; } +`;styled.div` + z-index: 2; + position: absolute; + top: 50%; + left: 50%; + width: 32px; + height: 32px; + border-radius: 50%; + background: rgba(0, 0, 0, 0.5); + box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.4), 0 4px 6px rgba(0, 0, 0, 0.1); + opacity: 0; + &.play { + animation: ${cursorIn} 1300ms 200ms cubic-bezier(0.16, 1, 0.6, 1) both; + } +`;styled.div` + z-index: 1; + position: absolute; + inset: 0; + &.shake { + animation: ${shake} 300ms 100ms cubic-bezier(0.16, 1, 0.6, 1) both; + } +`;styled.div` + z-index: 1; + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + &:before { + z-index: 9; + content: ''; + position: absolute; + inset: 0; + } +`;const CONNECTKIT_VERSION="1.8.2";/** + * @remix-run/router v1.20.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function _extends$2(){return _extends$2=Object.assign?Object.assign.bind():function(et){for(var o=1;o"u")throw new Error(o)}function warning(et,o){if(!et){typeof console<"u"&&console.warn(o);try{throw new Error(o)}catch{}}}function createKey(){return Math.random().toString(36).substr(2,8)}function getHistoryState(et,o){return{usr:et.state,key:et.key,idx:o}}function createLocation(et,o,tt,rt){return tt===void 0&&(tt=null),_extends$2({pathname:typeof et=="string"?et:et.pathname,search:"",hash:""},typeof o=="string"?parsePath(o):o,{state:tt,key:o&&o.key||rt||createKey()})}function createPath(et){let{pathname:o="/",search:tt="",hash:rt=""}=et;return tt&&tt!=="?"&&(o+=tt.charAt(0)==="?"?tt:"?"+tt),rt&&rt!=="#"&&(o+=rt.charAt(0)==="#"?rt:"#"+rt),o}function parsePath(et){let o={};if(et){let tt=et.indexOf("#");tt>=0&&(o.hash=et.substr(tt),et=et.substr(0,tt));let rt=et.indexOf("?");rt>=0&&(o.search=et.substr(rt),et=et.substr(0,rt)),et&&(o.pathname=et)}return o}function getUrlBasedHistory(et,o,tt,rt){rt===void 0&&(rt={});let{window:nt=document.defaultView,v5Compat:ot=!1}=rt,it=nt.history,st=Action.Pop,at=null,ct=lt();ct==null&&(ct=0,it.replaceState(_extends$2({},it.state,{idx:ct}),""));function lt(){return(it.state||{idx:null}).idx}function dt(){st=Action.Pop;let gt=lt(),yt=gt==null?null:gt-ct;ct=gt,at&&at({action:st,location:pt.location,delta:yt})}function ht(gt,yt){st=Action.Push;let bt=createLocation(pt.location,gt,yt);ct=lt()+1;let xt=getHistoryState(bt,ct),vt=pt.createHref(bt);try{it.pushState(xt,"",vt)}catch(Et){if(Et instanceof DOMException&&Et.name==="DataCloneError")throw Et;nt.location.assign(vt)}ot&&at&&at({action:st,location:pt.location,delta:1})}function mt(gt,yt){st=Action.Replace;let bt=createLocation(pt.location,gt,yt);ct=lt();let xt=getHistoryState(bt,ct),vt=pt.createHref(bt);it.replaceState(xt,"",vt),ot&&at&&at({action:st,location:pt.location,delta:0})}function ft(gt){let yt=nt.location.origin!=="null"?nt.location.origin:nt.location.href,bt=typeof gt=="string"?gt:createPath(gt);return bt=bt.replace(/ $/,"%20"),invariant(yt,"No window.location.(origin|href) available to create URL for href: "+bt),new URL(bt,yt)}let pt={get action(){return st},get location(){return et(nt,it)},listen(gt){if(at)throw new Error("A history only accepts one active listener");return nt.addEventListener(PopStateEventType,dt),at=gt,()=>{nt.removeEventListener(PopStateEventType,dt),at=null}},createHref(gt){return o(nt,gt)},createURL:ft,encodeLocation(gt){let yt=ft(gt);return{pathname:yt.pathname,search:yt.search,hash:yt.hash}},push:ht,replace:mt,go(gt){return it.go(gt)}};return pt}var ResultType;(function(et){et.data="data",et.deferred="deferred",et.redirect="redirect",et.error="error"})(ResultType||(ResultType={}));function matchRoutes(et,o,tt){return tt===void 0&&(tt="/"),matchRoutesImpl(et,o,tt,!1)}function matchRoutesImpl(et,o,tt,rt){let nt=typeof o=="string"?parsePath(o):o,ot=stripBasename(nt.pathname||"/",tt);if(ot==null)return null;let it=flattenRoutes(et);rankRouteBranches(it);let st=null;for(let at=0;st==null&&at{let at={relativePath:st===void 0?ot.path||"":st,caseSensitive:ot.caseSensitive===!0,childrenIndex:it,route:ot};at.relativePath.startsWith("/")&&(invariant(at.relativePath.startsWith(rt),'Absolute route path "'+at.relativePath+'" nested under path '+('"'+rt+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),at.relativePath=at.relativePath.slice(rt.length));let ct=joinPaths([rt,at.relativePath]),lt=tt.concat(at);ot.children&&ot.children.length>0&&(invariant(ot.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+ct+'".')),flattenRoutes(ot.children,o,lt,ct)),!(ot.path==null&&!ot.index)&&o.push({path:ct,score:computeScore(ct,ot.index),routesMeta:lt})};return et.forEach((ot,it)=>{var st;if(ot.path===""||!((st=ot.path)!=null&&st.includes("?")))nt(ot,it);else for(let at of explodeOptionalSegments(ot.path))nt(ot,it,at)}),o}function explodeOptionalSegments(et){let o=et.split("/");if(o.length===0)return[];let[tt,...rt]=o,nt=tt.endsWith("?"),ot=tt.replace(/\?$/,"");if(rt.length===0)return nt?[ot,""]:[ot];let it=explodeOptionalSegments(rt.join("/")),st=[];return st.push(...it.map(at=>at===""?ot:[ot,at].join("/"))),nt&&st.push(...it),st.map(at=>et.startsWith("/")&&at===""?"/":at)}function rankRouteBranches(et){et.sort((o,tt)=>o.score!==tt.score?tt.score-o.score:compareIndexes(o.routesMeta.map(rt=>rt.childrenIndex),tt.routesMeta.map(rt=>rt.childrenIndex)))}const paramRe=/^:[\w-]+$/,dynamicSegmentValue=3,indexRouteValue=2,emptySegmentValue=1,staticSegmentValue=10,splatPenalty=-2,isSplat=et=>et==="*";function computeScore(et,o){let tt=et.split("/"),rt=tt.length;return tt.some(isSplat)&&(rt+=splatPenalty),o&&(rt+=indexRouteValue),tt.filter(nt=>!isSplat(nt)).reduce((nt,ot)=>nt+(paramRe.test(ot)?dynamicSegmentValue:ot===""?emptySegmentValue:staticSegmentValue),rt)}function compareIndexes(et,o){return et.length===o.length&&et.slice(0,-1).every((rt,nt)=>rt===o[nt])?et[et.length-1]-o[o.length-1]:0}function matchRouteBranch(et,o,tt){let{routesMeta:rt}=et,nt={},ot="/",it=[];for(let st=0;st{let{paramName:ht,isOptional:mt}=lt;if(ht==="*"){let pt=st[dt]||"";it=ot.slice(0,ot.length-pt.length).replace(/(.)\/+$/,"$1")}const ft=st[dt];return mt&&!ft?ct[ht]=void 0:ct[ht]=(ft||"").replace(/%2F/g,"/"),ct},{}),pathname:ot,pathnameBase:it,pattern:et}}function compilePath(et,o,tt){o===void 0&&(o=!1),tt===void 0&&(tt=!0),warning(et==="*"||!et.endsWith("*")||et.endsWith("/*"),'Route path "'+et+'" will be treated as if it were '+('"'+et.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+et.replace(/\*$/,"/*")+'".'));let rt=[],nt="^"+et.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(it,st,at)=>(rt.push({paramName:st,isOptional:at!=null}),at?"/?([^\\/]+)?":"/([^\\/]+)"));return et.endsWith("*")?(rt.push({paramName:"*"}),nt+=et==="*"||et==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):tt?nt+="\\/*$":et!==""&&et!=="/"&&(nt+="(?:(?=\\/|$))"),[new RegExp(nt,o?void 0:"i"),rt]}function decodePath(et){try{return et.split("/").map(o=>decodeURIComponent(o).replace(/\//g,"%2F")).join("/")}catch(o){return warning(!1,'The URL path "'+et+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+o+").")),et}}function stripBasename(et,o){if(o==="/")return et;if(!et.toLowerCase().startsWith(o.toLowerCase()))return null;let tt=o.endsWith("/")?o.length-1:o.length,rt=et.charAt(tt);return rt&&rt!=="/"?null:et.slice(tt)||"/"}function resolvePath(et,o){o===void 0&&(o="/");let{pathname:tt,search:rt="",hash:nt=""}=typeof et=="string"?parsePath(et):et;return{pathname:tt?tt.startsWith("/")?tt:resolvePathname(tt,o):o,search:normalizeSearch(rt),hash:normalizeHash(nt)}}function resolvePathname(et,o){let tt=o.replace(/\/+$/,"").split("/");return et.split("/").forEach(nt=>{nt===".."?tt.length>1&&tt.pop():nt!=="."&&tt.push(nt)}),tt.length>1?tt.join("/"):"/"}function getInvalidPathError(et,o,tt,rt){return"Cannot include a '"+et+"' character in a manually specified "+("`to."+o+"` field ["+JSON.stringify(rt)+"]. Please separate it out to the ")+("`to."+tt+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function getPathContributingMatches(et){return et.filter((o,tt)=>tt===0||o.route.path&&o.route.path.length>0)}function getResolveToMatches(et,o){let tt=getPathContributingMatches(et);return o?tt.map((rt,nt)=>nt===tt.length-1?rt.pathname:rt.pathnameBase):tt.map(rt=>rt.pathnameBase)}function resolveTo(et,o,tt,rt){rt===void 0&&(rt=!1);let nt;typeof et=="string"?nt=parsePath(et):(nt=_extends$2({},et),invariant(!nt.pathname||!nt.pathname.includes("?"),getInvalidPathError("?","pathname","search",nt)),invariant(!nt.pathname||!nt.pathname.includes("#"),getInvalidPathError("#","pathname","hash",nt)),invariant(!nt.search||!nt.search.includes("#"),getInvalidPathError("#","search","hash",nt)));let ot=et===""||nt.pathname==="",it=ot?"/":nt.pathname,st;if(it==null)st=tt;else{let dt=o.length-1;if(!rt&&it.startsWith("..")){let ht=it.split("/");for(;ht[0]==="..";)ht.shift(),dt-=1;nt.pathname=ht.join("/")}st=dt>=0?o[dt]:"/"}let at=resolvePath(nt,st),ct=it&&it!=="/"&&it.endsWith("/"),lt=(ot||it===".")&&tt.endsWith("/");return!at.pathname.endsWith("/")&&(ct||lt)&&(at.pathname+="/"),at}const joinPaths=et=>et.join("/").replace(/\/\/+/g,"/"),normalizePathname=et=>et.replace(/\/+$/,"").replace(/^\/*/,"/"),normalizeSearch=et=>!et||et==="?"?"":et.startsWith("?")?et:"?"+et,normalizeHash=et=>!et||et==="#"?"":et.startsWith("#")?et:"#"+et;function isRouteErrorResponse(et){return et!=null&&typeof et.status=="number"&&typeof et.statusText=="string"&&typeof et.internal=="boolean"&&"data"in et}const validMutationMethodsArr=["post","put","patch","delete"];new Set(validMutationMethodsArr);const validRequestMethodsArr=["get",...validMutationMethodsArr];new Set(validRequestMethodsArr);/** + * React Router v6.27.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function _extends$1(){return _extends$1=Object.assign?Object.assign.bind():function(et){for(var o=1;o{st.current=!0}),reactExports.useCallback(function(ct,lt){if(lt===void 0&&(lt={}),!st.current)return;if(typeof ct=="number"){rt.go(ct);return}let dt=resolveTo(ct,JSON.parse(it),ot,lt.relative==="path");et==null&&o!=="/"&&(dt.pathname=dt.pathname==="/"?o:joinPaths([o,dt.pathname])),(lt.replace?rt.replace:rt.push)(dt,lt.state,lt)},[o,rt,it,ot,et])}function useParams(){let{matches:et}=reactExports.useContext(RouteContext),o=et[et.length-1];return o?o.params:{}}function useResolvedPath(et,o){let{relative:tt}=o===void 0?{}:o,{future:rt}=reactExports.useContext(NavigationContext),{matches:nt}=reactExports.useContext(RouteContext),{pathname:ot}=useLocation(),it=JSON.stringify(getResolveToMatches(nt,rt.v7_relativeSplatPath));return reactExports.useMemo(()=>resolveTo(et,JSON.parse(it),ot,tt==="path"),[et,it,ot,tt])}function useRoutes(et,o){return useRoutesImpl(et,o)}function useRoutesImpl(et,o,tt,rt){useInRouterContext()||invariant(!1);let{navigator:nt}=reactExports.useContext(NavigationContext),{matches:ot}=reactExports.useContext(RouteContext),it=ot[ot.length-1],st=it?it.params:{};it&&it.pathname;let at=it?it.pathnameBase:"/";it&&it.route;let ct=useLocation(),lt;if(o){var dt;let gt=typeof o=="string"?parsePath(o):o;at==="/"||(dt=gt.pathname)!=null&&dt.startsWith(at)||invariant(!1),lt=gt}else lt=ct;let ht=lt.pathname||"/",mt=ht;if(at!=="/"){let gt=at.replace(/^\//,"").split("/");mt="/"+ht.replace(/^\//,"").split("/").slice(gt.length).join("/")}let ft=matchRoutes(et,{pathname:mt}),pt=_renderMatches(ft&&ft.map(gt=>Object.assign({},gt,{params:Object.assign({},st,gt.params),pathname:joinPaths([at,nt.encodeLocation?nt.encodeLocation(gt.pathname).pathname:gt.pathname]),pathnameBase:gt.pathnameBase==="/"?at:joinPaths([at,nt.encodeLocation?nt.encodeLocation(gt.pathnameBase).pathname:gt.pathnameBase])})),ot,tt,rt);return o&&pt?reactExports.createElement(LocationContext.Provider,{value:{location:_extends$1({pathname:"/",search:"",hash:"",state:null,key:"default"},lt),navigationType:Action.Pop}},pt):pt}function DefaultErrorComponent(){let et=useRouteError(),o=isRouteErrorResponse(et)?et.status+" "+et.statusText:et instanceof Error?et.message:JSON.stringify(et),tt=et instanceof Error?et.stack:null,nt={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},o),tt?reactExports.createElement("pre",{style:nt},tt):null,null)}const defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null);class RenderErrorBoundary extends reactExports.Component{constructor(o){super(o),this.state={location:o.location,revalidation:o.revalidation,error:o.error}}static getDerivedStateFromError(o){return{error:o}}static getDerivedStateFromProps(o,tt){return tt.location!==o.location||tt.revalidation!=="idle"&&o.revalidation==="idle"?{error:o.error,location:o.location,revalidation:o.revalidation}:{error:o.error!==void 0?o.error:tt.error,location:tt.location,revalidation:o.revalidation||tt.revalidation}}componentDidCatch(o,tt){console.error("React Router caught the following error during render",o,tt)}render(){return this.state.error!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function RenderedRoute(et){let{routeContext:o,match:tt,children:rt}=et,nt=reactExports.useContext(DataRouterContext);return nt&&nt.static&&nt.staticContext&&(tt.route.errorElement||tt.route.ErrorBoundary)&&(nt.staticContext._deepestRenderedBoundaryId=tt.route.id),reactExports.createElement(RouteContext.Provider,{value:o},rt)}function _renderMatches(et,o,tt,rt){var nt;if(o===void 0&&(o=[]),tt===void 0&&(tt=null),rt===void 0&&(rt=null),et==null){var ot;if(!tt)return null;if(tt.errors)et=tt.matches;else if((ot=rt)!=null&&ot.v7_partialHydration&&o.length===0&&!tt.initialized&&tt.matches.length>0)et=tt.matches;else return null}let it=et,st=(nt=tt)==null?void 0:nt.errors;if(st!=null){let lt=it.findIndex(dt=>dt.route.id&&(st==null?void 0:st[dt.route.id])!==void 0);lt>=0||invariant(!1),it=it.slice(0,Math.min(it.length,lt+1))}let at=!1,ct=-1;if(tt&&rt&&rt.v7_partialHydration)for(let lt=0;lt=0?it=it.slice(0,ct+1):it=[it[0]];break}}}return it.reduceRight((lt,dt,ht)=>{let mt,ft=!1,pt=null,gt=null;tt&&(mt=st&&dt.route.id?st[dt.route.id]:void 0,pt=dt.route.errorElement||defaultErrorElement,at&&(ct<0&&ht===0?(ft=!0,gt=null):ct===ht&&(ft=!0,gt=dt.route.hydrateFallbackElement||null)));let yt=o.concat(it.slice(0,ht+1)),bt=()=>{let xt;return mt?xt=pt:ft?xt=gt:dt.route.Component?xt=reactExports.createElement(dt.route.Component,null):dt.route.element?xt=dt.route.element:xt=lt,reactExports.createElement(RenderedRoute,{match:dt,routeContext:{outlet:lt,matches:yt,isDataRoute:tt!=null},children:xt})};return tt&&(dt.route.ErrorBoundary||dt.route.errorElement||ht===0)?reactExports.createElement(RenderErrorBoundary,{location:tt.location,revalidation:tt.revalidation,component:pt,error:mt,children:bt(),routeContext:{outlet:null,matches:yt,isDataRoute:!0}}):bt()},null)}var DataRouterHook$1=function(et){return et.UseBlocker="useBlocker",et.UseRevalidator="useRevalidator",et.UseNavigateStable="useNavigate",et}(DataRouterHook$1||{}),DataRouterStateHook$1=function(et){return et.UseBlocker="useBlocker",et.UseLoaderData="useLoaderData",et.UseActionData="useActionData",et.UseRouteError="useRouteError",et.UseNavigation="useNavigation",et.UseRouteLoaderData="useRouteLoaderData",et.UseMatches="useMatches",et.UseRevalidator="useRevalidator",et.UseNavigateStable="useNavigate",et.UseRouteId="useRouteId",et}(DataRouterStateHook$1||{});function useDataRouterContext(et){let o=reactExports.useContext(DataRouterContext);return o||invariant(!1),o}function useDataRouterState(et){let o=reactExports.useContext(DataRouterStateContext);return o||invariant(!1),o}function useRouteContext(et){let o=reactExports.useContext(RouteContext);return o||invariant(!1),o}function useCurrentRouteId(et){let o=useRouteContext(),tt=o.matches[o.matches.length-1];return tt.route.id||invariant(!1),tt.route.id}function useRouteError(){var et;let o=reactExports.useContext(RouteErrorContext),tt=useDataRouterState(DataRouterStateHook$1.UseRouteError),rt=useCurrentRouteId(DataRouterStateHook$1.UseRouteError);return o!==void 0?o:(et=tt.errors)==null?void 0:et[rt]}function useNavigateStable(){let{router:et}=useDataRouterContext(DataRouterHook$1.UseNavigateStable),o=useCurrentRouteId(DataRouterStateHook$1.UseNavigateStable),tt=reactExports.useRef(!1);return useIsomorphicLayoutEffect$1(()=>{tt.current=!0}),reactExports.useCallback(function(nt,ot){ot===void 0&&(ot={}),tt.current&&(typeof nt=="number"?et.navigate(nt):et.navigate(nt,_extends$1({fromRouteId:o},ot)))},[et,o])}function Navigate(et){let{to:o,replace:tt,state:rt,relative:nt}=et;useInRouterContext()||invariant(!1);let{future:ot,static:it}=reactExports.useContext(NavigationContext),{matches:st}=reactExports.useContext(RouteContext),{pathname:at}=useLocation(),ct=useNavigate(),lt=resolveTo(o,getResolveToMatches(st,ot.v7_relativeSplatPath),at,nt==="path"),dt=JSON.stringify(lt);return reactExports.useEffect(()=>ct(JSON.parse(dt),{replace:tt,state:rt,relative:nt}),[ct,dt,nt,tt,rt]),null}function Route(et){invariant(!1)}function Router(et){let{basename:o="/",children:tt=null,location:rt,navigationType:nt=Action.Pop,navigator:ot,static:it=!1,future:st}=et;useInRouterContext()&&invariant(!1);let at=o.replace(/^\/*/,"/"),ct=reactExports.useMemo(()=>({basename:at,navigator:ot,static:it,future:_extends$1({v7_relativeSplatPath:!1},st)}),[at,st,ot,it]);typeof rt=="string"&&(rt=parsePath(rt));let{pathname:lt="/",search:dt="",hash:ht="",state:mt=null,key:ft="default"}=rt,pt=reactExports.useMemo(()=>{let gt=stripBasename(lt,at);return gt==null?null:{location:{pathname:gt,search:dt,hash:ht,state:mt,key:ft},navigationType:nt}},[at,lt,dt,ht,mt,ft,nt]);return pt==null?null:reactExports.createElement(NavigationContext.Provider,{value:ct},reactExports.createElement(LocationContext.Provider,{children:tt,value:pt}))}function Routes(et){let{children:o,location:tt}=et;return useRoutes(createRoutesFromChildren(o),tt)}new Promise(()=>{});function createRoutesFromChildren(et,o){o===void 0&&(o=[]);let tt=[];return reactExports.Children.forEach(et,(rt,nt)=>{if(!reactExports.isValidElement(rt))return;let ot=[...o,nt];if(rt.type===reactExports.Fragment){tt.push.apply(tt,createRoutesFromChildren(rt.props.children,ot));return}rt.type!==Route&&invariant(!1),!rt.props.index||!rt.props.children||invariant(!1);let it={id:rt.props.id||ot.join("-"),caseSensitive:rt.props.caseSensitive,element:rt.props.element,Component:rt.props.Component,index:rt.props.index,path:rt.props.path,loader:rt.props.loader,action:rt.props.action,errorElement:rt.props.errorElement,ErrorBoundary:rt.props.ErrorBoundary,hasErrorBoundary:rt.props.ErrorBoundary!=null||rt.props.errorElement!=null,shouldRevalidate:rt.props.shouldRevalidate,handle:rt.props.handle,lazy:rt.props.lazy};rt.props.children&&(it.children=createRoutesFromChildren(rt.props.children,ot)),tt.push(it)}),tt}/** + * React Router DOM v6.27.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function _extends(){return _extends=Object.assign?Object.assign.bind():function(et){for(var o=1;o=0)&&(tt[nt]=et[nt]);return tt}function isModifiedEvent(et){return!!(et.metaKey||et.altKey||et.ctrlKey||et.shiftKey)}function shouldProcessLinkClick(et,o){return et.button===0&&(!o||o==="_self")&&!isModifiedEvent(et)}const _excluded=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],REACT_ROUTER_VERSION="6";try{window.__reactRouterVersion=REACT_ROUTER_VERSION}catch{}const START_TRANSITION="startTransition",startTransitionImpl=React$1[START_TRANSITION];function BrowserRouter(et){let{basename:o,children:tt,future:rt,window:nt}=et,ot=reactExports.useRef();ot.current==null&&(ot.current=createBrowserHistory({window:nt,v5Compat:!0}));let it=ot.current,[st,at]=reactExports.useState({action:it.action,location:it.location}),{v7_startTransition:ct}=rt||{},lt=reactExports.useCallback(dt=>{ct&&startTransitionImpl?startTransitionImpl(()=>at(dt)):at(dt)},[at,ct]);return reactExports.useLayoutEffect(()=>it.listen(lt),[it,lt]),reactExports.createElement(Router,{basename:o,children:tt,location:st.location,navigationType:st.action,navigator:it,future:rt})}const isBrowser$1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ABSOLUTE_URL_REGEX=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Link=reactExports.forwardRef(function(o,tt){let{onClick:rt,relative:nt,reloadDocument:ot,replace:it,state:st,target:at,to:ct,preventScrollReset:lt,viewTransition:dt}=o,ht=_objectWithoutPropertiesLoose$1(o,_excluded),{basename:mt}=reactExports.useContext(NavigationContext),ft,pt=!1;if(typeof ct=="string"&&ABSOLUTE_URL_REGEX.test(ct)&&(ft=ct,isBrowser$1))try{let xt=new URL(window.location.href),vt=ct.startsWith("//")?new URL(xt.protocol+ct):new URL(ct),Et=stripBasename(vt.pathname,mt);vt.origin===xt.origin&&Et!=null?ct=Et+vt.search+vt.hash:pt=!0}catch{}let gt=useHref(ct,{relative:nt}),yt=useLinkClickHandler(ct,{replace:it,state:st,target:at,preventScrollReset:lt,relative:nt,viewTransition:dt});function bt(xt){rt&&rt(xt),xt.defaultPrevented||yt(xt)}return reactExports.createElement("a",_extends({},ht,{href:ft||gt,onClick:pt||ot?rt:bt,ref:tt,target:at}))});var DataRouterHook;(function(et){et.UseScrollRestoration="useScrollRestoration",et.UseSubmit="useSubmit",et.UseSubmitFetcher="useSubmitFetcher",et.UseFetcher="useFetcher",et.useViewTransitionState="useViewTransitionState"})(DataRouterHook||(DataRouterHook={}));var DataRouterStateHook;(function(et){et.UseFetcher="useFetcher",et.UseFetchers="useFetchers",et.UseScrollRestoration="useScrollRestoration"})(DataRouterStateHook||(DataRouterStateHook={}));function useLinkClickHandler(et,o){let{target:tt,replace:rt,state:nt,preventScrollReset:ot,relative:it,viewTransition:st}=o===void 0?{}:o,at=useNavigate(),ct=useLocation(),lt=useResolvedPath(et,{relative:it});return reactExports.useCallback(dt=>{if(shouldProcessLinkClick(dt,tt)){dt.preventDefault();let ht=rt!==void 0?rt:createPath(ct)===createPath(lt);at(et,{replace:ht,state:nt,preventScrollReset:ot,relative:it,viewTransition:st})}},[ct,at,lt,rt,nt,tt,et,ot,it,st])}function setRef(et,o){typeof et=="function"?et(o):et!=null&&(et.current=o)}function composeRefs(...et){return o=>et.forEach(tt=>setRef(tt,o))}function useComposedRefs(...et){return reactExports.useCallback(composeRefs(...et),et)}var Slot=reactExports.forwardRef((et,o)=>{const{children:tt,...rt}=et,nt=reactExports.Children.toArray(tt),ot=nt.find(isSlottable);if(ot){const it=ot.props.children,st=nt.map(at=>at===ot?reactExports.Children.count(it)>1?reactExports.Children.only(null):reactExports.isValidElement(it)?it.props.children:null:at);return jsxRuntimeExports.jsx(SlotClone,{...rt,ref:o,children:reactExports.isValidElement(it)?reactExports.cloneElement(it,void 0,st):null})}return jsxRuntimeExports.jsx(SlotClone,{...rt,ref:o,children:tt})});Slot.displayName="Slot";var SlotClone=reactExports.forwardRef((et,o)=>{const{children:tt,...rt}=et;if(reactExports.isValidElement(tt)){const nt=getElementRef$1(tt);return reactExports.cloneElement(tt,{...mergeProps(rt,tt.props),ref:o?composeRefs(o,nt):nt})}return reactExports.Children.count(tt)>1?reactExports.Children.only(null):null});SlotClone.displayName="SlotClone";var Slottable=({children:et})=>jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:et});function isSlottable(et){return reactExports.isValidElement(et)&&et.type===Slottable}function mergeProps(et,o){const tt={...o};for(const rt in o){const nt=et[rt],ot=o[rt];/^on[A-Z]/.test(rt)?nt&&ot?tt[rt]=(...st)=>{ot(...st),nt(...st)}:nt&&(tt[rt]=nt):rt==="style"?tt[rt]={...nt,...ot}:rt==="className"&&(tt[rt]=[nt,ot].filter(Boolean).join(" "))}return{...et,...tt}}function getElementRef$1(et){var rt,nt;let o=(rt=Object.getOwnPropertyDescriptor(et.props,"ref"))==null?void 0:rt.get,tt=o&&"isReactWarning"in o&&o.isReactWarning;return tt?et.ref:(o=(nt=Object.getOwnPropertyDescriptor(et,"ref"))==null?void 0:nt.get,tt=o&&"isReactWarning"in o&&o.isReactWarning,tt?et.props.ref:et.props.ref||et.ref)}function r$1(et){var o,tt,rt="";if(typeof et=="string"||typeof et=="number")rt+=et;else if(typeof et=="object")if(Array.isArray(et))for(o=0;otypeof et=="boolean"?"".concat(et):et===0?"0":et,cx=clsx$1,cva=(et,o)=>tt=>{var rt;if((o==null?void 0:o.variants)==null)return cx(et,tt==null?void 0:tt.class,tt==null?void 0:tt.className);const{variants:nt,defaultVariants:ot}=o,it=Object.keys(nt).map(ct=>{const lt=tt==null?void 0:tt[ct],dt=ot==null?void 0:ot[ct];if(lt===null)return null;const ht=falsyToString(lt)||falsyToString(dt);return nt[ct][ht]}),st=tt&&Object.entries(tt).reduce((ct,lt)=>{let[dt,ht]=lt;return ht===void 0||(ct[dt]=ht),ct},{}),at=o==null||(rt=o.compoundVariants)===null||rt===void 0?void 0:rt.reduce((ct,lt)=>{let{class:dt,className:ht,...mt}=lt;return Object.entries(mt).every(ft=>{let[pt,gt]=ft;return Array.isArray(gt)?gt.includes({...ot,...st}[pt]):{...ot,...st}[pt]===gt})?[...ct,dt,ht]:ct},[]);return cx(et,it,at,tt==null?void 0:tt.class,tt==null?void 0:tt.className)};function r(et){var o,tt,rt="";if(typeof et=="string"||typeof et=="number")rt+=et;else if(typeof et=="object")if(Array.isArray(et)){var nt=et.length;for(o=0;o{const o=createClassMap(et),{conflictingClassGroups:tt,conflictingClassGroupModifiers:rt}=et;return{getClassGroupId:it=>{const st=it.split(CLASS_PART_SEPARATOR);return st[0]===""&&st.length!==1&&st.shift(),getGroupRecursive(st,o)||getGroupIdForArbitraryProperty(it)},getConflictingClassGroupIds:(it,st)=>{const at=tt[it]||[];return st&&rt[it]?[...at,...rt[it]]:at}}},getGroupRecursive=(et,o)=>{var it;if(et.length===0)return o.classGroupId;const tt=et[0],rt=o.nextPart.get(tt),nt=rt?getGroupRecursive(et.slice(1),rt):void 0;if(nt)return nt;if(o.validators.length===0)return;const ot=et.join(CLASS_PART_SEPARATOR);return(it=o.validators.find(({validator:st})=>st(ot)))==null?void 0:it.classGroupId},arbitraryPropertyRegex=/^\[(.+)\]$/,getGroupIdForArbitraryProperty=et=>{if(arbitraryPropertyRegex.test(et)){const o=arbitraryPropertyRegex.exec(et)[1],tt=o==null?void 0:o.substring(0,o.indexOf(":"));if(tt)return"arbitrary.."+tt}},createClassMap=et=>{const{theme:o,prefix:tt}=et,rt={nextPart:new Map,validators:[]};return getPrefixedClassGroupEntries(Object.entries(et.classGroups),tt).forEach(([ot,it])=>{processClassesRecursively(it,rt,ot,o)}),rt},processClassesRecursively=(et,o,tt,rt)=>{et.forEach(nt=>{if(typeof nt=="string"){const ot=nt===""?o:getPart(o,nt);ot.classGroupId=tt;return}if(typeof nt=="function"){if(isThemeGetter(nt)){processClassesRecursively(nt(rt),o,tt,rt);return}o.validators.push({validator:nt,classGroupId:tt});return}Object.entries(nt).forEach(([ot,it])=>{processClassesRecursively(it,getPart(o,ot),tt,rt)})})},getPart=(et,o)=>{let tt=et;return o.split(CLASS_PART_SEPARATOR).forEach(rt=>{tt.nextPart.has(rt)||tt.nextPart.set(rt,{nextPart:new Map,validators:[]}),tt=tt.nextPart.get(rt)}),tt},isThemeGetter=et=>et.isThemeGetter,getPrefixedClassGroupEntries=(et,o)=>o?et.map(([tt,rt])=>{const nt=rt.map(ot=>typeof ot=="string"?o+ot:typeof ot=="object"?Object.fromEntries(Object.entries(ot).map(([it,st])=>[o+it,st])):ot);return[tt,nt]}):et,createLruCache=et=>{if(et<1)return{get:()=>{},set:()=>{}};let o=0,tt=new Map,rt=new Map;const nt=(ot,it)=>{tt.set(ot,it),o++,o>et&&(o=0,rt=tt,tt=new Map)};return{get(ot){let it=tt.get(ot);if(it!==void 0)return it;if((it=rt.get(ot))!==void 0)return nt(ot,it),it},set(ot,it){tt.has(ot)?tt.set(ot,it):nt(ot,it)}}},IMPORTANT_MODIFIER="!",createParseClassName=et=>{const{separator:o,experimentalParseClassName:tt}=et,rt=o.length===1,nt=o[0],ot=o.length,it=st=>{const at=[];let ct=0,lt=0,dt;for(let gt=0;gtlt?dt-lt:void 0;return{modifiers:at,hasImportantModifier:mt,baseClassName:ft,maybePostfixModifierPosition:pt}};return tt?st=>tt({className:st,parseClassName:it}):it},sortModifiers=et=>{if(et.length<=1)return et;const o=[];let tt=[];return et.forEach(rt=>{rt[0]==="["?(o.push(...tt.sort(),rt),tt=[]):tt.push(rt)}),o.push(...tt.sort()),o},createConfigUtils=et=>({cache:createLruCache(et.cacheSize),parseClassName:createParseClassName(et),...createClassGroupUtils(et)}),SPLIT_CLASSES_REGEX=/\s+/,mergeClassList=(et,o)=>{const{parseClassName:tt,getClassGroupId:rt,getConflictingClassGroupIds:nt}=o,ot=[],it=et.trim().split(SPLIT_CLASSES_REGEX);let st="";for(let at=it.length-1;at>=0;at-=1){const ct=it[at],{modifiers:lt,hasImportantModifier:dt,baseClassName:ht,maybePostfixModifierPosition:mt}=tt(ct);let ft=!!mt,pt=rt(ft?ht.substring(0,mt):ht);if(!pt){if(!ft){st=ct+(st.length>0?" "+st:st);continue}if(pt=rt(ht),!pt){st=ct+(st.length>0?" "+st:st);continue}ft=!1}const gt=sortModifiers(lt).join(":"),yt=dt?gt+IMPORTANT_MODIFIER:gt,bt=yt+pt;if(ot.includes(bt))continue;ot.push(bt);const xt=nt(pt,ft);for(let vt=0;vt0?" "+st:st)}return st};function twJoin(){let et=0,o,tt,rt="";for(;et{if(typeof et=="string")return et;let o,tt="";for(let rt=0;rtdt(lt),et());return tt=createConfigUtils(ct),rt=tt.cache.get,nt=tt.cache.set,ot=st,st(at)}function st(at){const ct=rt(at);if(ct)return ct;const lt=mergeClassList(at,tt);return nt(at,lt),lt}return function(){return ot(twJoin.apply(null,arguments))}}const fromTheme=et=>{const o=tt=>tt[et]||[];return o.isThemeGetter=!0,o},arbitraryValueRegex=/^\[(?:([a-z-]+):)?(.+)\]$/i,fractionRegex=/^\d+\/\d+$/,stringLengths=new Set(["px","full","screen"]),tshirtUnitRegex=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,lengthUnitRegex=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,colorFunctionRegex=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,shadowRegex=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,imageRegex=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,isLength=et=>isNumber(et)||stringLengths.has(et)||fractionRegex.test(et),isArbitraryLength=et=>getIsArbitraryValue(et,"length",isLengthOnly),isNumber=et=>!!et&&!Number.isNaN(Number(et)),isArbitraryNumber=et=>getIsArbitraryValue(et,"number",isNumber),isInteger$1=et=>!!et&&Number.isInteger(Number(et)),isPercent=et=>et.endsWith("%")&&isNumber(et.slice(0,-1)),isArbitraryValue=et=>arbitraryValueRegex.test(et),isTshirtSize=et=>tshirtUnitRegex.test(et),sizeLabels=new Set(["length","size","percentage"]),isArbitrarySize=et=>getIsArbitraryValue(et,sizeLabels,isNever),isArbitraryPosition=et=>getIsArbitraryValue(et,"position",isNever),imageLabels=new Set(["image","url"]),isArbitraryImage=et=>getIsArbitraryValue(et,imageLabels,isImage),isArbitraryShadow=et=>getIsArbitraryValue(et,"",isShadow),isAny=()=>!0,getIsArbitraryValue=(et,o,tt)=>{const rt=arbitraryValueRegex.exec(et);return rt?rt[1]?typeof o=="string"?rt[1]===o:o.has(rt[1]):tt(rt[2]):!1},isLengthOnly=et=>lengthUnitRegex.test(et)&&!colorFunctionRegex.test(et),isNever=()=>!1,isShadow=et=>shadowRegex.test(et),isImage=et=>imageRegex.test(et),getDefaultConfig=()=>{const et=fromTheme("colors"),o=fromTheme("spacing"),tt=fromTheme("blur"),rt=fromTheme("brightness"),nt=fromTheme("borderColor"),ot=fromTheme("borderRadius"),it=fromTheme("borderSpacing"),st=fromTheme("borderWidth"),at=fromTheme("contrast"),ct=fromTheme("grayscale"),lt=fromTheme("hueRotate"),dt=fromTheme("invert"),ht=fromTheme("gap"),mt=fromTheme("gradientColorStops"),ft=fromTheme("gradientColorStopPositions"),pt=fromTheme("inset"),gt=fromTheme("margin"),yt=fromTheme("opacity"),bt=fromTheme("padding"),xt=fromTheme("saturate"),vt=fromTheme("scale"),Et=fromTheme("sepia"),Ct=fromTheme("skew"),St=fromTheme("space"),At=fromTheme("translate"),kt=()=>["auto","contain","none"],It=()=>["auto","hidden","clip","visible","scroll"],Ot=()=>["auto",isArbitraryValue,o],Nt=()=>[isArbitraryValue,o],Yt=()=>["",isLength,isArbitraryLength],Ft=()=>["auto",isNumber,isArbitraryValue],Ht=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Qt=()=>["solid","dashed","dotted","double","none"],Vt=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Bt=()=>["start","end","center","between","around","evenly","stretch"],Wt=()=>["","0",isArbitraryValue],jt=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Xt=()=>[isNumber,isArbitraryValue];return{cacheSize:500,separator:":",theme:{colors:[isAny],spacing:[isLength,isArbitraryLength],blur:["none","",isTshirtSize,isArbitraryValue],brightness:Xt(),borderColor:[et],borderRadius:["none","","full",isTshirtSize,isArbitraryValue],borderSpacing:Nt(),borderWidth:Yt(),contrast:Xt(),grayscale:Wt(),hueRotate:Xt(),invert:Wt(),gap:Nt(),gradientColorStops:[et],gradientColorStopPositions:[isPercent,isArbitraryLength],inset:Ot(),margin:Ot(),opacity:Xt(),padding:Nt(),saturate:Xt(),scale:Xt(),sepia:Wt(),skew:Xt(),space:Nt(),translate:Nt()},classGroups:{aspect:[{aspect:["auto","square","video",isArbitraryValue]}],container:["container"],columns:[{columns:[isTshirtSize]}],"break-after":[{"break-after":jt()}],"break-before":[{"break-before":jt()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...Ht(),isArbitraryValue]}],overflow:[{overflow:It()}],"overflow-x":[{"overflow-x":It()}],"overflow-y":[{"overflow-y":It()}],overscroll:[{overscroll:kt()}],"overscroll-x":[{"overscroll-x":kt()}],"overscroll-y":[{"overscroll-y":kt()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[pt]}],"inset-x":[{"inset-x":[pt]}],"inset-y":[{"inset-y":[pt]}],start:[{start:[pt]}],end:[{end:[pt]}],top:[{top:[pt]}],right:[{right:[pt]}],bottom:[{bottom:[pt]}],left:[{left:[pt]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",isInteger$1,isArbitraryValue]}],basis:[{basis:Ot()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",isArbitraryValue]}],grow:[{grow:Wt()}],shrink:[{shrink:Wt()}],order:[{order:["first","last","none",isInteger$1,isArbitraryValue]}],"grid-cols":[{"grid-cols":[isAny]}],"col-start-end":[{col:["auto",{span:["full",isInteger$1,isArbitraryValue]},isArbitraryValue]}],"col-start":[{"col-start":Ft()}],"col-end":[{"col-end":Ft()}],"grid-rows":[{"grid-rows":[isAny]}],"row-start-end":[{row:["auto",{span:[isInteger$1,isArbitraryValue]},isArbitraryValue]}],"row-start":[{"row-start":Ft()}],"row-end":[{"row-end":Ft()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",isArbitraryValue]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",isArbitraryValue]}],gap:[{gap:[ht]}],"gap-x":[{"gap-x":[ht]}],"gap-y":[{"gap-y":[ht]}],"justify-content":[{justify:["normal",...Bt()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...Bt(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...Bt(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[bt]}],px:[{px:[bt]}],py:[{py:[bt]}],ps:[{ps:[bt]}],pe:[{pe:[bt]}],pt:[{pt:[bt]}],pr:[{pr:[bt]}],pb:[{pb:[bt]}],pl:[{pl:[bt]}],m:[{m:[gt]}],mx:[{mx:[gt]}],my:[{my:[gt]}],ms:[{ms:[gt]}],me:[{me:[gt]}],mt:[{mt:[gt]}],mr:[{mr:[gt]}],mb:[{mb:[gt]}],ml:[{ml:[gt]}],"space-x":[{"space-x":[St]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[St]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",isArbitraryValue,o]}],"min-w":[{"min-w":[isArbitraryValue,o,"min","max","fit"]}],"max-w":[{"max-w":[isArbitraryValue,o,"none","full","min","max","fit","prose",{screen:[isTshirtSize]},isTshirtSize]}],h:[{h:[isArbitraryValue,o,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[isArbitraryValue,o,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[isArbitraryValue,o,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[isArbitraryValue,o,"auto","min","max","fit"]}],"font-size":[{text:["base",isTshirtSize,isArbitraryLength]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",isArbitraryNumber]}],"font-family":[{font:[isAny]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",isArbitraryValue]}],"line-clamp":[{"line-clamp":["none",isNumber,isArbitraryNumber]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",isLength,isArbitraryValue]}],"list-image":[{"list-image":["none",isArbitraryValue]}],"list-style-type":[{list:["none","disc","decimal",isArbitraryValue]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[et]}],"placeholder-opacity":[{"placeholder-opacity":[yt]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[et]}],"text-opacity":[{"text-opacity":[yt]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Qt(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",isLength,isArbitraryLength]}],"underline-offset":[{"underline-offset":["auto",isLength,isArbitraryValue]}],"text-decoration-color":[{decoration:[et]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:Nt()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",isArbitraryValue]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",isArbitraryValue]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[yt]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Ht(),isArbitraryPosition]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",isArbitrarySize]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},isArbitraryImage]}],"bg-color":[{bg:[et]}],"gradient-from-pos":[{from:[ft]}],"gradient-via-pos":[{via:[ft]}],"gradient-to-pos":[{to:[ft]}],"gradient-from":[{from:[mt]}],"gradient-via":[{via:[mt]}],"gradient-to":[{to:[mt]}],rounded:[{rounded:[ot]}],"rounded-s":[{"rounded-s":[ot]}],"rounded-e":[{"rounded-e":[ot]}],"rounded-t":[{"rounded-t":[ot]}],"rounded-r":[{"rounded-r":[ot]}],"rounded-b":[{"rounded-b":[ot]}],"rounded-l":[{"rounded-l":[ot]}],"rounded-ss":[{"rounded-ss":[ot]}],"rounded-se":[{"rounded-se":[ot]}],"rounded-ee":[{"rounded-ee":[ot]}],"rounded-es":[{"rounded-es":[ot]}],"rounded-tl":[{"rounded-tl":[ot]}],"rounded-tr":[{"rounded-tr":[ot]}],"rounded-br":[{"rounded-br":[ot]}],"rounded-bl":[{"rounded-bl":[ot]}],"border-w":[{border:[st]}],"border-w-x":[{"border-x":[st]}],"border-w-y":[{"border-y":[st]}],"border-w-s":[{"border-s":[st]}],"border-w-e":[{"border-e":[st]}],"border-w-t":[{"border-t":[st]}],"border-w-r":[{"border-r":[st]}],"border-w-b":[{"border-b":[st]}],"border-w-l":[{"border-l":[st]}],"border-opacity":[{"border-opacity":[yt]}],"border-style":[{border:[...Qt(),"hidden"]}],"divide-x":[{"divide-x":[st]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[st]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[yt]}],"divide-style":[{divide:Qt()}],"border-color":[{border:[nt]}],"border-color-x":[{"border-x":[nt]}],"border-color-y":[{"border-y":[nt]}],"border-color-s":[{"border-s":[nt]}],"border-color-e":[{"border-e":[nt]}],"border-color-t":[{"border-t":[nt]}],"border-color-r":[{"border-r":[nt]}],"border-color-b":[{"border-b":[nt]}],"border-color-l":[{"border-l":[nt]}],"divide-color":[{divide:[nt]}],"outline-style":[{outline:["",...Qt()]}],"outline-offset":[{"outline-offset":[isLength,isArbitraryValue]}],"outline-w":[{outline:[isLength,isArbitraryLength]}],"outline-color":[{outline:[et]}],"ring-w":[{ring:Yt()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[et]}],"ring-opacity":[{"ring-opacity":[yt]}],"ring-offset-w":[{"ring-offset":[isLength,isArbitraryLength]}],"ring-offset-color":[{"ring-offset":[et]}],shadow:[{shadow:["","inner","none",isTshirtSize,isArbitraryShadow]}],"shadow-color":[{shadow:[isAny]}],opacity:[{opacity:[yt]}],"mix-blend":[{"mix-blend":[...Vt(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Vt()}],filter:[{filter:["","none"]}],blur:[{blur:[tt]}],brightness:[{brightness:[rt]}],contrast:[{contrast:[at]}],"drop-shadow":[{"drop-shadow":["","none",isTshirtSize,isArbitraryValue]}],grayscale:[{grayscale:[ct]}],"hue-rotate":[{"hue-rotate":[lt]}],invert:[{invert:[dt]}],saturate:[{saturate:[xt]}],sepia:[{sepia:[Et]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[tt]}],"backdrop-brightness":[{"backdrop-brightness":[rt]}],"backdrop-contrast":[{"backdrop-contrast":[at]}],"backdrop-grayscale":[{"backdrop-grayscale":[ct]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[lt]}],"backdrop-invert":[{"backdrop-invert":[dt]}],"backdrop-opacity":[{"backdrop-opacity":[yt]}],"backdrop-saturate":[{"backdrop-saturate":[xt]}],"backdrop-sepia":[{"backdrop-sepia":[Et]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[it]}],"border-spacing-x":[{"border-spacing-x":[it]}],"border-spacing-y":[{"border-spacing-y":[it]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",isArbitraryValue]}],duration:[{duration:Xt()}],ease:[{ease:["linear","in","out","in-out",isArbitraryValue]}],delay:[{delay:Xt()}],animate:[{animate:["none","spin","ping","pulse","bounce",isArbitraryValue]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[vt]}],"scale-x":[{"scale-x":[vt]}],"scale-y":[{"scale-y":[vt]}],rotate:[{rotate:[isInteger$1,isArbitraryValue]}],"translate-x":[{"translate-x":[At]}],"translate-y":[{"translate-y":[At]}],"skew-x":[{"skew-x":[Ct]}],"skew-y":[{"skew-y":[Ct]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",isArbitraryValue]}],accent:[{accent:["auto",et]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",isArbitraryValue]}],"caret-color":[{caret:[et]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":Nt()}],"scroll-mx":[{"scroll-mx":Nt()}],"scroll-my":[{"scroll-my":Nt()}],"scroll-ms":[{"scroll-ms":Nt()}],"scroll-me":[{"scroll-me":Nt()}],"scroll-mt":[{"scroll-mt":Nt()}],"scroll-mr":[{"scroll-mr":Nt()}],"scroll-mb":[{"scroll-mb":Nt()}],"scroll-ml":[{"scroll-ml":Nt()}],"scroll-p":[{"scroll-p":Nt()}],"scroll-px":[{"scroll-px":Nt()}],"scroll-py":[{"scroll-py":Nt()}],"scroll-ps":[{"scroll-ps":Nt()}],"scroll-pe":[{"scroll-pe":Nt()}],"scroll-pt":[{"scroll-pt":Nt()}],"scroll-pr":[{"scroll-pr":Nt()}],"scroll-pb":[{"scroll-pb":Nt()}],"scroll-pl":[{"scroll-pl":Nt()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",isArbitraryValue]}],fill:[{fill:[et,"none"]}],"stroke-w":[{stroke:[isLength,isArbitraryLength,isArbitraryNumber]}],stroke:[{stroke:[et,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},twMerge=createTailwindMerge(getDefaultConfig);function cn(...et){return twMerge(clsx(et))}const buttonVariants=cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Button=reactExports.forwardRef(({className:et,variant:o,size:tt,asChild:rt=!1,...nt},ot)=>{const it=rt?Slot:"button";return jsxRuntimeExports.jsx(it,{className:cn(buttonVariants({variant:o,size:tt,className:et})),ref:ot,...nt})});Button.displayName="Button";function allocUnsafe$j(et=0){return new Uint8Array(et)}const N1$6=Math.pow(2,7),N2$6=Math.pow(2,14),N3$6=Math.pow(2,21),N4$6=Math.pow(2,28),N5$6=Math.pow(2,35),N6$6=Math.pow(2,42),N7$6=Math.pow(2,49),MSB$8=128,REST$8=127;function encodingLength$6(et){if(etNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function encodeUint8Array(et,o,tt=0){switch(encodingLength$6(et)){case 8:o[tt++]=et&255|MSB$8,et/=128;case 7:o[tt++]=et&255|MSB$8,et/=128;case 6:o[tt++]=et&255|MSB$8,et/=128;case 5:o[tt++]=et&255|MSB$8,et/=128;case 4:o[tt++]=et&255|MSB$8,et>>>=7;case 3:o[tt++]=et&255|MSB$8,et>>>=7;case 2:o[tt++]=et&255|MSB$8,et>>>=7;case 1:{o[tt++]=et&255,et>>>=7;break}default:throw new Error("unreachable")}return o}function encodeUint8ArrayList(et,o,tt=0){switch(encodingLength$6(et)){case 8:o.set(tt++,et&255|MSB$8),et/=128;case 7:o.set(tt++,et&255|MSB$8),et/=128;case 6:o.set(tt++,et&255|MSB$8),et/=128;case 5:o.set(tt++,et&255|MSB$8),et/=128;case 4:o.set(tt++,et&255|MSB$8),et>>>=7;case 3:o.set(tt++,et&255|MSB$8),et>>>=7;case 2:o.set(tt++,et&255|MSB$8),et>>>=7;case 1:{o.set(tt++,et&255),et>>>=7;break}default:throw new Error("unreachable")}return o}function decodeUint8Array(et,o){let tt=et[o],rt=0;if(rt+=tt&REST$8,tt>>31>0){const tt=~this.lo+1>>>0;let rt=~this.hi>>>0;return tt===0&&(rt=rt+1>>>0),-(tt+rt*4294967296)}return this.lo+this.hi*4294967296}toBigInt(o=!1){if(o)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const tt=~this.lo+1>>>0;let rt=~this.hi>>>0;return tt===0&&(rt=rt+1>>>0),-(BigInt(tt)+(BigInt(rt)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(o=!1){return this.toBigInt(o).toString()}zzEncode(){const o=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^o)>>>0,this.lo=(this.lo<<1^o)>>>0,this}zzDecode(){const o=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^o)>>>0,this.hi=(this.hi>>>1^o)>>>0,this}length(){const o=this.lo,tt=(this.lo>>>28|this.hi<<4)>>>0,rt=this.hi>>>24;return rt===0?tt===0?o<16384?o<128?1:2:o<2097152?3:4:tt<16384?tt<128?5:6:tt<2097152?7:8:rt<128?9:10}static fromBigInt(o){if(o===0n)return zero;if(oMIN_SAFE_NUMBER_INTEGER)return this.fromNumber(Number(o));const tt=o<0n;tt&&(o=-o);let rt=o>>32n,nt=o-(rt<<32n);return tt&&(rt=~rt|0n,nt=~nt|0n,++nt>TWO_32&&(nt=0n,++rt>TWO_32&&(rt=0n))),new Sn(Number(nt),Number(rt))}static fromNumber(o){if(o===0)return zero;const tt=o<0;tt&&(o=-o);let rt=o>>>0,nt=(o-rt)/4294967296>>>0;return tt&&(nt=~nt>>>0,rt=~rt>>>0,++rt>4294967295&&(rt=0,++nt>4294967295&&(nt=0))),new Sn(rt,nt)}static from(o){return typeof o=="number"?Sn.fromNumber(o):typeof o=="bigint"?Sn.fromBigInt(o):typeof o=="string"?Sn.fromBigInt(BigInt(o)):o.low!=null||o.high!=null?new Sn(o.low>>>0,o.high>>>0):zero}};const zero=new LongBits$2(0,0);zero.toBigInt=function(){return 0n};zero.zzEncode=zero.zzDecode=function(){return this};zero.length=function(){return 1};const TWO_32=4294967296n;function length$6(et){let o=0,tt=0;for(let rt=0;rt191&&st<224?ot[it++]=(st&31)<<6|et[o++]&63:st>239&&st<365?(st=((st&7)<<18|(et[o++]&63)<<12|(et[o++]&63)<<6|et[o++]&63)-65536,ot[it++]=55296+(st>>10),ot[it++]=56320+(st&1023)):ot[it++]=(st&15)<<12|(et[o++]&63)<<6|et[o++]&63,it>8191&&((nt??(nt=[])).push(String.fromCharCode.apply(String,ot)),it=0);return nt!=null?(it>0&&nt.push(String.fromCharCode.apply(String,ot.slice(0,it))),nt.join("")):String.fromCharCode.apply(String,ot.slice(0,it))}function write$2(et,o,tt){const rt=tt;let nt,ot;for(let it=0;it>6|192,o[tt++]=nt&63|128):(nt&64512)===55296&&((ot=et.charCodeAt(it+1))&64512)===56320?(nt=65536+((nt&1023)<<10)+(ot&1023),++it,o[tt++]=nt>>18|240,o[tt++]=nt>>12&63|128,o[tt++]=nt>>6&63|128,o[tt++]=nt&63|128):(o[tt++]=nt>>12|224,o[tt++]=nt>>6&63|128,o[tt++]=nt&63|128);return tt-rt}function indexOutOfRange$1(et,o){return RangeError(`index out of range: ${et.pos} + ${o??1} > ${et.len}`)}function readFixed32End(et,o){return(et[o-4]|et[o-3]<<8|et[o-2]<<16|et[o-1]<<24)>>>0}class Uint8ArrayReader{constructor(o){wt(this,"buf");wt(this,"pos");wt(this,"len");wt(this,"_slice",Uint8Array.prototype.subarray);this.buf=o,this.pos=0,this.len=o.length}uint32(){let o=4294967295;if(o=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(o=(o|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(o=(o|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(o=(o|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(o=(o|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return o;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange$1(this,10);return o}int32(){return this.uint32()|0}sint32(){const o=this.uint32();return o>>>1^-(o&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw indexOutOfRange$1(this,4);return readFixed32End(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw indexOutOfRange$1(this,4);return readFixed32End(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw indexOutOfRange$1(this,4);const o=readFloatLE(this.buf,this.pos);return this.pos+=4,o}double(){if(this.pos+8>this.len)throw indexOutOfRange$1(this,4);const o=readDoubleLE(this.buf,this.pos);return this.pos+=8,o}bytes(){const o=this.uint32(),tt=this.pos,rt=this.pos+o;if(rt>this.len)throw indexOutOfRange$1(this,o);return this.pos+=o,tt===rt?new Uint8Array(0):this.buf.subarray(tt,rt)}string(){const o=this.bytes();return read$7(o,0,o.length)}skip(o){if(typeof o=="number"){if(this.pos+o>this.len)throw indexOutOfRange$1(this,o);this.pos+=o}else do if(this.pos>=this.len)throw indexOutOfRange$1(this);while(this.buf[this.pos++]&128);return this}skipType(o){switch(o){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(o=this.uint32()&7)!==4;)this.skipType(o);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${o} at offset ${this.pos}`)}return this}readLongVarint(){const o=new LongBits$2(0,0);let tt=0;if(this.len-this.pos>4){for(;tt<4;++tt)if(o.lo=(o.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o;if(o.lo=(o.lo|(this.buf[this.pos]&127)<<28)>>>0,o.hi=(o.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return o;tt=0}else{for(;tt<3;++tt){if(this.pos>=this.len)throw indexOutOfRange$1(this);if(o.lo=(o.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o}return o.lo=(o.lo|(this.buf[this.pos++]&127)<>>0,o}if(this.len-this.pos>4){for(;tt<5;++tt)if(o.hi=(o.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o}else for(;tt<5;++tt){if(this.pos>=this.len)throw indexOutOfRange$1(this);if(o.hi=(o.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange$1(this,8);const o=readFixed32End(this.buf,this.pos+=4),tt=readFixed32End(this.buf,this.pos+=4);return new LongBits$2(o,tt)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const o=decodeUint8Array(this.buf,this.pos);return this.pos+=encodingLength$6(o),o}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function createReader(et){return new Uint8ArrayReader(et instanceof Uint8Array?et:et.subarray())}function decodeMessage(et,o,tt){const rt=createReader(et);return o.decode(rt,void 0,tt)}function allocUnsafe$i(et=0){return new Uint8Array(et)}function coerce$l(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$w(et){return new TextEncoder().encode(et)}function toString$x(et){return new TextDecoder().decode(et)}function base$l(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$l=base$l,_brrp__multiformats_scope_baseX$k=src$l;let Encoder$m=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$m=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$m(this,o)}},ComposedDecoder$k=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$m(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$m(et,o){return new ComposedDecoder$k({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$k=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$m(o,tt,rt),this.decoder=new Decoder$m(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$n({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$k(et,o,tt,rt)}function baseX$k({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$k(tt,et);return from$n({prefix:o,name:et,encode:rt,decode:ot=>coerce$l(nt(ot))})}function decode$Y(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$O(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$g=alphabet$g.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$N(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$g[tt],o),"")}function decode$X(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$g[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$w=from$n({prefix:"🚀",name:"base256emoji",encode:encode$N,decode:decode$X}),base256emoji$x=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$w},Symbol.toStringTag,{value:"Module"})),base32$A=rfc4648$j({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$g=rfc4648$j({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$g=rfc4648$j({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$g=rfc4648$j({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$g=rfc4648$j({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$g=rfc4648$j({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$g=rfc4648$j({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$g=rfc4648$j({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$g=rfc4648$j({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$B=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$A,base32hex:base32hex$g,base32hexpad:base32hexpad$g,base32hexpadupper:base32hexpadupper$g,base32hexupper:base32hexupper$g,base32pad:base32pad$g,base32padupper:base32padupper$g,base32upper:base32upper$g,base32z:base32z$g},Symbol.toStringTag,{value:"Module"})),base36$x=baseX$k({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$g=baseX$k({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$y=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$x,base36upper:base36upper$g},Symbol.toStringTag,{value:"Module"})),base58btc$k=baseX$k({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$g=baseX$k({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$g=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$k,base58flickr:base58flickr$g},Symbol.toStringTag,{value:"Module"})),base64$z=rfc4648$j({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$g=rfc4648$j({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$h=rfc4648$j({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$g=rfc4648$j({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$A=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$z,base64pad:base64pad$g,base64url:base64url$h,base64urlpad:base64urlpad$g},Symbol.toStringTag,{value:"Module"})),base8$w=rfc4648$j({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$x=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$w},Symbol.toStringTag,{value:"Module"})),identity$i=from$n({prefix:"\0",name:"identity",encode:et=>toString$x(et),decode:et=>fromString$w(et)}),identityBase$g=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$i},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$g={...identityBase$g,...base2$x,...base8$x,...base10$x,...base16$x,...base32$B,...base36$y,...base58$g,...base64$A,...base256emoji$x};function createCodec$h(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$k=createCodec$h("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$g=createCodec$h("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$i(et.length);for(let tt=0;tt4096)return allocUnsafe$i(it);nt+it>8192&&(rt=allocUnsafe$i(8192),nt=0);const st=rt.subarray(nt,nt+=it);return nt&7&&(nt=(nt|7)+1),st}}let Op$1=class{constructor(o,tt,rt){wt(this,"fn");wt(this,"len");wt(this,"next");wt(this,"val");this.fn=o,this.len=tt,this.next=void 0,this.val=rt}};function noop$2(){}let State$1=class{constructor(o){wt(this,"head");wt(this,"tail");wt(this,"len");wt(this,"next");this.head=o.head,this.tail=o.tail,this.len=o.len,this.next=o.states}};const bufferPool=pool$1();function alloc$7(et){return globalThis.Buffer!=null?allocUnsafe$i(et):bufferPool(et)}class Uint8ArrayWriter{constructor(){wt(this,"len");wt(this,"head");wt(this,"tail");wt(this,"states");this.len=0,this.head=new Op$1(noop$2,0,0),this.tail=this.head,this.states=null}_push(o,tt,rt){return this.tail=this.tail.next=new Op$1(o,tt,rt),this.len+=tt,this}uint32(o){return this.len+=(this.tail=this.tail.next=new VarintOp$1((o=o>>>0)<128?1:o<16384?2:o<2097152?3:o<268435456?4:5,o)).len,this}int32(o){return o<0?this._push(writeVarint64$1,10,LongBits$2.fromNumber(o)):this.uint32(o)}sint32(o){return this.uint32((o<<1^o>>31)>>>0)}uint64(o){const tt=LongBits$2.fromBigInt(o);return this._push(writeVarint64$1,tt.length(),tt)}uint64Number(o){return this._push(encodeUint8Array,encodingLength$6(o),o)}uint64String(o){return this.uint64(BigInt(o))}int64(o){return this.uint64(o)}int64Number(o){return this.uint64Number(o)}int64String(o){return this.uint64String(o)}sint64(o){const tt=LongBits$2.fromBigInt(o).zzEncode();return this._push(writeVarint64$1,tt.length(),tt)}sint64Number(o){const tt=LongBits$2.fromNumber(o).zzEncode();return this._push(writeVarint64$1,tt.length(),tt)}sint64String(o){return this.sint64(BigInt(o))}bool(o){return this._push(writeByte$1,1,o?1:0)}fixed32(o){return this._push(writeFixed32$1,4,o>>>0)}sfixed32(o){return this.fixed32(o)}fixed64(o){const tt=LongBits$2.fromBigInt(o);return this._push(writeFixed32$1,4,tt.lo)._push(writeFixed32$1,4,tt.hi)}fixed64Number(o){const tt=LongBits$2.fromNumber(o);return this._push(writeFixed32$1,4,tt.lo)._push(writeFixed32$1,4,tt.hi)}fixed64String(o){return this.fixed64(BigInt(o))}sfixed64(o){return this.fixed64(o)}sfixed64Number(o){return this.fixed64Number(o)}sfixed64String(o){return this.fixed64String(o)}float(o){return this._push(writeFloatLE,4,o)}double(o){return this._push(writeDoubleLE,8,o)}bytes(o){const tt=o.length>>>0;return tt===0?this._push(writeByte$1,1,0):this.uint32(tt)._push(writeBytes$1,tt,o)}string(o){const tt=length$6(o);return tt!==0?this.uint32(tt)._push(write$2,tt,o):this._push(writeByte$1,1,0)}fork(){return this.states=new State$1(this),this.head=this.tail=new Op$1(noop$2,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op$1(noop$2,0,0),this.len=0),this}ldelim(){const o=this.head,tt=this.tail,rt=this.len;return this.reset().uint32(rt),rt!==0&&(this.tail.next=o.next,this.tail=tt,this.len+=rt),this}finish(){let o=this.head.next;const tt=alloc$7(this.len);let rt=0;for(;o!=null;)o.fn(o.val,tt,rt),rt+=o.len,o=o.next;return tt}}function writeByte$1(et,o,tt){o[tt]=et&255}function writeVarint32$1(et,o,tt){for(;et>127;)o[tt++]=et&127|128,et>>>=7;o[tt]=et}let VarintOp$1=class extends Op$1{constructor(tt,rt){super(writeVarint32$1,tt,rt);wt(this,"next");this.next=void 0}};function writeVarint64$1(et,o,tt){for(;et.hi!==0;)o[tt++]=et.lo&127|128,et.lo=(et.lo>>>7|et.hi<<25)>>>0,et.hi>>>=7;for(;et.lo>127;)o[tt++]=et.lo&127|128,et.lo=et.lo>>>7;o[tt++]=et.lo}function writeFixed32$1(et,o,tt){o[tt]=et&255,o[tt+1]=et>>>8&255,o[tt+2]=et>>>16&255,o[tt+3]=et>>>24}function writeBytes$1(et,o,tt){o.set(et,tt)}globalThis.Buffer!=null&&(Uint8ArrayWriter.prototype.bytes=function(et){const o=et.length>>>0;return this.uint32(o),o>0&&this._push(writeBytesBuffer,o,et),this},Uint8ArrayWriter.prototype.string=function(et){const o=globalThis.Buffer.byteLength(et);return this.uint32(o),o>0&&this._push(writeStringBuffer$1,o,et),this});function writeBytesBuffer(et,o,tt){o.set(et,tt)}function writeStringBuffer$1(et,o,tt){et.length<40?write$2(et,o,tt):o.utf8Write!=null?o.utf8Write(et,tt):o.set(fromString$v(et),tt)}function createWriter(){return new Uint8ArrayWriter}function encodeMessage(et,o){const tt=createWriter();return o.encode(et,tt,{lengthDelimited:!1}),tt.finish()}var CODEC_TYPES;(function(et){et[et.VARINT=0]="VARINT",et[et.BIT64=1]="BIT64",et[et.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",et[et.START_GROUP=3]="START_GROUP",et[et.END_GROUP=4]="END_GROUP",et[et.BIT32=5]="BIT32"})(CODEC_TYPES||(CODEC_TYPES={}));function createCodec$g(et,o,tt,rt){return{name:et,type:o,encode:tt,decode:rt}}function enumeration(et){function o(nt){if(et[nt.toString()]==null)throw new Error("Invalid enum value");return et[nt]}const tt=function(ot,it){const st=o(ot);it.int32(st)},rt=function(ot){const it=ot.int32();return o(it)};return createCodec$g("enum",CODEC_TYPES.VARINT,tt,rt)}function message$1(et,o){return createCodec$g("message",CODEC_TYPES.LENGTH_DELIMITED,et,o)}class MaxLengthError extends Error{constructor(){super(...arguments);wt(this,"code","ERR_MAX_LENGTH");wt(this,"name","MaxLengthError")}}class MaxSizeError extends Error{constructor(){super(...arguments);wt(this,"code","ERR_MAX_SIZE");wt(this,"name","MaxSizeError")}}function alloc$6(et=0){return globalThis.Buffer!=null&&globalThis.Buffer.alloc!=null?globalThis.Buffer.alloc(et):new Uint8Array(et)}function allocUnsafe$h(et=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(et):new Uint8Array(et)}var RateLimitProof$4;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.proof!=null&&tt.proof.byteLength>0&&(rt.uint32(10),rt.bytes(tt.proof)),tt.merkleRoot!=null&&tt.merkleRoot.byteLength>0&&(rt.uint32(18),rt.bytes(tt.merkleRoot)),tt.epoch!=null&&tt.epoch.byteLength>0&&(rt.uint32(26),rt.bytes(tt.epoch)),tt.shareX!=null&&tt.shareX.byteLength>0&&(rt.uint32(34),rt.bytes(tt.shareX)),tt.shareY!=null&&tt.shareY.byteLength>0&&(rt.uint32(42),rt.bytes(tt.shareY)),tt.nullifier!=null&&tt.nullifier.byteLength>0&&(rt.uint32(50),rt.bytes(tt.nullifier)),tt.rlnIdentifier!=null&&tt.rlnIdentifier.byteLength>0&&(rt.uint32(58),rt.bytes(tt.rlnIdentifier)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={proof:alloc$6(0),merkleRoot:alloc$6(0),epoch:alloc$6(0),shareX:alloc$6(0),shareY:alloc$6(0),nullifier:alloc$6(0),rlnIdentifier:alloc$6(0)},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.proof=tt.bytes();break}case 2:{ot.merkleRoot=tt.bytes();break}case 3:{ot.epoch=tt.bytes();break}case 4:{ot.shareX=tt.bytes();break}case 5:{ot.shareY=tt.bytes();break}case 6:{ot.nullifier=tt.bytes();break}case 7:{ot.rlnIdentifier=tt.bytes();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(RateLimitProof$4||(RateLimitProof$4={}));var WakuMessage$4;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.payload!=null&&tt.payload.byteLength>0&&(rt.uint32(10),rt.bytes(tt.payload)),tt.contentTopic!=null&&tt.contentTopic!==""&&(rt.uint32(18),rt.string(tt.contentTopic)),tt.version!=null&&(rt.uint32(24),rt.uint32(tt.version)),tt.timestamp!=null&&(rt.uint32(80),rt.sint64(tt.timestamp)),tt.meta!=null&&(rt.uint32(90),rt.bytes(tt.meta)),tt.rateLimitProof!=null&&(rt.uint32(170),RateLimitProof$4.codec().encode(tt.rateLimitProof,rt)),tt.ephemeral!=null&&(rt.uint32(248),rt.bool(tt.ephemeral)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={payload:alloc$6(0),contentTopic:""},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.payload=tt.bytes();break}case 2:{ot.contentTopic=tt.string();break}case 3:{ot.version=tt.uint32();break}case 10:{ot.timestamp=tt.sint64();break}case 11:{ot.meta=tt.bytes();break}case 21:{ot.rateLimitProof=RateLimitProof$4.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.rateLimitProof});break}case 31:{ot.ephemeral=tt.bool();break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(WakuMessage$4||(WakuMessage$4={}));var FilterRequest;(function(et){(function(tt){let rt;tt.codec=()=>(rt==null&&(rt=message$1((nt,ot,it={})=>{it.lengthDelimited!==!1&&ot.fork(),nt.contentTopic!=null&&nt.contentTopic!==""&&(ot.uint32(10),ot.string(nt.contentTopic)),it.lengthDelimited!==!1&&ot.ldelim()},(nt,ot,it={})=>{const st={contentTopic:""},at=ot==null?nt.len:nt.pos+ot;for(;nt.pos>>3){case 1:{st.contentTopic=nt.string();break}default:{nt.skipType(ct&7);break}}}return st})),rt),tt.encode=nt=>encodeMessage(nt,tt.codec()),tt.decode=(nt,ot)=>decodeMessage(nt,tt.codec(),ot)})(et.ContentFilter||(et.ContentFilter={}));let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.subscribe!=null&&tt.subscribe!==!1&&(rt.uint32(8),rt.bool(tt.subscribe)),tt.topic!=null&&tt.topic!==""&&(rt.uint32(18),rt.string(tt.topic)),tt.contentFilters!=null)for(const ot of tt.contentFilters)rt.uint32(26),et.ContentFilter.codec().encode(ot,rt);nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={subscribe:!1,topic:"",contentFilters:[]},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.subscribe=tt.bool();break}case 2:{ot.topic=tt.string();break}case 3:{if(((st=nt.limits)==null?void 0:st.contentFilters)!=null&&ot.contentFilters.length===nt.limits.contentFilters)throw new MaxLengthError('Decode error - map field "contentFilters" had too many elements');ot.contentFilters.push(et.ContentFilter.codec().decode(tt,tt.uint32(),{limits:(at=nt.limits)==null?void 0:at.contentFilters$}));break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(FilterRequest||(FilterRequest={}));var MessagePush$1;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.messages!=null)for(const ot of tt.messages)rt.uint32(10),WakuMessage$3.codec().encode(ot,rt);nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={messages:[]},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{if(((st=nt.limits)==null?void 0:st.messages)!=null&&ot.messages.length===nt.limits.messages)throw new MaxLengthError('Decode error - map field "messages" had too many elements');ot.messages.push(WakuMessage$3.codec().decode(tt,tt.uint32(),{limits:(at=nt.limits)==null?void 0:at.messages$}));break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(MessagePush$1||(MessagePush$1={}));var FilterRpc;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.requestId!=null&&tt.requestId!==""&&(rt.uint32(10),rt.string(tt.requestId)),tt.request!=null&&(rt.uint32(18),FilterRequest.codec().encode(tt.request,rt)),tt.push!=null&&(rt.uint32(26),MessagePush$1.codec().encode(tt.push,rt)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={requestId:""},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.requestId=tt.string();break}case 2:{ot.request=FilterRequest.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.request});break}case 3:{ot.push=MessagePush$1.codec().decode(tt,tt.uint32(),{limits:(at=nt.limits)==null?void 0:at.push});break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(FilterRpc||(FilterRpc={}));var RateLimitProof$3;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.proof!=null&&tt.proof.byteLength>0&&(rt.uint32(10),rt.bytes(tt.proof)),tt.merkleRoot!=null&&tt.merkleRoot.byteLength>0&&(rt.uint32(18),rt.bytes(tt.merkleRoot)),tt.epoch!=null&&tt.epoch.byteLength>0&&(rt.uint32(26),rt.bytes(tt.epoch)),tt.shareX!=null&&tt.shareX.byteLength>0&&(rt.uint32(34),rt.bytes(tt.shareX)),tt.shareY!=null&&tt.shareY.byteLength>0&&(rt.uint32(42),rt.bytes(tt.shareY)),tt.nullifier!=null&&tt.nullifier.byteLength>0&&(rt.uint32(50),rt.bytes(tt.nullifier)),tt.rlnIdentifier!=null&&tt.rlnIdentifier.byteLength>0&&(rt.uint32(58),rt.bytes(tt.rlnIdentifier)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={proof:alloc$6(0),merkleRoot:alloc$6(0),epoch:alloc$6(0),shareX:alloc$6(0),shareY:alloc$6(0),nullifier:alloc$6(0),rlnIdentifier:alloc$6(0)},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.proof=tt.bytes();break}case 2:{ot.merkleRoot=tt.bytes();break}case 3:{ot.epoch=tt.bytes();break}case 4:{ot.shareX=tt.bytes();break}case 5:{ot.shareY=tt.bytes();break}case 6:{ot.nullifier=tt.bytes();break}case 7:{ot.rlnIdentifier=tt.bytes();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(RateLimitProof$3||(RateLimitProof$3={}));var WakuMessage$3;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.payload!=null&&tt.payload.byteLength>0&&(rt.uint32(10),rt.bytes(tt.payload)),tt.contentTopic!=null&&tt.contentTopic!==""&&(rt.uint32(18),rt.string(tt.contentTopic)),tt.version!=null&&(rt.uint32(24),rt.uint32(tt.version)),tt.timestamp!=null&&(rt.uint32(80),rt.sint64(tt.timestamp)),tt.meta!=null&&(rt.uint32(90),rt.bytes(tt.meta)),tt.rateLimitProof!=null&&(rt.uint32(170),RateLimitProof$3.codec().encode(tt.rateLimitProof,rt)),tt.ephemeral!=null&&(rt.uint32(248),rt.bool(tt.ephemeral)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={payload:alloc$6(0),contentTopic:""},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.payload=tt.bytes();break}case 2:{ot.contentTopic=tt.string();break}case 3:{ot.version=tt.uint32();break}case 10:{ot.timestamp=tt.sint64();break}case 11:{ot.meta=tt.bytes();break}case 21:{ot.rateLimitProof=RateLimitProof$3.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.rateLimitProof});break}case 31:{ot.ephemeral=tt.bool();break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(WakuMessage$3||(WakuMessage$3={}));var TopicOnlyMessage;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.contentTopic!=null&&tt.contentTopic!==""&&(rt.uint32(18),rt.string(tt.contentTopic)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={contentTopic:""},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 2:{ot.contentTopic=tt.string();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(TopicOnlyMessage||(TopicOnlyMessage={}));var FilterSubscribeRequest;(function(et){let o;(function(nt){nt.SUBSCRIBER_PING="SUBSCRIBER_PING",nt.SUBSCRIBE="SUBSCRIBE",nt.UNSUBSCRIBE="UNSUBSCRIBE",nt.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"})(o=et.FilterSubscribeType||(et.FilterSubscribeType={}));let tt;(function(nt){nt[nt.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",nt[nt.SUBSCRIBE=1]="SUBSCRIBE",nt[nt.UNSUBSCRIBE=2]="UNSUBSCRIBE",nt[nt.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"})(tt||(tt={})),function(nt){nt.codec=()=>enumeration(tt)}(o=et.FilterSubscribeType||(et.FilterSubscribeType={}));let rt;et.codec=()=>(rt==null&&(rt=message$1((nt,ot,it={})=>{if(it.lengthDelimited!==!1&&ot.fork(),nt.requestId!=null&&nt.requestId!==""&&(ot.uint32(10),ot.string(nt.requestId)),nt.filterSubscribeType!=null&&tt[nt.filterSubscribeType]!==0&&(ot.uint32(16),et.FilterSubscribeType.codec().encode(nt.filterSubscribeType,ot)),nt.pubsubTopic!=null&&(ot.uint32(82),ot.string(nt.pubsubTopic)),nt.contentTopics!=null)for(const st of nt.contentTopics)ot.uint32(90),ot.string(st);it.lengthDelimited!==!1&&ot.ldelim()},(nt,ot,it={})=>{var ct;const st={requestId:"",filterSubscribeType:o.SUBSCRIBER_PING,contentTopics:[]},at=ot==null?nt.len:nt.pos+ot;for(;nt.pos>>3){case 1:{st.requestId=nt.string();break}case 2:{st.filterSubscribeType=et.FilterSubscribeType.codec().decode(nt);break}case 10:{st.pubsubTopic=nt.string();break}case 11:{if(((ct=it.limits)==null?void 0:ct.contentTopics)!=null&&st.contentTopics.length===it.limits.contentTopics)throw new MaxLengthError('Decode error - map field "contentTopics" had too many elements');st.contentTopics.push(nt.string());break}default:{nt.skipType(lt&7);break}}}return st})),rt),et.encode=nt=>encodeMessage(nt,et.codec()),et.decode=(nt,ot)=>decodeMessage(nt,et.codec(),ot)})(FilterSubscribeRequest||(FilterSubscribeRequest={}));var FilterSubscribeResponse$1;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.requestId!=null&&tt.requestId!==""&&(rt.uint32(10),rt.string(tt.requestId)),tt.statusCode!=null&&tt.statusCode!==0&&(rt.uint32(80),rt.uint32(tt.statusCode)),tt.statusDesc!=null&&(rt.uint32(90),rt.string(tt.statusDesc)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={requestId:"",statusCode:0},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.requestId=tt.string();break}case 10:{ot.statusCode=tt.uint32();break}case 11:{ot.statusDesc=tt.string();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(FilterSubscribeResponse$1||(FilterSubscribeResponse$1={}));var MessagePush;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.wakuMessage!=null&&(rt.uint32(10),WakuMessage$2.codec().encode(tt.wakuMessage,rt)),tt.pubsubTopic!=null&&(rt.uint32(18),rt.string(tt.pubsubTopic)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.wakuMessage=WakuMessage$2.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.wakuMessage});break}case 2:{ot.pubsubTopic=tt.string();break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(MessagePush||(MessagePush={}));var RateLimitProof$2;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.proof!=null&&tt.proof.byteLength>0&&(rt.uint32(10),rt.bytes(tt.proof)),tt.merkleRoot!=null&&tt.merkleRoot.byteLength>0&&(rt.uint32(18),rt.bytes(tt.merkleRoot)),tt.epoch!=null&&tt.epoch.byteLength>0&&(rt.uint32(26),rt.bytes(tt.epoch)),tt.shareX!=null&&tt.shareX.byteLength>0&&(rt.uint32(34),rt.bytes(tt.shareX)),tt.shareY!=null&&tt.shareY.byteLength>0&&(rt.uint32(42),rt.bytes(tt.shareY)),tt.nullifier!=null&&tt.nullifier.byteLength>0&&(rt.uint32(50),rt.bytes(tt.nullifier)),tt.rlnIdentifier!=null&&tt.rlnIdentifier.byteLength>0&&(rt.uint32(58),rt.bytes(tt.rlnIdentifier)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={proof:alloc$6(0),merkleRoot:alloc$6(0),epoch:alloc$6(0),shareX:alloc$6(0),shareY:alloc$6(0),nullifier:alloc$6(0),rlnIdentifier:alloc$6(0)},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.proof=tt.bytes();break}case 2:{ot.merkleRoot=tt.bytes();break}case 3:{ot.epoch=tt.bytes();break}case 4:{ot.shareX=tt.bytes();break}case 5:{ot.shareY=tt.bytes();break}case 6:{ot.nullifier=tt.bytes();break}case 7:{ot.rlnIdentifier=tt.bytes();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(RateLimitProof$2||(RateLimitProof$2={}));var WakuMessage$2;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.payload!=null&&tt.payload.byteLength>0&&(rt.uint32(10),rt.bytes(tt.payload)),tt.contentTopic!=null&&tt.contentTopic!==""&&(rt.uint32(18),rt.string(tt.contentTopic)),tt.version!=null&&(rt.uint32(24),rt.uint32(tt.version)),tt.timestamp!=null&&(rt.uint32(80),rt.sint64(tt.timestamp)),tt.meta!=null&&(rt.uint32(90),rt.bytes(tt.meta)),tt.rateLimitProof!=null&&(rt.uint32(170),RateLimitProof$2.codec().encode(tt.rateLimitProof,rt)),tt.ephemeral!=null&&(rt.uint32(248),rt.bool(tt.ephemeral)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={payload:alloc$6(0),contentTopic:""},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.payload=tt.bytes();break}case 2:{ot.contentTopic=tt.string();break}case 3:{ot.version=tt.uint32();break}case 10:{ot.timestamp=tt.sint64();break}case 11:{ot.meta=tt.bytes();break}case 21:{ot.rateLimitProof=RateLimitProof$2.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.rateLimitProof});break}case 31:{ot.ephemeral=tt.bool();break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(WakuMessage$2||(WakuMessage$2={}));var PushRequest;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.pubsubTopic!=null&&tt.pubsubTopic!==""&&(rt.uint32(10),rt.string(tt.pubsubTopic)),tt.message!=null&&(rt.uint32(18),WakuMessage$1.codec().encode(tt.message,rt)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={pubsubTopic:""},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.pubsubTopic=tt.string();break}case 2:{ot.message=WakuMessage$1.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.message});break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PushRequest||(PushRequest={}));var PushResponse;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.isSuccess!=null&&tt.isSuccess!==!1&&(rt.uint32(8),rt.bool(tt.isSuccess)),tt.info!=null&&(rt.uint32(18),rt.string(tt.info)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={isSuccess:!1},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.isSuccess=tt.bool();break}case 2:{ot.info=tt.string();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PushResponse||(PushResponse={}));var PushRpc$1;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.requestId!=null&&tt.requestId!==""&&(rt.uint32(10),rt.string(tt.requestId)),tt.request!=null&&(rt.uint32(18),PushRequest.codec().encode(tt.request,rt)),tt.response!=null&&(rt.uint32(26),PushResponse.codec().encode(tt.response,rt)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={requestId:""},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.requestId=tt.string();break}case 2:{ot.request=PushRequest.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.request});break}case 3:{ot.response=PushResponse.codec().decode(tt,tt.uint32(),{limits:(at=nt.limits)==null?void 0:at.response});break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PushRpc$1||(PushRpc$1={}));var RateLimitProof$1;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.proof!=null&&tt.proof.byteLength>0&&(rt.uint32(10),rt.bytes(tt.proof)),tt.merkleRoot!=null&&tt.merkleRoot.byteLength>0&&(rt.uint32(18),rt.bytes(tt.merkleRoot)),tt.epoch!=null&&tt.epoch.byteLength>0&&(rt.uint32(26),rt.bytes(tt.epoch)),tt.shareX!=null&&tt.shareX.byteLength>0&&(rt.uint32(34),rt.bytes(tt.shareX)),tt.shareY!=null&&tt.shareY.byteLength>0&&(rt.uint32(42),rt.bytes(tt.shareY)),tt.nullifier!=null&&tt.nullifier.byteLength>0&&(rt.uint32(50),rt.bytes(tt.nullifier)),tt.rlnIdentifier!=null&&tt.rlnIdentifier.byteLength>0&&(rt.uint32(58),rt.bytes(tt.rlnIdentifier)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={proof:alloc$6(0),merkleRoot:alloc$6(0),epoch:alloc$6(0),shareX:alloc$6(0),shareY:alloc$6(0),nullifier:alloc$6(0),rlnIdentifier:alloc$6(0)},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.proof=tt.bytes();break}case 2:{ot.merkleRoot=tt.bytes();break}case 3:{ot.epoch=tt.bytes();break}case 4:{ot.shareX=tt.bytes();break}case 5:{ot.shareY=tt.bytes();break}case 6:{ot.nullifier=tt.bytes();break}case 7:{ot.rlnIdentifier=tt.bytes();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(RateLimitProof$1||(RateLimitProof$1={}));var WakuMessage$1;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.payload!=null&&tt.payload.byteLength>0&&(rt.uint32(10),rt.bytes(tt.payload)),tt.contentTopic!=null&&tt.contentTopic!==""&&(rt.uint32(18),rt.string(tt.contentTopic)),tt.version!=null&&(rt.uint32(24),rt.uint32(tt.version)),tt.timestamp!=null&&(rt.uint32(80),rt.sint64(tt.timestamp)),tt.meta!=null&&(rt.uint32(90),rt.bytes(tt.meta)),tt.rateLimitProof!=null&&(rt.uint32(170),RateLimitProof$1.codec().encode(tt.rateLimitProof,rt)),tt.ephemeral!=null&&(rt.uint32(248),rt.bool(tt.ephemeral)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={payload:alloc$6(0),contentTopic:""},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.payload=tt.bytes();break}case 2:{ot.contentTopic=tt.string();break}case 3:{ot.version=tt.uint32();break}case 10:{ot.timestamp=tt.sint64();break}case 11:{ot.meta=tt.bytes();break}case 21:{ot.rateLimitProof=RateLimitProof$1.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.rateLimitProof});break}case 31:{ot.ephemeral=tt.bool();break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(WakuMessage$1||(WakuMessage$1={}));var WakuMessageKeyValue;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.messageHash!=null&&(rt.uint32(10),rt.bytes(tt.messageHash)),tt.message!=null&&(rt.uint32(18),WakuMessage.codec().encode(tt.message,rt)),tt.pubsubTopic!=null&&(rt.uint32(26),rt.string(tt.pubsubTopic)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.messageHash=tt.bytes();break}case 2:{ot.message=WakuMessage.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.message});break}case 3:{ot.pubsubTopic=tt.string();break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(WakuMessageKeyValue||(WakuMessageKeyValue={}));var StoreQueryRequest$1;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.requestId!=null&&tt.requestId!==""&&(rt.uint32(10),rt.string(tt.requestId)),tt.includeData!=null&&tt.includeData!==!1&&(rt.uint32(16),rt.bool(tt.includeData)),tt.pubsubTopic!=null&&(rt.uint32(82),rt.string(tt.pubsubTopic)),tt.contentTopics!=null)for(const ot of tt.contentTopics)rt.uint32(90),rt.string(ot);if(tt.timeStart!=null&&(rt.uint32(96),rt.sint64(tt.timeStart)),tt.timeEnd!=null&&(rt.uint32(104),rt.sint64(tt.timeEnd)),tt.messageHashes!=null)for(const ot of tt.messageHashes)rt.uint32(162),rt.bytes(ot);tt.paginationCursor!=null&&(rt.uint32(410),rt.bytes(tt.paginationCursor)),tt.paginationForward!=null&&tt.paginationForward!==!1&&(rt.uint32(416),rt.bool(tt.paginationForward)),tt.paginationLimit!=null&&(rt.uint32(424),rt.uint64(tt.paginationLimit)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.requestId=tt.string();break}case 2:{ot.includeData=tt.bool();break}case 10:{ot.pubsubTopic=tt.string();break}case 11:{if(((st=nt.limits)==null?void 0:st.contentTopics)!=null&&ot.contentTopics.length===nt.limits.contentTopics)throw new MaxLengthError('Decode error - map field "contentTopics" had too many elements');ot.contentTopics.push(tt.string());break}case 12:{ot.timeStart=tt.sint64();break}case 13:{ot.timeEnd=tt.sint64();break}case 20:{if(((at=nt.limits)==null?void 0:at.messageHashes)!=null&&ot.messageHashes.length===nt.limits.messageHashes)throw new MaxLengthError('Decode error - map field "messageHashes" had too many elements');ot.messageHashes.push(tt.bytes());break}case 51:{ot.paginationCursor=tt.bytes();break}case 52:{ot.paginationForward=tt.bool();break}case 53:{ot.paginationLimit=tt.uint64();break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(StoreQueryRequest$1||(StoreQueryRequest$1={}));var StoreQueryResponse$1;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.requestId!=null&&tt.requestId!==""&&(rt.uint32(10),rt.string(tt.requestId)),tt.statusCode!=null&&(rt.uint32(80),rt.uint32(tt.statusCode)),tt.statusDesc!=null&&(rt.uint32(90),rt.string(tt.statusDesc)),tt.messages!=null)for(const ot of tt.messages)rt.uint32(162),WakuMessageKeyValue.codec().encode(ot,rt);tt.paginationCursor!=null&&(rt.uint32(410),rt.bytes(tt.paginationCursor)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={requestId:"",messages:[]},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.requestId=tt.string();break}case 10:{ot.statusCode=tt.uint32();break}case 11:{ot.statusDesc=tt.string();break}case 20:{if(((st=nt.limits)==null?void 0:st.messages)!=null&&ot.messages.length===nt.limits.messages)throw new MaxLengthError('Decode error - map field "messages" had too many elements');ot.messages.push(WakuMessageKeyValue.codec().decode(tt,tt.uint32(),{limits:(at=nt.limits)==null?void 0:at.messages$}));break}case 51:{ot.paginationCursor=tt.bytes();break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(StoreQueryResponse$1||(StoreQueryResponse$1={}));var RateLimitProof;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.proof!=null&&tt.proof.byteLength>0&&(rt.uint32(10),rt.bytes(tt.proof)),tt.merkleRoot!=null&&tt.merkleRoot.byteLength>0&&(rt.uint32(18),rt.bytes(tt.merkleRoot)),tt.epoch!=null&&tt.epoch.byteLength>0&&(rt.uint32(26),rt.bytes(tt.epoch)),tt.shareX!=null&&tt.shareX.byteLength>0&&(rt.uint32(34),rt.bytes(tt.shareX)),tt.shareY!=null&&tt.shareY.byteLength>0&&(rt.uint32(42),rt.bytes(tt.shareY)),tt.nullifier!=null&&tt.nullifier.byteLength>0&&(rt.uint32(50),rt.bytes(tt.nullifier)),tt.rlnIdentifier!=null&&tt.rlnIdentifier.byteLength>0&&(rt.uint32(58),rt.bytes(tt.rlnIdentifier)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={proof:alloc$6(0),merkleRoot:alloc$6(0),epoch:alloc$6(0),shareX:alloc$6(0),shareY:alloc$6(0),nullifier:alloc$6(0),rlnIdentifier:alloc$6(0)},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.proof=tt.bytes();break}case 2:{ot.merkleRoot=tt.bytes();break}case 3:{ot.epoch=tt.bytes();break}case 4:{ot.shareX=tt.bytes();break}case 5:{ot.shareY=tt.bytes();break}case 6:{ot.nullifier=tt.bytes();break}case 7:{ot.rlnIdentifier=tt.bytes();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(RateLimitProof||(RateLimitProof={}));var WakuMessage;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.payload!=null&&tt.payload.byteLength>0&&(rt.uint32(10),rt.bytes(tt.payload)),tt.contentTopic!=null&&tt.contentTopic!==""&&(rt.uint32(18),rt.string(tt.contentTopic)),tt.version!=null&&(rt.uint32(24),rt.uint32(tt.version)),tt.timestamp!=null&&(rt.uint32(80),rt.sint64(tt.timestamp)),tt.meta!=null&&(rt.uint32(90),rt.bytes(tt.meta)),tt.rateLimitProof!=null&&(rt.uint32(170),RateLimitProof.codec().encode(tt.rateLimitProof,rt)),tt.ephemeral!=null&&(rt.uint32(248),rt.bool(tt.ephemeral)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={payload:alloc$6(0),contentTopic:""},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.payload=tt.bytes();break}case 2:{ot.contentTopic=tt.string();break}case 3:{ot.version=tt.uint32();break}case 10:{ot.timestamp=tt.sint64();break}case 11:{ot.meta=tt.bytes();break}case 21:{ot.rateLimitProof=RateLimitProof.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.rateLimitProof});break}case 31:{ot.ephemeral=tt.bool();break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(WakuMessage||(WakuMessage={}));var PeerInfo;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.enr!=null&&(rt.uint32(10),rt.bytes(tt.enr)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.enr=tt.bytes();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PeerInfo||(PeerInfo={}));var PeerExchangeQuery;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.numPeers!=null&&(rt.uint32(8),rt.uint64(tt.numPeers)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.numPeers=tt.uint64();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PeerExchangeQuery||(PeerExchangeQuery={}));var PeerExchangeResponse;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.peerInfos!=null)for(const ot of tt.peerInfos)rt.uint32(10),PeerInfo.codec().encode(ot,rt);nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={peerInfos:[]},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{if(((st=nt.limits)==null?void 0:st.peerInfos)!=null&&ot.peerInfos.length===nt.limits.peerInfos)throw new MaxLengthError('Decode error - map field "peerInfos" had too many elements');ot.peerInfos.push(PeerInfo.codec().decode(tt,tt.uint32(),{limits:(at=nt.limits)==null?void 0:at.peerInfos$}));break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PeerExchangeResponse||(PeerExchangeResponse={}));var PeerExchangeRPC$1;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.query!=null&&(rt.uint32(10),PeerExchangeQuery.codec().encode(tt.query,rt)),tt.response!=null&&(rt.uint32(18),PeerExchangeResponse.codec().encode(tt.response,rt)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.query=PeerExchangeQuery.codec().decode(tt,tt.uint32(),{limits:(st=nt.limits)==null?void 0:st.query});break}case 2:{ot.response=PeerExchangeResponse.codec().decode(tt,tt.uint32(),{limits:(at=nt.limits)==null?void 0:at.response});break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PeerExchangeRPC$1||(PeerExchangeRPC$1={}));var WakuMetadataRequest;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.clusterId!=null&&(rt.uint32(8),rt.uint32(tt.clusterId)),tt.shards!=null)for(const ot of tt.shards)rt.uint32(16),rt.uint32(ot);nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={shards:[]},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.clusterId=tt.uint32();break}case 2:{if(((st=nt.limits)==null?void 0:st.shards)!=null&&ot.shards.length===nt.limits.shards)throw new MaxLengthError('Decode error - map field "shards" had too many elements');ot.shards.push(tt.uint32());break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(WakuMetadataRequest||(WakuMetadataRequest={}));var WakuMetadataResponse;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.clusterId!=null&&(rt.uint32(8),rt.uint32(tt.clusterId)),tt.shards!=null)for(const ot of tt.shards)rt.uint32(16),rt.uint32(ot);nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st;const ot={shards:[]},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.clusterId=tt.uint32();break}case 2:{if(((st=nt.limits)==null?void 0:st.shards)!=null&&ot.shards.length===nt.limits.shards)throw new MaxLengthError('Decode error - map field "shards" had too many elements');ot.shards.push(tt.uint32());break}default:{tt.skipType(at&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(WakuMetadataResponse||(WakuMetadataResponse={}));function isDefined(et){return!!et}function groupByContentTopic(et){const o=new Map;return et.forEach(tt=>{let rt=o.get(tt.contentTopic);rt||(o.set(tt.contentTopic,[]),rt=o.get(tt.contentTopic)),rt.push(tt)}),o}const FRAME_RATE=60;async function toAsyncIterator(et,o,tt){const rt=FRAME_RATE,nt=[];let ot;ot=await et.subscribeWithUnsubscribe(o,lt=>{nt.push(lt)});const it=Number.isInteger(tt==null?void 0:tt.timeoutMs),st=0,at=Date.now();async function*ct(){for(;;){if(it&&Date.now()-at>=st)return;await wait(rt);const lt=nt.shift();if(!ot&&nt.length===0)return lt;!lt&&ot||(yield lt)}}return{iterator:ct(),async stop(){ot&&(await ot(),ot=void 0)}}}function wait(et){return new Promise(o=>{setTimeout(o,et)})}const MB=1024**2,SIZE_CAP_IN_MB=1;async function isMessageSizeUnderCap(et,o){const tt=await et.toWire(o);return tt?isWireSizeUnderCap(tt):!1}const isWireSizeUnderCap=et=>et.length/MB<=SIZE_CAP_IN_MB;var Protocols;(function(et){et.Relay="relay",et.Store="store",et.LightPush="lightpush",et.Filter="filter"})(Protocols||(Protocols={}));var ProtocolError$1;(function(et){et.GENERIC_FAIL="Generic error",et.ENCODE_FAILED="Failed to encode",et.DECODE_FAILED="Failed to decode",et.EMPTY_PAYLOAD="Payload is empty",et.SIZE_TOO_BIG="Size is too big",et.TOPIC_NOT_CONFIGURED="Topic not configured",et.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",et.INVALID_DECODER_TOPICS="Invalid decoder topics",et.NO_PEER_AVAILABLE="No peer available",et.NO_STREAM_AVAILABLE="No stream available",et.NO_RESPONSE="No response received",et.REMOTE_PEER_REJECTED="Remote peer rejected",et.REQUEST_TIMEOUT="Request timeout",et.RLN_IDENTITY_MISSING="Identity credentials are not set",et.RLN_MEMBERSHIP_INDEX="Membership index is not set",et.RLN_LIMIT_MISSING="User message limit is not set",et.RLN_PROOF_GENERATION="Proof generation failed"})(ProtocolError$1||(ProtocolError$1={}));var Tags;(function(et){et.BOOTSTRAP="bootstrap",et.PEER_EXCHANGE="peer-exchange",et.LOCAL="local-peer-cache"})(Tags||(Tags={}));var EPeersByDiscoveryEvents;(function(et){et.PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",et.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",et.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",et.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange"})(EPeersByDiscoveryEvents||(EPeersByDiscoveryEvents={}));var EConnectionStateEvents;(function(et){et.CONNECTION_STATUS="waku:connection"})(EConnectionStateEvents||(EConnectionStateEvents={}));const DNS_DISCOVERY_TAG="@waku/bootstrap",DEFAULT_CLUSTER_ID=1,DefaultShardInfo={clusterId:DEFAULT_CLUSTER_ID,shards:[0,1,2,3,4,5,6,7,8]},DefaultNetworkConfig=DefaultShardInfo;var HealthStatus;(function(et){et.Unhealthy="Unhealthy",et.MinimallyHealthy="MinimallyHealthy",et.SufficientlyHealthy="SufficientlyHealthy"})(HealthStatus||(HealthStatus={}));function coerce$k(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$u(et){return new TextEncoder().encode(et)}function toString$w(et){return new TextDecoder().decode(et)}function base$k(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$k=base$k,_brrp__multiformats_scope_baseX$j=src$k;let Encoder$l=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$l=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$l(this,o)}},ComposedDecoder$j=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$l(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$l(et,o){return new ComposedDecoder$j({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$j=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$l(o,tt,rt),this.decoder=new Decoder$l(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$m({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$j(et,o,tt,rt)}function baseX$j({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$j(tt,et);return from$m({prefix:o,name:et,encode:rt,decode:ot=>coerce$k(nt(ot))})}function decode$W(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$M(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$f=alphabet$f.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$L(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$f[tt],o),"")}function decode$V(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$f[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$u=from$m({prefix:"🚀",name:"base256emoji",encode:encode$L,decode:decode$V}),base256emoji$v=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$u},Symbol.toStringTag,{value:"Module"})),base32$y=rfc4648$i({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$f=rfc4648$i({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$f=rfc4648$i({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$f=rfc4648$i({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$f=rfc4648$i({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$f=rfc4648$i({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$f=rfc4648$i({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$f=rfc4648$i({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$f=rfc4648$i({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$z=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$y,base32hex:base32hex$f,base32hexpad:base32hexpad$f,base32hexpadupper:base32hexpadupper$f,base32hexupper:base32hexupper$f,base32pad:base32pad$f,base32padupper:base32padupper$f,base32upper:base32upper$f,base32z:base32z$f},Symbol.toStringTag,{value:"Module"})),base36$v=baseX$j({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$f=baseX$j({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$w=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$v,base36upper:base36upper$f},Symbol.toStringTag,{value:"Module"})),base58btc$j=baseX$j({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$f=baseX$j({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$f=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$j,base58flickr:base58flickr$f},Symbol.toStringTag,{value:"Module"})),base64$x=rfc4648$i({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$f=rfc4648$i({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$g=rfc4648$i({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$f=rfc4648$i({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$y=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$x,base64pad:base64pad$f,base64url:base64url$g,base64urlpad:base64urlpad$f},Symbol.toStringTag,{value:"Module"})),base8$u=rfc4648$i({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$v=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$u},Symbol.toStringTag,{value:"Module"})),identity$h=from$m({prefix:"\0",name:"identity",encode:et=>toString$w(et),decode:et=>fromString$u(et)}),identityBase$f=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$h},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$f={...identityBase$f,...base2$v,...base8$v,...base10$v,...base16$v,...base32$z,...base36$w,...base58$f,...base64$y,...base256emoji$v};function allocUnsafe$g(et=0){return new Uint8Array(et)}function createCodec$f(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$j=createCodec$f("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$f=createCodec$f("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$g(et.length);for(let tt=0;tttoString$v(et,"base16"),bytesToUtf8=et=>toString$v(et,"utf8"),utf8ToBytes$1=et=>fromString$t(et,"utf8");function concat$5(et,o){const tt=et.reduce((ot,it)=>ot+it.length,0),rt=new Uint8Array(tt);let nt=0;for(const ot of et)rt.set(ot,nt),nt+=ot.length;return rt}function isStaticSharding(et){return"clusterId"in et&&"shards"in et&&!("contentTopics"in et)}function isAutoSharding(et){return"contentTopics"in et}function derivePubsubTopicsFromNetworkConfig(et){if(isStaticSharding(et)){if(et.shards.length===0)throw new Error("Invalid shards configuration: please provide at least one shard");return shardInfoToPubsubTopics(et)}else if(isAutoSharding(et)){if(et.contentTopics.length===0)throw new Error("Invalid content topics configuration: please provide at least one content topic");return et.contentTopics.map(o=>contentTopicToPubsubTopic(o,et.clusterId))}else throw new Error("Unknown shard config. Please use ShardInfo or ContentTopicInfo")}const singleShardInfoToPubsubTopic=et=>{if(et.shard===void 0)throw new Error("Invalid shard");return`/waku/2/rs/${et.clusterId??DEFAULT_CLUSTER_ID}/${et.shard}`},shardInfoToPubsubTopics=et=>{if("contentTopics"in et&&et.contentTopics)return Array.from(new Set(et.contentTopics.map(o=>contentTopicToPubsubTopic(o,et.clusterId))));if("shards"in et){if(et.shards===void 0)throw new Error("Invalid shard");return Array.from(new Set(et.shards.map(o=>`/waku/2/rs/${et.clusterId??DEFAULT_CLUSTER_ID}/${o}`)))}else{if("application"in et&&"version"in et)return[contentTopicToPubsubTopic(`/${et.application}/${et.version}/default/default`,et.clusterId)];throw new Error("Missing required configuration in shard parameters")}},pubsubTopicToSingleShardInfo=et=>{const o=et.split("/");if(o.length!=6||o[1]!=="waku"||o[2]!=="2"||o[3]!=="rs")throw new Error("Invalid pubsub topic");const tt=parseInt(o[4]),rt=parseInt(o[5]);if(isNaN(tt)||isNaN(rt))throw new Error("Invalid clusterId or shard");return{clusterId:tt,shard:rt}},pubsubTopicsToShardInfo=et=>{const o=new Set,tt=new Set;for(const ot of et){const{clusterId:it,shard:st}=pubsubTopicToSingleShardInfo(ot);o.add(`${it}:${st}`),tt.add(it)}if(o.size===0)throw new Error("No valid pubsub topics provided");if(tt.size>1)throw new Error("Pubsub topics from multiple cluster IDs are not supported");const rt=tt.values().next().value,nt=Array.from(o).map(ot=>parseInt(ot.split(":")[1]));return{clusterId:rt,shards:nt}};function ensurePubsubTopicIsConfigured(et,o){if(!o.includes(et))throw new Error(`Pubsub topic ${et} has not been configured on this instance. Configured topics are: ${o}. Please update your configuration by passing in the topic during Waku node instantiation.`)}function ensureValidContentTopic(et){const o=et.split("/");if(o.length<5||o.length>6)throw Error("Content topic format is invalid");let tt=0;if(o.length==6){if(tt=parseInt(o[1]),isNaN(tt))throw new Error("Invalid generation field in content topic");if(tt>0)throw new Error("Generation greater than 0 is not supported")}const rt=o.splice(-4);if(rt[0].length==0)throw new Error("Application field cannot be empty");if(rt[1].length==0)throw new Error("Version field cannot be empty");if(rt[2].length==0)throw new Error("Topic name field cannot be empty");if(rt[3].length==0)throw new Error("Encoding field cannot be empty");return{generation:tt,application:rt[0],version:rt[1],topicName:rt[2],encoding:rt[3]}}function contentTopicToShardIndex(et,o=8){const{application:tt,version:rt}=ensureValidContentTopic(et),nt=sha256$3(concat$5([utf8ToBytes$1(tt),utf8ToBytes$1(rt)])),ot=new DataView(nt.buffer.slice(-8));return Number(ot.getBigUint64(0,!1)%BigInt(o))}function contentTopicToPubsubTopic(et,o=DEFAULT_CLUSTER_ID,tt=8){if(!et)throw Error("Content topic must be specified");const rt=contentTopicToShardIndex(et,tt);return`/waku/2/rs/${o}/${rt}`}function determinePubsubTopic(et,o){return typeof o=="string"?o:(o==null?void 0:o.shard)!==void 0?singleShardInfoToPubsubTopic(o):contentTopicToPubsubTopic(et,(o==null?void 0:o.clusterId)??DEFAULT_CLUSTER_ID)}const decodeRelayShard=et=>{if(et=new Uint8Array(et),et.length<3)throw new Error("Insufficient data");const o=new DataView(et.buffer),tt=o.getUint16(0),rt=[];if(et.length===130)for(let nt=0;nt<1024;nt++){const ot=Math.floor(nt/8)+2,it=7-nt%8;o.getUint8(ot)&1<=et.length)throw new Error("Unexpected end of data");rt.push(o.getUint16(it))}}return{clusterId:tt,shards:rt}},encodeRelayShard=et=>{const{clusterId:o,shards:tt}=et,rt=tt.length>=64?130:3+2*tt.length,nt=new ArrayBuffer(rt),ot=new DataView(nt);if(ot.setUint16(0,o),tt.length>=64)for(const it of tt){const st=Math.floor(it/8)+2,at=7-it%8;ot.setUint8(st,ot.getUint8(st)|1<tt.toString().includes("ws")||tt.toString().includes("wss"));if(!o)throw new Error("No ws multiaddr found in the given addresses");return o}var browser={exports:{}},ms$1,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms$1;hasRequiredMs=1;var et=1e3,o=et*60,tt=o*60,rt=tt*24,nt=rt*7,ot=rt*365.25;ms$1=function(lt,dt){dt=dt||{};var ht=typeof lt;if(ht==="string"&<.length>0)return it(lt);if(ht==="number"&&isFinite(lt))return dt.long?at(lt):st(lt);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(lt))};function it(lt){if(lt=String(lt),!(lt.length>100)){var dt=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(lt);if(dt){var ht=parseFloat(dt[1]),mt=(dt[2]||"ms").toLowerCase();switch(mt){case"years":case"year":case"yrs":case"yr":case"y":return ht*ot;case"weeks":case"week":case"w":return ht*nt;case"days":case"day":case"d":return ht*rt;case"hours":case"hour":case"hrs":case"hr":case"h":return ht*tt;case"minutes":case"minute":case"mins":case"min":case"m":return ht*o;case"seconds":case"second":case"secs":case"sec":case"s":return ht*et;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return ht;default:return}}}}function st(lt){var dt=Math.abs(lt);return dt>=rt?Math.round(lt/rt)+"d":dt>=tt?Math.round(lt/tt)+"h":dt>=o?Math.round(lt/o)+"m":dt>=et?Math.round(lt/et)+"s":lt+"ms"}function at(lt){var dt=Math.abs(lt);return dt>=rt?ct(lt,dt,rt,"day"):dt>=tt?ct(lt,dt,tt,"hour"):dt>=o?ct(lt,dt,o,"minute"):dt>=et?ct(lt,dt,et,"second"):lt+" ms"}function ct(lt,dt,ht,mt){var ft=dt>=ht*1.5;return Math.round(lt/ht)+" "+mt+(ft?"s":"")}return ms$1}function setup$1(et){tt.debug=tt,tt.default=tt,tt.coerce=at,tt.disable=ot,tt.enable=nt,tt.enabled=it,tt.humanize=requireMs(),tt.destroy=ct,Object.keys(et).forEach(lt=>{tt[lt]=et[lt]}),tt.names=[],tt.skips=[],tt.formatters={};function o(lt){let dt=0;for(let ht=0;ht{if(Ct==="%%")return"%";vt++;const At=tt.formatters[St];if(typeof At=="function"){const kt=gt[vt];Ct=At.call(yt,kt),gt.splice(vt,1),vt--}return Ct}),tt.formatArgs.call(yt,gt),(yt.log||tt.log).apply(yt,gt)}return pt.namespace=lt,pt.useColors=tt.useColors(),pt.color=tt.selectColor(lt),pt.extend=rt,pt.destroy=tt.destroy,Object.defineProperty(pt,"enabled",{enumerable:!0,configurable:!1,get:()=>ht!==null?ht:(mt!==tt.namespaces&&(mt=tt.namespaces,ft=tt.enabled(lt)),ft),set:gt=>{ht=gt}}),typeof tt.init=="function"&&tt.init(pt),pt}function rt(lt,dt){const ht=tt(this.namespace+(typeof dt>"u"?":":dt)+lt);return ht.log=this.log,ht}function nt(lt){tt.save(lt),tt.namespaces=lt,tt.names=[],tt.skips=[];let dt;const ht=(typeof lt=="string"?lt:"").split(/[\s,]+/),mt=ht.length;for(dt=0;dt"-"+dt)].join(",");return tt.enable(""),lt}function it(lt){if(lt[lt.length-1]==="*")return!0;let dt,ht;for(dt=0,ht=tt.skips.length;dt{let ct=!1;return()=>{ct||(ct=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),o.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function rt(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let ct;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(ct=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(ct[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function nt(ct){if(ct[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+ct[0]+(this.useColors?"%c ":" ")+"+"+et.exports.humanize(this.diff),!this.useColors)return;const lt="color: "+this.color;ct.splice(1,0,lt,"color: inherit");let dt=0,ht=0;ct[0].replace(/%[a-zA-Z%]/g,mt=>{mt!=="%%"&&(dt++,mt==="%c"&&(ht=dt))}),ct.splice(ht,0,lt)}o.log=console.debug||console.log||(()=>{});function ot(ct){try{ct?o.storage.setItem("debug",ct):o.storage.removeItem("debug")}catch{}}function it(){let ct;try{ct=o.storage.getItem("debug")}catch{}return!ct&&typeof process<"u"&&"env"in process&&(ct=tt.DEBUG),ct}function st(){try{return localStorage}catch{}}et.exports=common$1(o);const{formatters:at}=et.exports;at.j=function(ct){try{return JSON.stringify(ct)}catch(lt){return"[UnexpectedJSONParseError]: "+lt.message}}})(browser,browser.exports);var browserExports=browser.exports;const debug=getDefaultExportFromCjs(browserExports),APP_NAME="waku";let Logger$1=class Jo{constructor(o){wt(this,"_info");wt(this,"_warn");wt(this,"_error");this._info=debug(Jo.createDebugNamespace("info",o)),this._warn=debug(Jo.createDebugNamespace("warn",o)),this._error=debug(Jo.createDebugNamespace("error",o))}static createDebugNamespace(o,tt){return tt?`${APP_NAME}:${o}:${tt}`:`${APP_NAME}:${o}`}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(o,...tt){const rt=this[o];rt(...tt)}};const log$o=new Logger$1("message:version-0"),OneMillion=BigInt(1e6),Version=0;class DecodedMessage{constructor(o,tt){wt(this,"pubsubTopic");wt(this,"proto");this.pubsubTopic=o,this.proto=tt}get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get _rawTimestamp(){return this.proto.timestamp}get timestamp(){try{if(this.proto.timestamp){const o=this.proto.timestamp/OneMillion;return new Date(Number(o))}return}catch{return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}let Encoder$k=class{constructor(o,tt=!1,rt,nt){wt(this,"contentTopic");wt(this,"ephemeral");wt(this,"pubsubTopic");wt(this,"metaSetter");if(this.contentTopic=o,this.ephemeral=tt,this.pubsubTopic=rt,this.metaSetter=nt,!o||o==="")throw new Error("Content topic must be specified")}async toWire(o){return WakuMessage$4.encode(await this.toProtoObj(o))}async toProtoObj(o){const tt=o.timestamp??new Date,rt={payload:o.payload,version:Version,contentTopic:this.contentTopic,timestamp:BigInt(tt.valueOf())*OneMillion,meta:void 0,rateLimitProof:o.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const nt=this.metaSetter(rt);return{...rt,meta:nt}}return rt}};function createEncoder({pubsubTopic:et,pubsubTopicShardInfo:o,contentTopic:tt,ephemeral:rt,metaSetter:nt}){return new Encoder$k(tt,rt,determinePubsubTopic(tt,et??o),nt)}let Decoder$k=class{constructor(o,tt){wt(this,"pubsubTopic");wt(this,"contentTopic");if(this.pubsubTopic=o,this.contentTopic=tt,!tt||tt==="")throw new Error("Content topic must be specified")}fromWireToProtoObj(o){const tt=WakuMessage$4.decode(o);return Promise.resolve({payload:tt.payload,contentTopic:tt.contentTopic,version:tt.version??void 0,timestamp:tt.timestamp??void 0,meta:tt.meta??void 0,rateLimitProof:tt.rateLimitProof??void 0,ephemeral:tt.ephemeral??!1})}async fromProtoObj(o,tt){return tt.version??Version!==0?(log$o.error("Failed to decode due to incorrect version, expected:",Version,", actual:",tt.version),Promise.resolve(void 0)):new DecodedMessage(o,tt)}};function createDecoder(et,o){return new Decoder$k(determinePubsubTopic(et,o),et)}function isAsyncIterable$8(et){return et[Symbol.asyncIterator]!=null}function all$2(et){if(isAsyncIterable$8(et))return(async()=>{const tt=[];for await(const rt of et)tt.push(rt);return tt})();const o=[];for(const tt of et)o.push(tt);return o}function alloc$5(et=0){return new Uint8Array(et)}function allocUnsafe$f(et=0){return new Uint8Array(et)}function asUint8Array$3(et){return et}function concat$4(et,o){o==null&&(o=et.reduce((nt,ot)=>nt+ot.length,0));const tt=allocUnsafe$f(o);let rt=0;for(const nt of et)tt.set(nt,rt),rt+=nt.length;return tt}function equals$f(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;tt0&&this.appendAll(o)}*[(Ys=symbol$1,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...o){this.appendAll(o)}appendAll(o){let tt=0;for(const rt of o)if(rt instanceof Uint8Array)tt+=rt.byteLength,this.bufs.push(rt);else if(isUint8ArrayList(rt))tt+=rt.byteLength,this.bufs.push(...rt.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=tt}prepend(...o){this.prependAll(o)}prependAll(o){let tt=0;for(const rt of o.reverse())if(rt instanceof Uint8Array)tt+=rt.byteLength,this.bufs.unshift(rt);else if(isUint8ArrayList(rt))tt+=rt.byteLength,this.bufs.unshift(...rt.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=tt}get(o){const tt=findBufAndOffset(this.bufs,o);return tt.buf[tt.index]}set(o,tt){const rt=findBufAndOffset(this.bufs,o);rt.buf[rt.index]=tt}write(o,tt=0){if(o instanceof Uint8Array)for(let rt=0;rt0;)if(o>=this.bufs[0].byteLength)o-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(o),this.length-=o;break}}}slice(o,tt){const{bufs:rt,length:nt}=this._subList(o,tt);return concat$4(rt,nt)}subarray(o,tt){const{bufs:rt,length:nt}=this._subList(o,tt);return rt.length===1?rt[0]:concat$4(rt,nt)}sublist(o,tt){const{bufs:rt,length:nt}=this._subList(o,tt),ot=new Uint8ArrayList;return ot.length=nt,ot.bufs=[...rt],ot}_subList(o,tt){if(o=o??0,tt=tt??this.length,o<0&&(o=this.length+o),tt<0&&(tt=this.length+tt),o<0||tt>this.length)throw new RangeError("index is out of bounds");if(o===tt)return{bufs:[],length:0};if(o===0&&tt===this.length)return{bufs:this.bufs,length:this.length};const rt=[];let nt=0;for(let ot=0;ot=at)continue;const ct=o>=st&&ost&&tt<=at;if(ct&<){if(o===st&&tt===at){rt.push(it);break}const dt=o-st;rt.push(it.subarray(dt,dt+(tt-o)));break}if(ct){if(o===0){rt.push(it);continue}rt.push(it.subarray(o-st));continue}if(lt){if(tt===at){rt.push(it);break}rt.push(it.subarray(0,tt-st));break}rt.push(it)}return{bufs:rt,length:tt-o}}indexOf(o,tt=0){if(!isUint8ArrayList(o)&&!(o instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const rt=o instanceof Uint8Array?o:o.subarray();if(tt=Number(tt??0),isNaN(tt)&&(tt=0),tt<0&&(tt=this.length+tt),tt<0&&(tt=0),o.length===0)return tt>this.length?this.length:tt;const nt=rt.byteLength;if(nt===0)throw new TypeError("search must be at least 1 byte long");const ot=256,it=new Int32Array(ot);for(let dt=0;dt=0;ht--){const mt=this.get(dt+ht);if(rt[ht]!==mt){lt=Math.max(1,ht-st[mt]);break}}if(lt===0)return dt}return-1}getInt8(o){const tt=this.subarray(o,o+1);return new DataView(tt.buffer,tt.byteOffset,tt.byteLength).getInt8(0)}setInt8(o,tt){const rt=allocUnsafe$f(1);new DataView(rt.buffer,rt.byteOffset,rt.byteLength).setInt8(0,tt),this.write(rt,o)}getInt16(o,tt){const rt=this.subarray(o,o+2);return new DataView(rt.buffer,rt.byteOffset,rt.byteLength).getInt16(0,tt)}setInt16(o,tt,rt){const nt=alloc$5(2);new DataView(nt.buffer,nt.byteOffset,nt.byteLength).setInt16(0,tt,rt),this.write(nt,o)}getInt32(o,tt){const rt=this.subarray(o,o+4);return new DataView(rt.buffer,rt.byteOffset,rt.byteLength).getInt32(0,tt)}setInt32(o,tt,rt){const nt=alloc$5(4);new DataView(nt.buffer,nt.byteOffset,nt.byteLength).setInt32(0,tt,rt),this.write(nt,o)}getBigInt64(o,tt){const rt=this.subarray(o,o+8);return new DataView(rt.buffer,rt.byteOffset,rt.byteLength).getBigInt64(0,tt)}setBigInt64(o,tt,rt){const nt=alloc$5(8);new DataView(nt.buffer,nt.byteOffset,nt.byteLength).setBigInt64(0,tt,rt),this.write(nt,o)}getUint8(o){const tt=this.subarray(o,o+1);return new DataView(tt.buffer,tt.byteOffset,tt.byteLength).getUint8(0)}setUint8(o,tt){const rt=allocUnsafe$f(1);new DataView(rt.buffer,rt.byteOffset,rt.byteLength).setUint8(0,tt),this.write(rt,o)}getUint16(o,tt){const rt=this.subarray(o,o+2);return new DataView(rt.buffer,rt.byteOffset,rt.byteLength).getUint16(0,tt)}setUint16(o,tt,rt){const nt=alloc$5(2);new DataView(nt.buffer,nt.byteOffset,nt.byteLength).setUint16(0,tt,rt),this.write(nt,o)}getUint32(o,tt){const rt=this.subarray(o,o+4);return new DataView(rt.buffer,rt.byteOffset,rt.byteLength).getUint32(0,tt)}setUint32(o,tt,rt){const nt=alloc$5(4);new DataView(nt.buffer,nt.byteOffset,nt.byteLength).setUint32(0,tt,rt),this.write(nt,o)}getBigUint64(o,tt){const rt=this.subarray(o,o+8);return new DataView(rt.buffer,rt.byteOffset,rt.byteLength).getBigUint64(0,tt)}setBigUint64(o,tt,rt){const nt=alloc$5(8);new DataView(nt.buffer,nt.byteOffset,nt.byteLength).setBigUint64(0,tt,rt),this.write(nt,o)}getFloat32(o,tt){const rt=this.subarray(o,o+4);return new DataView(rt.buffer,rt.byteOffset,rt.byteLength).getFloat32(0,tt)}setFloat32(o,tt,rt){const nt=alloc$5(4);new DataView(nt.buffer,nt.byteOffset,nt.byteLength).setFloat32(0,tt,rt),this.write(nt,o)}getFloat64(o,tt){const rt=this.subarray(o,o+8);return new DataView(rt.buffer,rt.byteOffset,rt.byteLength).getFloat64(0,tt)}setFloat64(o,tt,rt){const nt=alloc$5(8);new DataView(nt.buffer,nt.byteOffset,nt.byteLength).setFloat64(0,tt,rt),this.write(nt,o)}equals(o){if(o==null||!(o instanceof Uint8ArrayList)||o.bufs.length!==this.bufs.length)return!1;for(let tt=0;ttnt+ot.byteLength,0)),rt.length=tt,rt}}function allocUnsafe$e(et=0){return new Uint8Array(et)}function isAsyncIterable$7(et){return et[Symbol.asyncIterator]!=null}const defaultEncoder=et=>{const o=encodingLength$6(et),tt=allocUnsafe$e(o);return encode$P(et,tt),defaultEncoder.bytes=o,tt};defaultEncoder.bytes=0;function encode$K(et,o){o=o??{};const tt=o.lengthEncoder??defaultEncoder;function*rt(nt){const ot=tt(nt.byteLength);ot instanceof Uint8Array?yield ot:yield*ot,nt instanceof Uint8Array?yield nt:yield*nt}return isAsyncIterable$7(et)?async function*(){for await(const nt of et)yield*rt(nt)}():function*(){for(const nt of et)yield*rt(nt)}()}encode$K.single=(et,o)=>{o=o??{};const tt=o.lengthEncoder??defaultEncoder;return new Uint8ArrayList(tt(et.byteLength),et)};let InvalidMessageLengthError$1=class extends Error{constructor(){super(...arguments);wt(this,"name","InvalidMessageLengthError");wt(this,"code","ERR_INVALID_MSG_LENGTH")}},InvalidDataLengthError$1=class extends Error{constructor(){super(...arguments);wt(this,"name","InvalidDataLengthError");wt(this,"code","ERR_MSG_DATA_TOO_LONG")}},InvalidDataLengthLengthError$1=class extends Error{constructor(){super(...arguments);wt(this,"name","InvalidDataLengthLengthError");wt(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},UnexpectedEOFError$1=class extends Error{constructor(){super(...arguments);wt(this,"name","UnexpectedEOFError");wt(this,"code","ERR_UNEXPECTED_EOF")}};const MAX_LENGTH_LENGTH=8,MAX_DATA_LENGTH=1024*1024*4;var ReadMode;(function(et){et[et.LENGTH=0]="LENGTH",et[et.DATA=1]="DATA"})(ReadMode||(ReadMode={}));const defaultDecoder=et=>{const o=decode$Z(et);return defaultDecoder.bytes=encodingLength$6(o),o};defaultDecoder.bytes=0;function decode$U(et,o){const tt=new Uint8ArrayList;let rt=ReadMode.LENGTH,nt=-1;const ot=(o==null?void 0:o.lengthDecoder)??defaultDecoder,it=(o==null?void 0:o.maxLengthLength)??MAX_LENGTH_LENGTH,st=(o==null?void 0:o.maxDataLength)??MAX_DATA_LENGTH;function*at(){for(;tt.byteLength>0;){if(rt===ReadMode.LENGTH)try{if(nt=ot(tt),nt<0)throw new InvalidMessageLengthError$1("Invalid message length");if(nt>st)throw new InvalidDataLengthError$1("Message length too long");const ct=ot.bytes;tt.consume(ct),(o==null?void 0:o.onLength)!=null&&o.onLength(nt),rt=ReadMode.DATA}catch(ct){if(ct instanceof RangeError){if(tt.byteLength>it)throw new InvalidDataLengthLengthError$1("Message length length too long");break}throw ct}if(rt===ReadMode.DATA){if(tt.byteLength0)throw new UnexpectedEOFError$1("Unexpected end of input")}():function*(){for(const ct of et)tt.append(ct),yield*at();if(tt.byteLength>0)throw new UnexpectedEOFError$1("Unexpected end of input")}()}decode$U.fromReader=(et,o)=>{let tt=1;const rt=async function*(){for(;;)try{const{done:ot,value:it}=await et.next(tt);if(ot===!0)return;it!=null&&(yield it)}catch(ot){if(ot.code==="ERR_UNDER_READ")return{done:!0,value:null};throw ot}finally{tt=1}}();return decode$U(rt,{...o??{},onLength:ot=>{tt=ot}})};function pDefer(){const et={};return et.promise=new Promise((o,tt)=>{et.resolve=o,et.reject=tt}),et}class FixedFIFO{constructor(o){wt(this,"buffer");wt(this,"mask");wt(this,"top");wt(this,"btm");wt(this,"next");if(!(o>0)||o-1&o)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(o),this.mask=o-1,this.top=0,this.btm=0,this.next=null}push(o){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=o,this.top=this.top+1&this.mask,!0)}shift(){const o=this.buffer[this.btm];if(o!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,o}isEmpty(){return this.buffer[this.btm]===void 0}}class FIFO{constructor(o={}){wt(this,"size");wt(this,"hwm");wt(this,"head");wt(this,"tail");this.hwm=o.splitLimit??16,this.head=new FixedFIFO(this.hwm),this.tail=this.head,this.size=0}calculateSize(o){return(o==null?void 0:o.byteLength)!=null?o.byteLength:1}push(o){if((o==null?void 0:o.value)!=null&&(this.size+=this.calculateSize(o.value)),!this.head.push(o)){const tt=this.head;this.head=tt.next=new FixedFIFO(2*this.head.buffer.length),this.head.push(o)}}shift(){let o=this.tail.shift();if(o===void 0&&this.tail.next!=null){const tt=this.tail.next;this.tail.next=null,this.tail=tt,o=this.tail.shift()}return(o==null?void 0:o.value)!=null&&(this.size-=this.calculateSize(o.value)),o}isEmpty(){return this.head.isEmpty()}}let AbortError$a=class extends Error{constructor(tt,rt){super(tt??"The operation was aborted");wt(this,"type");wt(this,"code");this.type="aborted",this.code=rt??"ABORT_ERR"}};function pushable(et={}){return _pushable(tt=>{const rt=tt.shift();if(rt==null)return{done:!0};if(rt.error!=null)throw rt.error;return{done:rt.done===!0,value:rt.value}},et)}function _pushable(et,o){o=o??{};let tt=o.onEnd,rt=new FIFO,nt,ot,it,st=pDefer();const at=async()=>{try{return rt.isEmpty()?it?{done:!0}:await new Promise((gt,yt)=>{ot=bt=>{ot=null,rt.push(bt);try{gt(et(rt))}catch(xt){yt(xt)}return nt}}):et(rt)}finally{rt.isEmpty()&&queueMicrotask(()=>{st.resolve(),st=pDefer()})}},ct=gt=>ot!=null?ot(gt):(rt.push(gt),nt),lt=gt=>(rt=new FIFO,ot!=null?ot({error:gt}):(rt.push({error:gt}),nt)),dt=gt=>{if(it)return nt;if((o==null?void 0:o.objectMode)!==!0&&(gt==null?void 0:gt.byteLength)==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return ct({done:!1,value:gt})},ht=gt=>it?nt:(it=!0,gt!=null?lt(gt):ct({done:!0})),mt=()=>(rt=new FIFO,ht(),{done:!0}),ft=gt=>(ht(gt),{done:!0});if(nt={[Symbol.asyncIterator](){return this},next:at,return:mt,throw:ft,push:dt,end:ht,get readableLength(){return rt.size},onEmpty:async gt=>{const yt=gt==null?void 0:gt.signal;if(yt==null||yt.throwIfAborted(),rt.isEmpty())return;let bt,xt;yt!=null&&(bt=new Promise((vt,Et)=>{xt=()=>{Et(new AbortError$a)},yt.addEventListener("abort",xt)}));try{await Promise.race([st.promise,bt])}finally{xt!=null&&yt!=null&&(yt==null||yt.removeEventListener("abort",xt))}}},tt==null)return nt;const pt=nt;return nt={[Symbol.asyncIterator](){return this},next(){return pt.next()},throw(gt){return pt.throw(gt),tt!=null&&(tt(gt),tt=void 0),{done:!0}},return(){return pt.return(),tt!=null&&(tt(),tt=void 0),{done:!0}},push:dt,end(gt){return pt.end(gt),tt!=null&&(tt(gt),tt=void 0),nt},get readableLength(){return pt.readableLength},onEmpty:gt=>pt.onEmpty(gt)},nt}function isAsyncIterable$6(et){return et[Symbol.asyncIterator]!=null}function merge$2(...et){const o=[];for(const tt of et)isAsyncIterable$6(tt)||o.push(tt);return o.length===et.length?function*(){for(const tt of o)yield*tt}():async function*(){const tt=pushable({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(et.map(async rt=>{for await(const nt of rt)tt.push(nt)})),tt.end()}catch(rt){tt.end(rt)}}),yield*tt}()}function pipe(et,...o){if(et==null)throw new Error("Empty pipeline");if(isDuplex(et)){const rt=et;et=()=>rt.source}else if(isIterable(et)||isAsyncIterable$5(et)){const rt=et;et=()=>rt}const tt=[et,...o];if(tt.length>1&&isDuplex(tt[tt.length-1])&&(tt[tt.length-1]=tt[tt.length-1].sink),tt.length>2)for(let rt=1;rt{let o;for(;et.length>0;)o=et.shift()(o);return o},isAsyncIterable$5=et=>(et==null?void 0:et[Symbol.asyncIterator])!=null,isIterable=et=>(et==null?void 0:et[Symbol.iterator])!=null,isDuplex=et=>et==null?!1:et.sink!=null&&et.source!=null,duplexPipelineFn=et=>o=>{const tt=et.sink(o);if((tt==null?void 0:tt.then)!=null){const rt=pushable({objectMode:!0});tt.then(()=>{rt.end()},it=>{rt.end(it)});let nt;const ot=et.source;if(isAsyncIterable$5(ot))nt=async function*(){yield*ot,rt.end()};else if(isIterable(ot))nt=function*(){yield*ot,rt.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return merge$2(rt,nt())}return et.source};async function sortPeersByLatency(et,o){return o.length===0?[]:(await Promise.all(o.map(async nt=>{try{const ot=(await et.get(nt.id)).metadata.get("ping");if(!ot)return{peer:nt,ping:1/0};const it=Number(bytesToUtf8(ot));return{peer:nt,ping:it}}catch{return{peer:nt,ping:1/0}}}))).filter(nt=>nt!==null).sort((nt,ot)=>nt.ping-ot.ping).map(nt=>nt.peer)}async function getPeersForProtocol(et,o){const tt=[];return await et.forEach(rt=>{for(let nt=0;ntit.tags.has(Tags.BOOTSTRAP)).slice(0,tt);o>0&&o!it.tags.has(Tags.BOOTSTRAP));if(o===0)return[...rt,...nt];const ot=[...rt];for(;ot.length0;){const it=Math.floor(Math.random()*nt.length),st=nt.splice(it,1)[0];ot.push(st)}return ot}function selectOpenConnection(et){return et.filter(o=>o.status==="open").sort((o,tt)=>tt.timeline.open-o.timeline.open).at(0)}const STREAM_LOCK_KEY="consumed";class StreamManager{constructor(o,tt,rt){wt(this,"multicodec");wt(this,"getConnections");wt(this,"addEventListener");wt(this,"log");wt(this,"ongoingCreation",new Set);wt(this,"streamPool",new Map);wt(this,"handlePeerUpdateStreamPool",o=>{const{peer:tt}=o.detail;!tt.protocols.includes(this.multicodec)||this.getOpenStreamForCodec(tt.id)||this.scheduleNewStream(tt)});this.multicodec=o,this.getConnections=tt,this.addEventListener=rt,this.log=new Logger$1(`stream-manager:${o}`),this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(o){const tt=o.id.toString(),rt=this.streamPool.get(tt);rt&&(this.streamPool.delete(tt),await rt);let nt=this.getOpenStreamForCodec(o.id);return nt?(this.log.info(`Found existing stream peerId=${o.id.toString()} multicodec=${this.multicodec}`),this.lockStream(o.id.toString(),nt),nt):(nt=await this.createStream(o),this.lockStream(o.id.toString(),nt),nt)}async createStream(o,tt=0){const rt=this.getConnections(o.id),nt=selectOpenConnection(rt);if(!nt)throw new Error(`Failed to get a connection to the peer peerId=${o.id.toString()} multicodec=${this.multicodec}`);let ot,it;for(let st=0;stit.protocol===this.multicodec);if(!(!nt||["done","closed","closing"].includes(nt.writeStatus||"")||this.isStreamLocked(nt)))return nt}lockStream(o,tt){this.log.info(`Locking stream for peerId:${o} streamId:${tt.id}`),tt.metadata[STREAM_LOCK_KEY]=!0}isStreamLocked(o){return!!o.metadata[STREAM_LOCK_KEY]}}class BaseProtocol{constructor(o,tt,rt,nt){wt(this,"multicodec");wt(this,"components");wt(this,"log");wt(this,"pubsubTopics");wt(this,"addLibp2pEventListener");wt(this,"removeLibp2pEventListener");wt(this,"streamManager");this.multicodec=o,this.components=tt,this.log=rt,this.pubsubTopics=nt,this.addLibp2pEventListener=tt.events.addEventListener.bind(tt.events),this.removeLibp2pEventListener=tt.events.removeEventListener.bind(tt.events),this.streamManager=new StreamManager(o,tt.connectionManager.getConnections.bind(tt.connectionManager),this.addLibp2pEventListener)}async getStream(o){return this.streamManager.getStream(o)}async allPeers(){return getPeersForProtocol(this.components.peerStore,[this.multicodec])}async connectedPeers(){return(await this.allPeers()).filter(tt=>this.components.connectionManager.getConnections(tt.id).length>0)}async getPeers({numPeers:o,maxBootstrapPeers:tt,peerIdStr:rt}={maxBootstrapPeers:0,numPeers:0}){if(rt){const st=(await this.connectedPeers()).find(at=>at.id.toString()===rt);return st?[st]:(this.log.warn(`Passed node to use for ${this.multicodec} not found: ${rt}. Attempting to use random peers.`),this.getPeers({numPeers:o,maxBootstrapPeers:tt}))}const nt=await this.connectedPeers(),ot=filterPeersByDiscovery(nt,o,tt),it=await sortPeersByLatency(this.components.peerStore,ot);return it.length===0&&this.log.warn("No peers found. Ensure you have a connection to the network."),it.length{log$n.error("Failed to register ",FilterCodecs.PUSH,ot)})}async subscribe(tt,rt,nt){const ot=await this.getStream(rt),it=FilterSubscribeRpc.createSubscribeRequest(tt,nt);let st;try{st=await pipe([it.encode()],encode$K,ot,decode$U,async dt=>await all$2(dt))}catch(dt){return log$n.error("Failed to send subscribe request",dt),{success:null,failure:{error:ProtocolError$1.GENERIC_FAIL,peerId:rt.id}}}const{statusCode:at,requestId:ct,statusDesc:lt}=FilterSubscribeResponse.decode(st[0].slice());return at<200||at>=300?(log$n.error(`Filter subscribe request ${ct} failed with status code ${at}: ${lt}`),{failure:{error:ProtocolError$1.REMOTE_PEER_REJECTED,peerId:rt.id},success:null}):{failure:null,success:rt.id}}async unsubscribe(tt,rt,nt){let ot;try{ot=await this.getStream(rt)}catch(st){return log$n.error(`Failed to get a stream for remote peer${rt.id.toString()}`,st),{success:null,failure:{error:ProtocolError$1.NO_STREAM_AVAILABLE,peerId:rt.id}}}const it=FilterSubscribeRpc.createUnsubscribeRequest(tt,nt);try{await pipe([it.encode()],encode$K,ot.sink)}catch(st){return log$n.error("Failed to send unsubscribe request",st),{success:null,failure:{error:ProtocolError$1.GENERIC_FAIL,peerId:rt.id}}}return{success:rt.id,failure:null}}async unsubscribeAll(tt,rt){const nt=await this.getStream(rt),ot=FilterSubscribeRpc.createUnsubscribeAllRequest(tt),it=await pipe([ot.encode()],encode$K,nt,decode$U,async lt=>await all$2(lt));if(!it||!it.length)return{failure:{error:ProtocolError$1.NO_RESPONSE,peerId:rt.id},success:null};const{statusCode:st,requestId:at,statusDesc:ct}=FilterSubscribeResponse.decode(it[0].slice());return st<200||st>=300?(log$n.error(`Filter unsubscribe all request ${at} failed with status code ${st}: ${ct}`),{failure:{error:ProtocolError$1.REMOTE_PEER_REJECTED,peerId:rt.id},success:null}):{failure:null,success:rt.id}}async ping(tt){let rt;try{rt=await this.getStream(tt)}catch(ct){return log$n.error(`Failed to get a stream for remote peer${tt.id.toString()}`,ct),{success:null,failure:{error:ProtocolError$1.NO_STREAM_AVAILABLE,peerId:tt.id}}}const nt=FilterSubscribeRpc.createSubscriberPingRequest();let ot;try{ot=await pipe([nt.encode()],encode$K,rt,decode$U,async ct=>await all$2(ct))}catch(ct){return log$n.error("Failed to send ping request",ct),{success:null,failure:{error:ProtocolError$1.GENERIC_FAIL,peerId:tt.id}}}if(!ot||!ot.length)return{success:null,failure:{error:ProtocolError$1.NO_RESPONSE,peerId:tt.id}};const{statusCode:it,requestId:st,statusDesc:at}=FilterSubscribeResponse.decode(ot[0].slice());return it<200||it>=300?(log$n.error(`Filter ping request ${st} failed with status code ${it}: ${at}`),{success:null,failure:{error:ProtocolError$1.REMOTE_PEER_REJECTED,peerId:tt.id}}):{success:tt.id,failure:null}}onRequest(tt){const{connection:rt,stream:nt}=tt,{remotePeer:ot}=rt;log$n.info(`Received message from ${ot.toString()}`);try{pipe(nt,decode$U,async it=>{for await(const st of it){const at=FilterPushRpc.decode(st.slice()),{pubsubTopic:ct,wakuMessage:lt}=at;if(!lt){log$n.error("Received empty message");return}if(!ct){log$n.error("Pubsub topic missing from push message");return}await this.handleIncomingMessage(ct,lt,rt.remotePeer.toString())}}).then(()=>{log$n.info("Receiving pipe closed.")},async it=>{log$n.error(`Error with receiving pipe on peer:${rt.remotePeer.toString()} -- stream:${nt.id} -- protocol:${nt.protocol}: `,it)})}catch(it){log$n.error("Error decoding message",it)}}}class PushRpc{constructor(o){wt(this,"proto");this.proto=o}static createRequest(o,tt){return new PushRpc({requestId:v4$2(),request:{message:o,pubsubTopic:tt},response:void 0})}static decode(o){const tt=PushRpc$1.decode(o);return new PushRpc(tt)}encode(){return PushRpc$1.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const RLN_GENERATION_PREFIX_ERROR="could not generate rln-v2 proof",isRLNResponseError=et=>et?et.includes(RLN_GENERATION_PREFIX_ERROR):!1,matchRLNErrorMessage=et=>{const o={[ProtocolError$1.RLN_IDENTITY_MISSING]:ProtocolError$1.RLN_IDENTITY_MISSING,[ProtocolError$1.RLN_MEMBERSHIP_INDEX]:ProtocolError$1.RLN_MEMBERSHIP_INDEX,[ProtocolError$1.RLN_LIMIT_MISSING]:ProtocolError$1.RLN_LIMIT_MISSING},tt=et.toLowerCase();for(const rt in o)if(tt.includes(rt.toLowerCase()))return o[rt];return ProtocolError$1.RLN_PROOF_GENERATION},log$m=new Logger$1("light-push"),LightPushCodec="/vac/waku/lightpush/2.0.0-beta1";class LightPushCore extends BaseProtocol{constructor(tt,rt){super(LightPushCodec,rt.components,log$m,tt);wt(this,"pubsubTopics");this.pubsubTopics=tt}async preparePushMessage(tt,rt){try{if(!rt.payload||rt.payload.length===0)return log$m.error("Failed to send waku light push: payload is empty"),{query:null,error:ProtocolError$1.EMPTY_PAYLOAD};if(!await isMessageSizeUnderCap(tt,rt))return log$m.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:ProtocolError$1.SIZE_TOO_BIG};const nt=await tt.toProtoObj(rt);return nt?{query:PushRpc.createRequest(nt,tt.pubsubTopic),error:null}:(log$m.error("Failed to encode to protoMessage, aborting push"),{query:null,error:ProtocolError$1.ENCODE_FAILED})}catch(nt){return log$m.error("Failed to prepare push message",nt),{query:null,error:ProtocolError$1.GENERIC_FAIL}}}async send(tt,rt,nt){const{query:ot,error:it}=await this.preparePushMessage(tt,rt);if(it||!ot)return{success:null,failure:{error:it,peerId:nt.id}};let st;try{st=await this.getStream(nt)}catch(dt){return log$m.error("Failed to get stream",dt),{success:null,failure:{error:ProtocolError$1.NO_STREAM_AVAILABLE,peerId:nt.id}}}let at;try{at=await pipe([ot.encode()],encode$K,st,decode$U,async dt=>await all$2(dt))}catch(dt){return log$m.error("Failed to send waku light push request",dt),{success:null,failure:{error:ProtocolError$1.GENERIC_FAIL,peerId:nt.id}}}const ct=new Uint8ArrayList;at.forEach(dt=>{ct.append(dt)});let lt;try{lt=PushRpc.decode(ct).response}catch(dt){return log$m.error("Failed to decode push reply",dt),{success:null,failure:{error:ProtocolError$1.DECODE_FAILED,peerId:nt.id}}}if(!lt)return log$m.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:ProtocolError$1.NO_RESPONSE,peerId:nt.id}};if(isRLNResponseError(lt.info)){const dt=matchRLNErrorMessage(lt.info);return log$m.error("Remote peer rejected the message: ",dt),{success:null,failure:{error:dt,peerId:nt.id}}}return lt.isSuccess?{success:nt.id,failure:null}:(log$m.error("Remote peer rejected the message: ",lt.info),{success:null,failure:{error:ProtocolError$1.REMOTE_PEER_REJECTED,peerId:nt.id}})}}const EmptyMessage={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0};function toProtoMessage(et){return{...EmptyMessage,...et}}const DEFAULT_PAGE_SIZE=20,MAX_PAGE_SIZE=100,ONE_MILLION=1e6;class StoreQueryRequest{constructor(o){wt(this,"proto");this.proto=o}static create(o){const tt=new StoreQueryRequest({...o,requestId:v4$2(),timeStart:o.timeStart?BigInt(o.timeStart.getTime()*ONE_MILLION):void 0,timeEnd:o.timeEnd?BigInt(o.timeEnd.getTime()*ONE_MILLION):void 0,messageHashes:o.messageHashes||[],paginationLimit:o.paginationLimit?BigInt(o.paginationLimit):void 0});if(o.pubsubTopic&&!o.contentTopics||!o.pubsubTopic&&o.contentTopics)throw new Error("Both pubsubTopic and contentTopics must be set or unset");if(o.messageHashes&&(o.pubsubTopic||o.contentTopics||o.timeStart||o.timeEnd))throw new Error("Message hash lookup queries cannot include content filter criteria");return tt}static decode(o){const tt=StoreQueryRequest$1.decode(o);return new StoreQueryRequest(tt)}encode(){return StoreQueryRequest$1.encode(this.proto)}}class StoreQueryResponse{constructor(o){wt(this,"proto");this.proto=o}static decode(o){const tt=StoreQueryResponse$1.decode(o);return new StoreQueryResponse(tt)}encode(){return StoreQueryResponse$1.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const log$l=new Logger$1("store"),StoreCodec="/vac/waku/store-query/3.0.0";class StoreCore extends BaseProtocol{constructor(tt,rt){super(StoreCodec,rt.components,log$l,tt);wt(this,"pubsubTopics");this.pubsubTopics=tt}async*queryPerPage(tt,rt,nt){if(tt.contentTopics.toString()!==Array.from(rt.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let ot=tt.paginationCursor;for(;;){const it=StoreQueryRequest.create({...tt,paginationCursor:ot});let st;try{st=await this.getStream(nt)}catch(ht){log$l.error("Failed to get stream",ht);break}const at=await pipe([it.encode()],encode$K,st,decode$U,async ht=>await all$2(ht)),ct=new Uint8ArrayList;at.forEach(ht=>{ct.append(ht)});const lt=StoreQueryResponse.decode(ct);if(!lt.statusCode||lt.statusCode>=300){const ht=`Store query failed with status code: ${lt.statusCode}, description: ${lt.statusDesc}`;throw log$l.error(ht),new Error(ht)}if(!lt.messages||!lt.messages.length){log$l.warn("Stopping pagination due to empty messages in response");break}if(log$l.info(`${lt.messages.length} messages retrieved from store`),yield lt.messages.map(ht=>{if(!ht.message)return Promise.resolve(void 0);const mt=ht.message.contentTopic;if(mt){const ft=rt.get(mt);if(ft)return ft.fromProtoObj(ht.pubsubTopic||"",toProtoMessage(ht.message))}return Promise.resolve(void 0)}),tt.paginationForward?ot=lt.messages[lt.messages.length-1].messageHash:ot=lt.messages[0].messageHash,lt.messages.length>MAX_PAGE_SIZE&<.messages.length<(tt.paginationLimit||DEFAULT_PAGE_SIZE))break}}}const peerDiscoverySymbol$2=Symbol.for("@libp2p/peer-discovery"),peerIdSymbol$3=Symbol.for("@libp2p/peer-id");function isPeerId$2(et){return!!(et!=null&&et[peerIdSymbol$3])}var cs;let AbortError$9=(cs=class extends Error{constructor(o="The operation was aborted"){super(o),this.name="AbortError"}},wt(cs,"name","AbortError"),cs);class UnexpectedPeerError extends Error{constructor(o="Unexpected Peer"){super(o),this.name="UnexpectedPeerError"}}wt(UnexpectedPeerError,"name","UnexpectedPeerError");var ls;let InvalidMessageError$3=(ls=class extends Error{constructor(o="Invalid message"){super(o),this.name="InvalidMessageError"}},wt(ls,"name","InvalidMessageError"),ls);class ProtocolError extends Error{constructor(o="Protocol error"){super(o),this.name="ProtocolError"}}wt(ProtocolError,"name","ProtocolError");var us;let TimeoutError$3=(us=class extends Error{constructor(o="Timed out"){super(o),this.name="TimeoutError"}},wt(us,"name","TimeoutError"),us);function setMaxListeners$9(){}const setMaxListeners$8=(et,...o)=>{try{[...o]}catch{}};var Yr,Xs;let TypedEventEmitter$3=(Xs=class extends EventTarget{constructor(){super();hr(this,Yr,new Map);setMaxListeners$8(1/0,this)}listenerCount(tt){const rt=Lt(this,Yr).get(tt);return rt==null?0:rt.length}addEventListener(tt,rt,nt){super.addEventListener(tt,rt,nt);let ot=Lt(this,Yr).get(tt);ot==null&&(ot=[],Lt(this,Yr).set(tt,ot)),ot.push({callback:rt,once:(nt!==!0&&nt!==!1&&(nt==null?void 0:nt.once))??!1})}removeEventListener(tt,rt,nt){super.removeEventListener(tt.toString(),rt??null,nt);let ot=Lt(this,Yr).get(tt);ot!=null&&(ot=ot.filter(({callback:it})=>it!==rt),Lt(this,Yr).set(tt,ot))}dispatchEvent(tt){const rt=super.dispatchEvent(tt);let nt=Lt(this,Yr).get(tt.type);return nt==null||(nt=nt.filter(({once:ot})=>!ot),Lt(this,Yr).set(tt.type,nt)),rt}safeDispatchEvent(tt,rt={}){return this.dispatchEvent(new CustomEvent(tt,rt))}},Yr=new WeakMap,Xs);const serviceCapabilities$5=Symbol.for("@libp2p/service-capabilities"),RelayPingContentTopic="/relay-ping/1/ping/null",log$k=new Logger$1("keep-alive");class KeepAliveManager{constructor({options:o,relay:tt,libp2p:rt}){wt(this,"relay");wt(this,"libp2p");wt(this,"options");wt(this,"pingKeepAliveTimers",new Map);wt(this,"relayKeepAliveTimers",new Map);this.options=o,this.relay=tt,this.libp2p=rt}start(o){this.stop(o);const{pingKeepAlive:tt,relayKeepAlive:rt}=this.options,nt=o.toString();if(tt!==0){const it=setInterval(()=>{(async()=>{let st;try{try{st=await this.libp2p.services.ping.ping(o),log$k.info(`Ping succeeded (${nt})`,st)}catch{log$k.error(`Ping failed for peer (${nt}). + Next ping will be attempted in ${tt} seconds. + `);return}try{await this.libp2p.peerStore.merge(o,{metadata:{ping:utf8ToBytes$1(st.toString())}})}catch(at){log$k.error("Failed to update ping",at)}}catch(at){log$k.error(`Ping failed (${nt})`,at)}})()},tt*1e3);this.pingKeepAliveTimers.set(nt,it)}const ot=this.relay;if(ot&&rt!==0){const it=this.scheduleRelayPings(ot,rt,o.toString());this.relayKeepAliveTimers.set(o,it)}}stop(o){var rt;const tt=o.toString();this.pingKeepAliveTimers.has(tt)&&(clearInterval(this.pingKeepAliveTimers.get(tt)),this.pingKeepAliveTimers.delete(tt)),this.relayKeepAliveTimers.has(o)&&((rt=this.relayKeepAliveTimers.get(o))==null||rt.map(clearInterval),this.relayKeepAliveTimers.delete(o))}stopAll(){for(const o of[...Object.values(this.pingKeepAliveTimers),...Object.values(this.relayKeepAliveTimers)])clearInterval(o);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}connectionsExist(){return this.pingKeepAliveTimers.size>0||this.relayKeepAliveTimers.size>0}scheduleRelayPings(o,tt,rt){const nt=[];for(const ot of o.pubsubTopics){if(!o.getMeshPeers(ot).includes(rt))continue;const st=createEncoder({pubsubTopicShardInfo:pubsubTopicToSingleShardInfo(ot),contentTopic:RelayPingContentTopic,ephemeral:!0}),at=setInterval(()=>{log$k.info("Sending Waku Relay ping message"),o.send(st,{payload:new Uint8Array([1])}).catch(ct=>log$k.error("Failed to send relay ping",ct))},tt*1e3);nt.push(at)}return nt}}const log$j=new Logger$1("connection-manager"),DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED=1,DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER=3,DEFAULT_MAX_PARALLEL_DIALS=3,Nn=class Nn extends TypedEventEmitter$3{constructor(tt,rt,nt,ot,it){super();wt(this,"configuredPubsubTopics");wt(this,"keepAliveManager");wt(this,"options");wt(this,"libp2p");wt(this,"dialAttemptsForPeer",new Map);wt(this,"dialErrorsForPeer",new Map);wt(this,"currentActiveParallelDialCount",0);wt(this,"pendingPeerDialQueue",[]);wt(this,"isP2PNetworkConnected",!1);wt(this,"onEventHandlers",{"peer:discovery":tt=>{(async()=>{const{id:rt}=tt.detail;await this.dispatchDiscoveryEvent(rt);try{await this.attemptDial(rt)}catch(nt){log$j.error(`Error dialing peer ${rt.toString()} : ${nt}`)}})()},"peer:connect":tt=>{(async()=>{log$j.info(`Connected to peer ${tt.detail.toString()}`);const rt=tt.detail;this.keepAliveManager.start(rt),(await this.getTagNamesForPeer(rt)).includes(Tags.BOOTSTRAP)?this.libp2p.getConnections().filter(it=>it.tags.includes(Tags.BOOTSTRAP)).length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(rt):this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP,{detail:rt})):this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE,{detail:rt})),this.setP2PNetworkConnected()})()},"peer:disconnect":tt=>{(async()=>(this.keepAliveManager.stop(tt.detail),this.setP2PNetworkDisconnected()))()},"browser:network":()=>{this.dispatchWakuConnectionEvent()}});this.configuredPubsubTopics=nt,this.libp2p=tt,this.configuredPubsubTopics=nt,this.options={maxDialAttemptsForPeer:DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER,maxBootstrapPeersAllowed:DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,maxParallelDials:DEFAULT_MAX_PARALLEL_DIALS,...it},this.keepAliveManager=new KeepAliveManager({relay:ot,libp2p:tt,options:rt}),this.startEventListeners().then(()=>log$j.info("Connection Manager is now running")).catch(st=>log$j.error("Unexpected error while running service",st)),this.dialPeerStorePeers().catch(st=>log$j.error("Unexpected error while dialing peer store peers",st))}isConnected(){var tt;return globalThis!=null&&globalThis.navigator&&!((tt=globalThis==null?void 0:globalThis.navigator)!=null&&tt.onLine)?!1:this.isP2PNetworkConnected}static create(tt,rt,nt,ot,it,st){let at=Nn.instances.get(tt);return at||(at=new Nn(rt,nt,ot,it,st),Nn.instances.set(tt,at)),at}stop(){this.keepAliveManager.stopAll(),this.libp2p.removeEventListener("peer:connect",this.onEventHandlers["peer:connect"]),this.libp2p.removeEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"]),this.libp2p.removeEventListener("peer:discovery",this.onEventHandlers["peer:discovery"]),this.stopNetworkStatusListener()}async dropConnection(tt){try{this.keepAliveManager.stop(tt),await this.libp2p.hangUp(tt),log$j.info(`Dropped connection with peer ${tt.toString()}`)}catch(rt){log$j.error(`Error dropping connection with peer ${tt.toString()} - ${rt}`)}}async getPeersByDiscovery(){const tt=await this.libp2p.peerStore.all(),rt=this.libp2p.getConnections().map(lt=>lt.remotePeer),nt=[],ot=[],it=[],st=[],at=[],ct=[];for(const lt of tt){const dt=await this.getTagNamesForPeer(lt.id);dt.includes(Tags.BOOTSTRAP)?nt.push(lt):dt.includes(Tags.PEER_EXCHANGE)?ot.push(lt):dt.includes(Tags.LOCAL)&&it.push(lt)}for(const lt of rt){const dt=await this.libp2p.peerStore.get(lt),ht=await this.getTagNamesForPeer(lt);ht.includes(Tags.BOOTSTRAP)?st.push(dt):ht.includes(Tags.PEER_EXCHANGE)?at.push(dt):ht.includes(Tags.LOCAL)&&ct.push(dt)}return{DISCOVERED:{[Tags.BOOTSTRAP]:nt,[Tags.PEER_EXCHANGE]:ot,[Tags.LOCAL]:it},CONNECTED:{[Tags.BOOTSTRAP]:st,[Tags.PEER_EXCHANGE]:at,[Tags.LOCAL]:ct}}}async dialPeerStorePeers(){const tt=await this.libp2p.peerStore.all(),rt=[];for(const nt of tt)this.libp2p.getConnections().find(ot=>ot.remotePeer===nt.id)||rt.push(this.attemptDial(nt.id));try{await Promise.all(rt)}catch(nt){log$j.error("Unexpected error while dialing peer store peers",nt)}}async startEventListeners(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener(),this.startNetworkStatusListener()}async dialPeer(tt){this.currentActiveParallelDialCount+=1;let rt=0;for(;rt{ot.tags=Array.from(new Set([...ot.tags,...nt]))}),this.dialAttemptsForPeer.set(tt.toString(),-1),this.keepAliveManager.start(tt);break}catch(nt){nt instanceof AggregateError?log$j.error(`Error dialing peer ${tt.toString()} - ${nt.errors}`):log$j.error(`Error dialing peer ${tt.toString()} - ${nt.message}`),this.dialErrorsForPeer.set(tt.toString(),nt),rt++,this.dialAttemptsForPeer.set(tt.toString(),rt)}if(this.currentActiveParallelDialCount--,this.processDialQueue(),rt===this.options.maxDialAttemptsForPeer)try{const nt=this.dialErrorsForPeer.get(tt.toString());if(nt){let ot;nt instanceof AggregateError?nt.errors?nt.errors.length===0?log$j.warn("Errors array is empty for AggregateError"):ot=JSON.stringify(nt.errors[0]):log$j.warn("No errors array found for AggregateError"):ot=nt.message,log$j.info(`Deleting undialable peer ${tt.toString()} from peer store. Reason: ${ot}`)}this.dialErrorsForPeer.delete(tt.toString()),await this.libp2p.peerStore.delete(tt),await this.attemptDnsDiscovery()}catch(nt){throw new Error(`Error deleting undialable peer ${tt.toString()} from peer store - ${nt}`)}}async attemptDnsDiscovery(){if(this.libp2p.getConnections().length>0||(await this.libp2p.peerStore.all()).length>0)return;log$j.info("Attempting to trigger DNS discovery.");const tt=Object.values(this.libp2p.components.components).find(rt=>rt&&rt.toString?rt.toString().includes(DNS_DISCOVERY_TAG):!1);tt&&await tt.findPeers()}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount{log$j.error(rt)})}}startPeerDiscoveryListener(){this.libp2p.addEventListener("peer:discovery",this.onEventHandlers["peer:discovery"])}startPeerConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onEventHandlers["peer:connect"])}startPeerDisconnectionListener(){this.libp2p.addEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"])}async attemptDial(tt){if(await this.shouldDialPeer(tt)){if(this.currentActiveParallelDialCount>=this.options.maxParallelDials){this.pendingPeerDialQueue.push(tt);return}await this.dialPeer(tt)}}async shouldDialPeer(tt){if(this.libp2p.getConnections(tt).length>0)return log$j.warn(`Already connected to peer ${tt.toString()}. Not dialing.`),!1;if(!await this.isPeerTopicConfigured(tt)){const st=await this.getPeerShardInfo(tt,this.libp2p.peerStore);return log$j.warn(`Discovered peer ${tt.toString()} with ShardInfo ${st} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}). + Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(tt)?this.dialAttemptsForPeer.has(tt.toString())?(log$j.warn(`Peer ${tt.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):!0:(log$j.warn(`Peer ${tt.toString()} is not dialable based on bootstrap status. Not dialing.`),!1)}async isPeerDialableBasedOnBootstrapStatus(tt){return(await this.getTagNamesForPeer(tt)).some(it=>it===Tags.BOOTSTRAP)?this.libp2p.getConnections().filter(it=>it.tags.find(st=>st===Tags.BOOTSTRAP)).lengththis.configuredPubsubTopics.includes(it)):!0}async getPeerShardInfo(tt,rt){const ot=(await rt.get(tt)).metadata.get("shardInfo");if(ot)return decodeRelayShard(ot)}startNetworkStatusListener(){try{globalThis.addEventListener("online",this.onEventHandlers["browser:network"]),globalThis.addEventListener("offline",this.onEventHandlers["browser:network"])}catch(tt){log$j.error(`Failed to start network listener: ${tt}`)}}stopNetworkStatusListener(){try{globalThis.removeEventListener("online",this.onEventHandlers["browser:network"]),globalThis.removeEventListener("offline",this.onEventHandlers["browser:network"])}catch(tt){log$j.error(`Failed to stop network listener: ${tt}`)}}setP2PNetworkConnected(){this.isP2PNetworkConnected||(this.isP2PNetworkConnected=!0,this.dispatchWakuConnectionEvent())}setP2PNetworkDisconnected(){this.isP2PNetworkConnected&&this.libp2p.getConnections().length===0&&(this.isP2PNetworkConnected=!1,this.dispatchWakuConnectionEvent())}dispatchWakuConnectionEvent(){this.dispatchEvent(new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS,{detail:this.isConnected()}))}};wt(Nn,"instances",new Map);let ConnectionManager=Nn;const An=class An{constructor(){wt(this,"health");this.health={overallStatus:HealthStatus.Unhealthy,protocolStatuses:new Map}}static getInstance(){return An.instance||(An.instance=new An),An.instance}getHealthStatus(){return this.health.overallStatus}getProtocolStatus(o){return this.health.protocolStatuses.get(o)}updateProtocolHealth(o,tt){const rt=this.getNameFromMulticodec(o);let nt=HealthStatus.Unhealthy;tt==1?nt=HealthStatus.MinimallyHealthy:tt>=2&&(nt=HealthStatus.SufficientlyHealthy),this.health.protocolStatuses.set(rt,{name:rt,status:nt,lastUpdate:new Date}),this.updateOverallHealth()}getNameFromMulticodec(o){let tt;if(o.includes("filter"))tt=Protocols.Filter;else if(o.includes("lightpush"))tt=Protocols.LightPush;else if(o.includes("store"))tt=Protocols.Store;else throw new Error(`Unknown protocol: ${o}`);return tt}updateOverallHealth(){const tt=[Protocols.LightPush,Protocols.Filter].map(rt=>{var nt;return(nt=this.getProtocolStatus(rt))==null?void 0:nt.status});tt.some(rt=>rt===HealthStatus.Unhealthy)?this.health.overallStatus=HealthStatus.Unhealthy:tt.some(rt=>rt===HealthStatus.MinimallyHealthy)?this.health.overallStatus=HealthStatus.MinimallyHealthy:this.health.overallStatus=HealthStatus.SufficientlyHealthy}};wt(An,"instance");let HealthManager=An;const getHealthManager=()=>HealthManager.getInstance(),log$i=new Logger$1("metadata"),MetadataCodec="/vac/waku/metadata/1.0.0";class Metadata extends BaseProtocol{constructor(tt,rt){super(MetadataCodec,rt.components,log$i,tt);wt(this,"pubsubTopics");wt(this,"libp2pComponents");wt(this,"handshakesConfirmed",new Map);this.pubsubTopics=tt,this.libp2pComponents=rt,rt.registrar.handle(MetadataCodec,nt=>{this.onRequest(nt)})}async query(tt){const rt=WakuMetadataRequest.encode(pubsubTopicsToShardInfo(this.pubsubTopics)),nt=await this.libp2pComponents.peerStore.get(tt);if(!nt)return{shardInfo:null,error:ProtocolError$1.NO_PEER_AVAILABLE};let ot;try{ot=await this.getStream(nt)}catch(ct){return log$i.error("Failed to get stream",ct),{shardInfo:null,error:ProtocolError$1.NO_STREAM_AVAILABLE}}const it=await pipe([rt],encode$K,ot,decode$U,async ct=>await all$2(ct)),{error:st,shardInfo:at}=this.decodeMetadataResponse(it);return st?{shardInfo:null,error:st}:(await this.savePeerShardInfo(tt,at),{shardInfo:at,error:null})}async confirmOrAttemptHandshake(tt){const rt=this.handshakesConfirmed.get(tt.toString());return rt?{shardInfo:rt,error:null}:await this.query(tt)}async onRequest(tt){try{const{stream:rt,connection:nt}=tt,ot=WakuMetadataResponse.encode(pubsubTopicsToShardInfo(this.pubsubTopics)),it=await pipe([ot],encode$K,rt,decode$U,async ct=>await all$2(ct)),{error:st,shardInfo:at}=this.decodeMetadataResponse(it);if(st)return;await this.savePeerShardInfo(nt.remotePeer,at)}catch(rt){log$i.error("Error handling metadata request",rt)}}decodeMetadataResponse(tt){const rt=new Uint8ArrayList;tt.forEach(ot=>{rt.append(ot)});const nt=WakuMetadataResponse.decode(rt);return nt?{shardInfo:nt,error:null}:(log$i.error("Error decoding metadata response"),{shardInfo:null,error:ProtocolError$1.DECODE_FAILED})}async savePeerShardInfo(tt,rt){await this.libp2pComponents.peerStore.merge(tt,{metadata:{shardInfo:encodeRelayShard(rt)}}),this.handshakesConfirmed.set(tt.toString(),rt)}}function wakuMetadata(et){return o=>new Metadata(et,o)}function equals$e(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;tt=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$j=base$j,_brrp__multiformats_scope_baseX$i=src$j;let Encoder$j=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$j=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$k(this,o)}},ComposedDecoder$i=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$k(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$k(et,o){return new ComposedDecoder$i({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$i=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$j(o,tt,rt),this.decoder=new Decoder$j(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$l({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$i(et,o,tt,rt)}function baseX$i({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$i(tt,et);return from$l({prefix:o,name:et,encode:rt,decode:ot=>coerce$j(nt(ot))})}function decode$T(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$J(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<=INT$5;)o[tt++]=et&255|MSB$7,et/=128;for(;et&MSBALL$5;)o[tt++]=et&255|MSB$7,et>>>=7;return o[tt]=et|0,encode$I.bytes=tt-rt+1,o}var decode$S=read$6,MSB$1$5=128,REST$1$5=127;function read$6(et,rt){var tt=0,rt=rt||0,nt=0,ot=rt,it,st=et.length;do{if(ot>=st)throw read$6.bytes=0,new RangeError("Could not decode varint");it=et[ot++],tt+=nt<28?(it&REST$1$5)<=MSB$1$5);return read$6.bytes=ot-rt,tt}var N1$5=Math.pow(2,7),N2$5=Math.pow(2,14),N3$5=Math.pow(2,21),N4$5=Math.pow(2,28),N5$5=Math.pow(2,35),N6$5=Math.pow(2,42),N7$5=Math.pow(2,49),N8$5=Math.pow(2,56),N9$5=Math.pow(2,63),length$5=function(et){return et{const[dt,ht]=decode$R(o.subarray(tt));return tt+=ht,dt};let nt=rt(),ot=DAG_PB_CODE$3;if(nt===18?(nt=0,tt=0):ot=rt(),nt!==0&&nt!==1)throw new RangeError(`Invalid CID version ${nt}`);const it=tt,st=rt(),at=rt(),ct=tt+at,lt=ct-it;return{version:nt,codec:ot,multihashCode:st,digestSize:at,multihashSize:lt,size:ct}}static parse(o,tt){const[rt,nt]=parseCIDtoBytes$3(o,tt),ot=jr.decode(nt);if(ot.version===0&&o[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$3(ot).set(rt,o),ot}};function parseCIDtoBytes$3(et,o){switch(et[0]){case"Q":{const tt=o??base58btc$i;return[base58btc$i.prefix,tt.decode(`${base58btc$i.prefix}${et}`)]}case base58btc$i.prefix:{const tt=o??base58btc$i;return[base58btc$i.prefix,tt.decode(et)]}case base32$w.prefix:{const tt=o??base32$w;return[base32$w.prefix,tt.decode(et)]}case base36$t.prefix:{const tt=o??base36$t;return[base36$t.prefix,tt.decode(et)]}default:{if(o==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[et[0],o.decode(et)]}}}function toStringV0$3(et,o,tt){const{prefix:rt}=tt;if(rt!==base58btc$i.prefix)throw Error(`Cannot string encode V0 in ${tt.name} encoding`);const nt=o.get(rt);if(nt==null){const ot=tt.encode(et).slice(1);return o.set(rt,ot),ot}else return nt}function toStringV1$3(et,o,tt){const{prefix:rt}=tt,nt=o.get(rt);if(nt==null){const ot=tt.encode(et);return o.set(rt,ot),ot}else return nt}const DAG_PB_CODE$3=112,SHA_256_CODE$3=18;function encodeCID$3(et,o,tt){const rt=encodingLength$5(et),nt=rt+encodingLength$5(o),ot=new Uint8Array(nt+tt.byteLength);return encodeTo$3(et,ot,0),encodeTo$3(o,ot,rt),ot.set(tt,nt),ot}const cidSymbol$3=Symbol.for("@ipld/js-cid/CID");function equals$c(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;tt(et[tt]=o,et),[]),alphabetCharsToBytes$e=alphabet$e.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$H(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$e[tt],o),"")}function decode$P(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$e[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$s=from$l({prefix:"🚀",name:"base256emoji",encode:encode$H,decode:decode$P}),base256emoji$t=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$s},Symbol.toStringTag,{value:"Module"})),base64$v=rfc4648$h({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$e=rfc4648$h({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$f=rfc4648$h({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$e=rfc4648$h({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$w=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$v,base64pad:base64pad$e,base64url:base64url$f,base64urlpad:base64urlpad$e},Symbol.toStringTag,{value:"Module"})),base8$s=rfc4648$h({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$t=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$s},Symbol.toStringTag,{value:"Module"})),identity$g=from$l({prefix:"\0",name:"identity",encode:et=>toString$u(et),decode:et=>fromString$s(et)}),identityBase$e=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$g},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$e={...identityBase$e,...base2$t,...base8$t,...base10$t,...base16$t,...base32$x,...base36$u,...base58$e,...base64$w,...base256emoji$t};function allocUnsafe$d(et=0){return new Uint8Array(et)}function createCodec$e(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$i=createCodec$e("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$e=createCodec$e("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$d(et.length);for(let tt=0;ttnt+ot.length,0));const tt=allocUnsafe$d(o);let rt=0;for(const nt of et)tt.set(nt,rt),rt+=nt.length;return tt}class Parser{constructor(){wt(this,"index",0);wt(this,"input","")}new(o){return this.index=0,this.input=o,this}readAtomically(o){const tt=this.index,rt=o();return rt===void 0&&(this.index=tt),rt}parseWith(o){const tt=o();if(this.index===this.input.length)return tt}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(o){return this.readAtomically(()=>{const tt=this.readChar();if(tt===o)return tt})}readSeparator(o,tt,rt){return this.readAtomically(()=>{if(!(tt>0&&this.readGivenChar(o)===void 0))return rt()})}readNumber(o,tt,rt,nt){return this.readAtomically(()=>{let ot=0,it=0;const st=this.peekChar();if(st===void 0)return;const at=st==="0",ct=2**(8*nt)-1;for(;;){const lt=this.readAtomically(()=>{const dt=this.readChar();if(dt===void 0)return;const ht=Number.parseInt(dt,o);if(!Number.isNaN(ht))return ht});if(lt===void 0)break;if(ot*=o,ot+=lt,ot>ct||(it+=1,tt!==void 0&&it>tt))return}if(it!==0)return!rt&&at&&it>1?void 0:ot})}readIPv4Addr(){return this.readAtomically(()=>{const o=new Uint8Array(4);for(let tt=0;ttthis.readNumber(10,3,!1,1));if(rt===void 0)return;o[tt]=rt}return o})}readIPv6Addr(){const o=tt=>{for(let rt=0;rtthis.readIPv4Addr());if(it!==void 0)return tt[nt]=it[0],tt[nt+1]=it[1],tt[nt+2]=it[2],tt[nt+3]=it[3],[nt+4,!0]}const ot=this.readSeparator(":",rt,()=>this.readNumber(16,4,!0,2));if(ot===void 0)return[nt,!1];tt[nt]=ot>>8,tt[nt+1]=ot&255}return[tt.length,!1]};return this.readAtomically(()=>{const tt=new Uint8Array(16),[rt,nt]=o(tt);if(rt===16)return tt;if(nt||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;const ot=new Uint8Array(14),it=16-(rt+2),[st]=o(ot.subarray(0,it));return tt.set(ot.subarray(0,st),16-st),tt})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}}const MAX_IPV6_LENGTH=45,MAX_IPV4_LENGTH=15,parser=new Parser;function parseIPv4(et){if(!(et.length>MAX_IPV4_LENGTH))return parser.new(et).parseWith(()=>parser.readIPv4Addr())}function parseIPv6(et){if(et.includes("%")&&(et=et.split("%")[0]),!(et.length>MAX_IPV6_LENGTH))return parser.new(et).parseWith(()=>parser.readIPv6Addr())}function parseIP(et){if(et.includes("%")&&(et=et.split("%")[0]),!(et.length>MAX_IPV6_LENGTH))return parser.new(et).parseWith(()=>parser.readIPAddr())}function fromString$r(et,o="utf8"){const tt=BASES$e[o];if(tt==null)throw new Error(`Unsupported encoding "${o}"`);return tt.decoder.decode(`${tt.prefix}${et}`)}function isIPv4(et){return!!parseIPv4(et)}function isIPv6(et){return!!parseIPv6(et)}function isIP(et){return!!parseIP(et)}const isV4=isIPv4,isV6=isIPv6,toBytes$1=function(et){let o=0;if(et=et.toString().trim(),isV4(et)){const tt=new Uint8Array(o+4);return et.split(/\./g).forEach(rt=>{tt[o++]=parseInt(rt,10)&255}),tt}if(isV6(et)){const tt=et.split(":",8);let rt;for(rt=0;rt0;rt--)ot.push("0");tt.splice.apply(tt,ot)}const nt=new Uint8Array(o+16);for(rt=0;rt>8&255,nt[o++]=ot&255}return nt}throw new Error("invalid ip address")},toString$s=function(et,o=0,tt){o=~~o,tt=tt??et.length-o;const rt=new DataView(et.buffer);if(tt===4){const nt=[];for(let ot=0;ot{const o=createProtocol(...et);codes[o.code]=o,names[o.name]=o});function createProtocol(et,o,tt,rt,nt){return{code:et,size:o,name:tt,resolvable:!!rt,path:!!nt}}function getProtocol(et){if(typeof et=="number"){if(codes[et]!=null)return codes[et];throw new Error(`no protocol with code: ${et}`)}else if(typeof et=="string"){if(names[et]!=null)return names[et];throw new Error(`no protocol with name: ${et}`)}throw new Error(`invalid protocol id type: ${typeof et}`)}getProtocol("ip4");getProtocol("ip6");getProtocol("ipcidr");function convertToString(et,o){switch(getProtocol(et).code){case 4:case 41:return bytes2ip(o);case 42:return bytes2str(o);case 6:case 273:case 33:case 132:return bytes2port(o).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return bytes2str(o);case 421:return bytes2mh(o);case 444:return bytes2onion(o);case 445:return bytes2onion(o);case 466:return bytes2mb(o);case 481:return globalThis.encodeURIComponent(bytes2str(o));default:return toString$t(o,"base16")}}function convertToBytes(et,o){switch(getProtocol(et).code){case 4:return ip2bytes(o);case 41:return ip2bytes(o);case 42:return str2bytes(o);case 6:case 273:case 33:case 132:return port2bytes(parseInt(o,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return str2bytes(o);case 421:return mh2bytes(o);case 444:return onion2bytes(o);case 445:return onion32bytes(o);case 466:return mb2bytes(o);case 481:return str2bytes(globalThis.decodeURIComponent(o));default:return fromString$r(o,"base16")}}const decoders=Object.values(bases$e).map(et=>et.decoder),anybaseDecoder=function(){let et=decoders[0].or(decoders[1]);return decoders.slice(2).forEach(o=>et=et.or(o)),et}();function ip2bytes(et){if(!isIP(et))throw new Error("invalid ip address");return toBytes$1(et)}function bytes2ip(et){const o=toString$s(et,0,et.length);if(o==null)throw new Error("ipBuff is required");if(!isIP(o))throw new Error("invalid ip address");return o}function port2bytes(et){const o=new ArrayBuffer(2);return new DataView(o).setUint16(0,et),new Uint8Array(o)}function bytes2port(et){return new DataView(et.buffer).getUint16(et.byteOffset)}function str2bytes(et){const o=fromString$r(et),tt=Uint8Array.from(encode$P(o.length));return concat$3([tt,o],tt.length+o.length)}function bytes2str(et){const o=decode$Z(et);if(et=et.slice(encodingLength$6(o)),et.length!==o)throw new Error("inconsistent lengths");return toString$t(et)}function mh2bytes(et){let o;et[0]==="Q"||et[0]==="1"?o=decode$Q(base58btc$i.decode(`z${et}`)).bytes:o=CID$3.parse(et).multihash.bytes;const tt=Uint8Array.from(encode$P(o.length));return concat$3([tt,o],tt.length+o.length)}function mb2bytes(et){const o=anybaseDecoder.decode(et),tt=Uint8Array.from(encode$P(o.length));return concat$3([tt,o],tt.length+o.length)}function bytes2mb(et){const o=decode$Z(et),tt=et.slice(encodingLength$6(o));if(tt.length!==o)throw new Error("inconsistent lengths");return"u"+toString$t(tt,"base64url")}function bytes2mh(et){const o=decode$Z(et),tt=et.slice(encodingLength$6(o));if(tt.length!==o)throw new Error("inconsistent lengths");return toString$t(tt,"base58btc")}function onion2bytes(et){const o=et.split(":");if(o.length!==2)throw new Error(`failed to parse onion addr: ["'${o.join('", "')}'"]' does not contain a port number`);if(o[0].length!==16)throw new Error(`failed to parse onion addr: ${o[0]} not a Tor onion address.`);const tt=base32$w.decode("b"+o[0]),rt=parseInt(o[1],10);if(rt<1||rt>65536)throw new Error("Port number is not in range(1, 65536)");const nt=port2bytes(rt);return concat$3([tt,nt],tt.length+nt.length)}function onion32bytes(et){const o=et.split(":");if(o.length!==2)throw new Error(`failed to parse onion addr: ["'${o.join('", "')}'"]' does not contain a port number`);if(o[0].length!==56)throw new Error(`failed to parse onion addr: ${o[0]} not a Tor onion3 address.`);const tt=base32$w.decode(`b${o[0]}`),rt=parseInt(o[1],10);if(rt<1||rt>65536)throw new Error("Port number is not in range(1, 65536)");const nt=port2bytes(rt);return concat$3([tt,nt],tt.length+nt.length)}function bytes2onion(et){const o=et.slice(0,et.length-2),tt=et.slice(et.length-2),rt=toString$t(o,"base32"),nt=bytes2port(tt);return`${rt}:${nt}`}function stringToMultiaddrParts(et){et=cleanPath(et);const o=[],tt=[];let rt=null;const nt=et.split("/").slice(1);if(nt.length===1&&nt[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let ot=0;ot=nt.length)throw ParseError("invalid address: "+et);if(st.path===!0){rt=cleanPath(nt.slice(ot).join("/")),o.push([st.code,convertToBytes(st.code,rt)]),tt.push([st.code,rt]);break}const at=convertToBytes(st.code,nt[ot]);o.push([st.code,at]),tt.push([st.code,convertToString(st.code,at)])}return{string:stringTuplesToString(tt),bytes:tuplesToBytes(o),tuples:o,stringTuples:tt,path:rt}}function bytesToMultiaddrParts(et){const o=[],tt=[];let rt=null,nt=0;for(;ntet.length)throw ParseError("Invalid address Uint8Array: "+toString$t(et,"base16"));o.push([ot,ct]);const lt=convertToString(ot,ct);if(tt.push([ot,lt]),st.path===!0){rt=lt;break}}return{bytes:Uint8Array.from(et),string:stringTuplesToString(tt),tuples:o,stringTuples:tt,path:rt}}function stringTuplesToString(et){const o=[];return et.map(tt=>{const rt=getProtocol(tt[0]);return o.push(rt.name),tt.length>1&&tt[1]!=null&&o.push(tt[1]),null}),cleanPath(o.join("/"))}function tuplesToBytes(et){return concat$3(et.map(o=>{const tt=getProtocol(o[0]);let rt=Uint8Array.from(encode$P(tt.code));return o.length>1&&o[1]!=null&&(rt=concat$3([rt,o[1]])),rt}))}function sizeForAddr(et,o){if(et.size>0)return et.size/8;if(et.size===0)return 0;{const tt=decode$Z(o instanceof Uint8Array?o:Uint8Array.from(o));return tt+encodingLength$6(tt)}}function cleanPath(et){return"/"+et.trim().split("/").filter(o=>o).join("/")}function ParseError(et){return new Error("Error parsing address: "+et)}const inspect$1=Symbol.for("nodejs.util.inspect.custom"),symbol=Symbol.for("@multiformats/js-multiaddr/multiaddr"),DNS_CODES=[getProtocol("dns").code,getProtocol("dns4").code,getProtocol("dns6").code,getProtocol("dnsaddr").code];class NoAvailableResolverError extends Error{constructor(o="No available resolver"){super(o),this.name="NoAvailableResolverError"}}var na,Yn,wn,lo,uo;const Dn=class Dn{constructor(o){wt(this,"bytes");hr(this,Yn);hr(this,wn);hr(this,lo);hr(this,uo);wt(this,na,!0);o==null&&(o="");let tt;if(o instanceof Uint8Array)tt=bytesToMultiaddrParts(o);else if(typeof o=="string"){if(o.length>0&&o.charAt(0)!=="/")throw new Error(`multiaddr "${o}" must start with a "/"`);tt=stringToMultiaddrParts(o)}else if(isMultiaddr(o))tt=bytesToMultiaddrParts(o.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=tt.bytes,ur(this,Yn,tt.string),ur(this,wn,tt.tuples),ur(this,lo,tt.stringTuples),ur(this,uo,tt.path)}toString(){return Lt(this,Yn)}toJSON(){return this.toString()}toOptions(){let o,tt,rt,nt,ot="";const it=getProtocol("tcp"),st=getProtocol("udp"),at=getProtocol("ip4"),ct=getProtocol("ip6"),lt=getProtocol("dns6"),dt=getProtocol("ip6zone");for(const[mt,ft]of this.stringTuples())mt===dt.code&&(ot=`%${ft??""}`),DNS_CODES.includes(mt)&&(tt=it.name,nt=443,rt=`${ft??""}${ot}`,o=mt===lt.code?6:4),(mt===it.code||mt===st.code)&&(tt=getProtocol(mt).name,nt=parseInt(ft??"")),(mt===at.code||mt===ct.code)&&(tt=getProtocol(mt).name,rt=`${ft??""}${ot}`,o=mt===ct.code?6:4);if(o==null||tt==null||rt==null||nt==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:o,host:rt,transport:tt,port:nt}}protos(){return Lt(this,wn).map(([o])=>Object.assign({},getProtocol(o)))}protoCodes(){return Lt(this,wn).map(([o])=>o)}protoNames(){return Lt(this,wn).map(([o])=>getProtocol(o).name)}tuples(){return Lt(this,wn)}stringTuples(){return Lt(this,lo)}encapsulate(o){return o=new Dn(o),new Dn(this.toString()+o.toString())}decapsulate(o){const tt=o.toString(),rt=this.toString(),nt=rt.lastIndexOf(tt);if(nt<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${o.toString()}`);return new Dn(rt.slice(0,nt))}decapsulateCode(o){const tt=this.tuples();for(let rt=tt.length-1;rt>=0;rt--)if(tt[rt][0]===o)return new Dn(tuplesToBytes(tt.slice(0,rt)));return this}getPeerId(){try{let o=[];this.stringTuples().forEach(([rt,nt])=>{rt===names.p2p.code&&o.push([rt,nt]),rt===names["p2p-circuit"].code&&(o=[])});const tt=o.pop();if((tt==null?void 0:tt[1])!=null){const rt=tt[1];return rt[0]==="Q"||rt[0]==="1"?toString$t(base58btc$i.decode(`z${rt}`),"base58btc"):toString$t(CID$3.parse(rt).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return Lt(this,uo)}equals(o){return equals$c(this.bytes,o.bytes)}async resolve(o){const tt=this.protos().find(ot=>ot.resolvable);if(tt==null)return[this];const rt=resolvers$1.get(tt.name);if(rt==null)throw new NoAvailableResolverError(`no available resolver for ${tt.name}`);return(await rt(this,o)).map(ot=>multiaddr(ot))}nodeAddress(){const o=this.toOptions();if(o.transport!=="tcp"&&o.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${o.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:o.family,address:o.host,port:o.port}}isThinWaistAddress(o){const tt=(o??this).protos();return!(tt.length!==2||tt[0].code!==4&&tt[0].code!==41||tt[1].code!==6&&tt[1].code!==273)}[(na=symbol,inspect$1)](){return`Multiaddr(${Lt(this,Yn)})`}};Yn=new WeakMap,wn=new WeakMap,lo=new WeakMap,uo=new WeakMap;let Multiaddr=Dn;const resolvers$1=new Map;function isMultiaddr(et){return!!(et!=null&&et[symbol])}function multiaddr(et){return new Multiaddr(et)}const E_CANCELED=new Error("request for lock canceled");var __awaiter$2=function(et,o,tt,rt){function nt(ot){return ot instanceof tt?ot:new tt(function(it){it(ot)})}return new(tt||(tt=Promise))(function(ot,it){function st(lt){try{ct(rt.next(lt))}catch(dt){it(dt)}}function at(lt){try{ct(rt.throw(lt))}catch(dt){it(dt)}}function ct(lt){lt.done?ot(lt.value):nt(lt.value).then(st,at)}ct((rt=rt.apply(et,o||[])).next())})};class Semaphore{constructor(o,tt=E_CANCELED){this._value=o,this._cancelError=tt,this._queue=[],this._weightedWaiters=[]}acquire(o=1,tt=0){if(o<=0)throw new Error(`invalid weight ${o}: must be positive`);return new Promise((rt,nt)=>{const ot={resolve:rt,reject:nt,weight:o,priority:tt},it=findIndexFromEnd(this._queue,st=>tt<=st.priority);it===-1&&o<=this._value?this._dispatchItem(ot):this._queue.splice(it+1,0,ot)})}runExclusive(o){return __awaiter$2(this,arguments,void 0,function*(tt,rt=1,nt=0){const[ot,it]=yield this.acquire(rt,nt);try{return yield tt(ot)}finally{it()}})}waitForUnlock(o=1,tt=0){if(o<=0)throw new Error(`invalid weight ${o}: must be positive`);return this._couldLockImmediately(o,tt)?Promise.resolve():new Promise(rt=>{this._weightedWaiters[o-1]||(this._weightedWaiters[o-1]=[]),insertSorted(this._weightedWaiters[o-1],{resolve:rt,priority:tt})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(o){this._value=o,this._dispatchQueue()}release(o=1){if(o<=0)throw new Error(`invalid weight ${o}: must be positive`);this._value+=o,this._dispatchQueue()}cancel(){this._queue.forEach(o=>o.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(o){const tt=this._value;this._value-=o.weight,o.resolve([tt,this._newReleaser(o.weight)])}_newReleaser(o){let tt=!1;return()=>{tt||(tt=!0,this.release(o))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let o=this._value;o>0;o--){const tt=this._weightedWaiters[o-1];tt&&(tt.forEach(rt=>rt.resolve()),this._weightedWaiters[o-1]=[])}else{const o=this._queue[0].priority;for(let tt=this._value;tt>0;tt--){const rt=this._weightedWaiters[tt-1];if(!rt)continue;const nt=rt.findIndex(ot=>ot.priority<=o);(nt===-1?rt:rt.splice(0,nt)).forEach(ot=>ot.resolve())}}}_couldLockImmediately(o,tt){return(this._queue.length===0||this._queue[0].priorityo.priority<=rt.priority);et.splice(tt+1,0,o)}function findIndexFromEnd(et,o){for(let tt=et.length-1;tt>=0;tt--)if(o(et[tt]))return tt;return-1}var __awaiter$1=function(et,o,tt,rt){function nt(ot){return ot instanceof tt?ot:new tt(function(it){it(ot)})}return new(tt||(tt=Promise))(function(ot,it){function st(lt){try{ct(rt.next(lt))}catch(dt){it(dt)}}function at(lt){try{ct(rt.throw(lt))}catch(dt){it(dt)}}function ct(lt){lt.done?ot(lt.value):nt(lt.value).then(st,at)}ct((rt=rt.apply(et,o||[])).next())})};class Mutex{constructor(o){this._semaphore=new Semaphore(1,o)}acquire(){return __awaiter$1(this,arguments,void 0,function*(o=0){const[,tt]=yield this._semaphore.acquire(1,o);return tt})}runExclusive(o,tt=0){return this._semaphore.runExclusive(()=>o(),1,tt)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(o=0){return this._semaphore.waitForUnlock(1,o)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}class PeerManager{constructor(o,tt,rt){wt(this,"connectionManager");wt(this,"core");wt(this,"log");wt(this,"peers",new Map);wt(this,"healthManager");wt(this,"readMutex",new Mutex);wt(this,"writeMutex",new Mutex);wt(this,"writeLockHolder",null);this.connectionManager=o,this.core=tt,this.log=rt,this.healthManager=getHealthManager(),this.healthManager.updateProtocolHealth(this.core.multicodec,0)}getWriteLockHolder(){return this.writeLockHolder}getPeers(){return Array.from(this.peers.values())}async addPeer(o){return this.writeMutex.runExclusive(async()=>{this.writeLockHolder=`addPeer: ${o.id.toString()}`,await this.connectionManager.attemptDial(o.id),this.peers.set(o.id.toString(),o),this.log.info(`Added and dialed peer: ${o.id.toString()}`),this.healthManager.updateProtocolHealth(this.core.multicodec,this.peers.size),this.writeLockHolder=null})}async removePeer(o){return this.writeMutex.runExclusive(()=>{this.writeLockHolder=`removePeer: ${o.toString()}`,this.peers.delete(o.toString()),this.log.info(`Removed peer: ${o.toString()}`),this.healthManager.updateProtocolHealth(this.core.multicodec,this.peers.size),this.writeLockHolder=null})}async getPeerCount(){return this.readMutex.runExclusive(()=>this.peers.size)}async hasPeers(){return this.readMutex.runExclusive(()=>this.peers.size>0)}async removeExcessPeers(o){this.log.info(`Removing ${o} excess peer(s)`);const tt=Array.from(this.peers.values()).slice(0,o);for(const rt of tt)await this.removePeer(rt.id)}async findAndAddPeers(o){const tt=await this.findPeers(o);return tt.length===0?(this.log.warn("No additional peers found"),[]):this.addMultiplePeers(tt)}async findPeers(o){const tt=await this.core.getPeers();return this.readMutex.runExclusive(async()=>tt.filter(nt=>!this.peers.has(nt.id.toString())).slice(0,o))}async addMultiplePeers(o){const tt=[];for(const rt of o)await this.addPeer(rt),tt.push(rt);return tt}}const DEFAULT_NUM_PEERS_TO_USE=2,DEFAULT_MAINTAIN_PEERS_INTERVAL=3e4;class BaseProtocolSDK{constructor(o,tt,rt){wt(this,"core");wt(this,"connectionManager");wt(this,"peerManager");wt(this,"numPeersToUse");wt(this,"maintainPeersIntervalId",null);wt(this,"log");this.core=o,this.connectionManager=tt,this.log=new Logger$1(`sdk:${o.multicodec}`),this.numPeersToUse=(rt==null?void 0:rt.numPeersToUse)??DEFAULT_NUM_PEERS_TO_USE;const nt=(rt==null?void 0:rt.maintainPeersInterval)??DEFAULT_MAINTAIN_PEERS_INTERVAL;this.peerManager=new PeerManager(tt,o,this.log),this.log.info(`Initializing BaseProtocolSDK with numPeersToUse: ${this.numPeersToUse}, maintainPeersInterval: ${nt}ms`),this.startMaintainPeersInterval(nt)}get connectedPeers(){return this.peerManager.getPeers().slice(0,this.numPeersToUse)}async renewPeer(o){this.log.info(`Attempting to renew peer ${o}`);const tt=await this.peerManager.findPeers(1);if(tt.length===0){this.log.error("Failed to find a new peer to replace the disconnected one");return}return await this.peerManager.removePeer(o),await this.peerManager.addPeer(tt[0]),this.log.info(`Successfully renewed peer. New peer: ${tt[0].id}`),tt[0]}stopMaintainPeersInterval(){this.maintainPeersIntervalId?(clearInterval(this.maintainPeersIntervalId),this.maintainPeersIntervalId=null,this.log.info("Maintain peers interval stopped")):this.log.info("Maintain peers interval was not running")}async hasPeers(o={}){const{forceUseAllPeers:tt=!1,maxAttempts:rt=3}=o;this.log.info(`Checking for peers. forceUseAllPeers: ${tt}, maxAttempts: ${rt}`);for(let nt=0;nt0)return this.log.info(`At least one peer connected (${this.connectedPeers.length}), not forcing use of all peers`),!0;if(this.connectedPeers.length>=this.numPeersToUse)return this.log.info(`Required number of peers (${this.numPeersToUse}) reached`),!0;this.log.warn(`Found only ${this.connectedPeers.length}/${this.numPeersToUse} required peers. Retrying...`)}return this.log.error(`Failed to find required number of peers (${this.numPeersToUse}) after ${rt} attempts`),!1}async startMaintainPeersInterval(o){this.log.info(`Starting maintain peers interval with ${o}ms interval`);try{this.maintainPeersIntervalId=setInterval(()=>{this.log.info("Running scheduled peer maintenance"),this.maintainPeers().catch(tt=>{this.log.error("Error during scheduled peer maintenance:",tt)})},o),this.log.info("Maintain peers interval started successfully")}catch(tt){throw this.log.error("Error starting maintain peers interval:",tt),tt}}async maintainPeers(){try{const o=await this.peerManager.getPeerCount(),tt=this.numPeersToUse-o;if(this.log.info(`Current peer count: ${o}, target: ${this.numPeersToUse}`),tt===0){this.log.info("Peer count is at target, no maintenance required");return}tt>0?(this.log.info(`Attempting to add ${tt} peer(s)`),await this.peerManager.findAndAddPeers(tt)):(this.log.info(`Attempting to remove ${Math.abs(tt)} excess peer(s)`),await this.peerManager.removeExcessPeers(Math.abs(tt)));const rt=await this.peerManager.getPeerCount();this.log.info(`Peer maintenance completed. Initial count: ${o}, Final count: ${rt}`)}catch(o){this.log.error("Error during peer maintenance",{error:o})}}}const DEFAULT_KEEP_ALIVE=6e4,DEFAULT_LIGHT_PUSH_FILTER_CHECK=!1,DEFAULT_LIGHT_PUSH_FILTER_CHECK_INTERVAL=1e4,DEFAULT_SUBSCRIBE_OPTIONS={keepAlive:DEFAULT_KEEP_ALIVE,enableLightPushFilterCheck:DEFAULT_LIGHT_PUSH_FILTER_CHECK};function messageHash(et,o){const tt=utf8ToBytes$1(et),rt=utf8ToBytes$1(o.contentTopic),nt=tryConvertTimestampToBytes(o.timestamp),ot=concat$5([tt,o.payload,rt,o.meta,nt].filter(isDefined));return sha256$3(ot)}function tryConvertTimestampToBytes(et){if(!et)return;let o;return typeof et=="bigint"?o=et:o=BigInt(et.valueOf())*1000000n,numberToBytes(o)}function messageHashStr(et,o){const tt=messageHash(et,o);return bytesToHex$1(tt)}const log$h=new Logger$1("sdk:receiver:reliability_monitor"),DEFAULT_MAX_PINGS=3,MESSAGE_VERIFICATION_DELAY=5e3;class ReceiverReliabilityMonitor{constructor(o,tt,rt,nt,ot,it,st){wt(this,"pubsubTopic");wt(this,"getPeers");wt(this,"renewPeer");wt(this,"getContentTopics");wt(this,"protocolSubscribe");wt(this,"addLibp2pEventListener");wt(this,"sendLightPushMessage");wt(this,"receivedMessagesFormPeer",new Set);wt(this,"receivedMessages",new Set);wt(this,"scheduledVerification",new Map);wt(this,"verifiedPeers",new Set);wt(this,"peerFailures",new Map);wt(this,"maxPingFailures",DEFAULT_MAX_PINGS);wt(this,"peerRenewalLocks",new Set);this.pubsubTopic=o,this.getPeers=tt,this.renewPeer=rt,this.getContentTopics=nt,this.protocolSubscribe=ot,this.addLibp2pEventListener=it,this.sendLightPushMessage=st,this.addLibp2pEventListener("peer:disconnect",at=>{const ct=at.detail;this.getPeers().some(lt=>lt.id.equals(ct))&&this.renewAndSubscribePeer(ct)})}setMaxPingFailures(o){o!==void 0&&(this.maxPingFailures=o)}async handlePingResult(o,tt){if(tt!=null&&tt.success){this.peerFailures.delete(o.toString());return}const rt=(this.peerFailures.get(o.toString())||0)+1;if(this.peerFailures.set(o.toString(),rt),rt>=this.maxPingFailures)try{log$h.info(`Attempting to renew ${o.toString()} due to ping failures.`),await this.renewAndSubscribePeer(o),this.peerFailures.delete(o.toString())}catch(nt){log$h.error(`Failed to renew peer ${o.toString()}: ${nt}.`)}}notifyMessageReceived(o,tt){const rt=this.buildMessageHash(tt);return this.verifiedPeers.add(o),this.receivedMessagesFormPeer.add(`${o}-${rt}`),log$h.info(`notifyMessage received debug: ephemeral:${tt.ephemeral} ${bytesToUtf8(tt.payload)}`),log$h.info(`notifyMessage received: peer:${o} message:${rt}`),this.receivedMessages.has(rt)?!0:(this.receivedMessages.add(rt),!1)}notifyMessageSent(o,tt){const rt=o.toString(),nt=this.buildMessageHash(tt);if(log$h.info(`notifyMessage sent debug: ${bytesToUtf8(tt.payload)}`),this.scheduledVerification.has(rt)){log$h.warn(`notifyMessage sent: attempting to schedule verification for pending peer:${rt} message:${nt}`);return}const ot=window.setTimeout(async()=>{const it=this.verifiedPeers.has(rt),st=this.receivedMessagesFormPeer.has(`${rt}-${nt}`);if(it||st){log$h.info(`notifyMessage sent setTimeout: verified that peer pushes filter messages, peer:${rt} message:${nt}`);return}log$h.warn(`notifyMessage sent setTimeout: peer didn't return probe message, attempting renewAndSubscribe, peer:${rt} message:${nt}`),this.scheduledVerification.delete(rt),await this.renewAndSubscribePeer(o)},MESSAGE_VERIFICATION_DELAY);this.scheduledVerification.set(rt,ot)}shouldVerifyPeer(o){const tt=o.toString(),rt=this.verifiedPeers.has(tt),nt=this.scheduledVerification.has(tt);return!(rt||nt)}buildMessageHash(o){return messageHashStr(this.pubsubTopic,o)}async renewAndSubscribePeer(o){const tt=o.toString();try{if(this.peerRenewalLocks.has(tt)){log$h.info(`Peer ${tt} is already being renewed.`);return}this.peerRenewalLocks.add(tt);const rt=await this.renewPeer(o);if(!rt){log$h.warn(`Failed to renew peer ${tt}: No new peer found.`);return}return await this.protocolSubscribe(this.pubsubTopic,rt,this.getContentTopics()),await this.sendLightPushMessage(rt),this.peerFailures.delete(tt),rt}catch(rt){log$h.error(`Failed to renew peer ${tt}: ${rt}.`);return}finally{this.peerRenewalLocks.delete(tt)}}}const On=class On{static createReceiverMonitor(o,tt,rt,nt,ot,it,st){if(On.receiverMonitors.has(o))return On.receiverMonitors.get(o);const at=new ReceiverReliabilityMonitor(o,tt,rt,nt,ot,it,st);return On.receiverMonitors.set(o,at),at}constructor(){}static stop(o){this.receiverMonitors.delete(o)}static stopAll(){for(const[o,tt]of this.receiverMonitors)tt.setMaxPingFailures(void 0),this.receiverMonitors.delete(o)}};wt(On,"receiverMonitors",new Map);let ReliabilityMonitorManager=On;const log$g=new Logger$1("sdk:filter:subscription_manager");class SubscriptionManager{constructor(o,tt,rt,nt,ot,it,st){wt(this,"pubsubTopic");wt(this,"protocol");wt(this,"connectionManager");wt(this,"getPeers");wt(this,"renewPeer");wt(this,"libp2p");wt(this,"lightPush");wt(this,"reliabilityMonitor");wt(this,"keepAliveTimeout",DEFAULT_KEEP_ALIVE);wt(this,"keepAliveInterval",null);wt(this,"enableLightPushFilterCheck",DEFAULT_LIGHT_PUSH_FILTER_CHECK);wt(this,"subscriptionCallbacks");this.pubsubTopic=o,this.protocol=tt,this.connectionManager=rt,this.getPeers=nt,this.renewPeer=ot,this.libp2p=it,this.lightPush=st,this.pubsubTopic=o,this.subscriptionCallbacks=new Map,this.reliabilityMonitor=ReliabilityMonitorManager.createReceiverMonitor(this.pubsubTopic,this.getPeers.bind(this),this.renewPeer.bind(this),()=>Array.from(this.subscriptionCallbacks.keys()),this.protocol.subscribe.bind(this.protocol),this.protocol.addLibp2pEventListener.bind(this.protocol),this.sendLightPushCheckMessage.bind(this))}async subscribe(o,tt,rt=DEFAULT_SUBSCRIBE_OPTIONS){this.reliabilityMonitor.setMaxPingFailures(rt.pingsBeforePeerRenewed),this.keepAliveTimeout=rt.keepAlive||DEFAULT_KEEP_ALIVE,this.enableLightPushFilterCheck=(rt==null?void 0:rt.enableLightPushFilterCheck)||DEFAULT_LIGHT_PUSH_FILTER_CHECK;const nt=Array.isArray(o)?o:[o];for(const lt of nt)if(lt.pubsubTopic!==this.pubsubTopic)return{failures:[{error:ProtocolError$1.TOPIC_DECODER_MISMATCH}],successes:[]};this.enableLightPushFilterCheck&&nt.push(createDecoder(this.buildLightPushContentTopic(),this.pubsubTopic));const ot=groupByContentTopic(nt),it=Array.from(ot.keys()),st=this.getPeers().map(async lt=>this.subscribeWithPeerVerification(lt,it)),at=await Promise.allSettled(st),ct=this.handleResult(at,"subscribe");return ot.forEach((lt,dt)=>{const ht={decoders:lt,callback:tt};dt!==this.buildLightPushContentTopic()&&this.subscriptionCallbacks.set(dt,ht)}),this.startSubscriptionsMaintenance(this.keepAliveTimeout),ct}async unsubscribe(o){const tt=this.getPeers().map(async ot=>{const it=await this.protocol.unsubscribe(this.pubsubTopic,ot,o);return o.forEach(st=>{this.subscriptionCallbacks.delete(st)}),it}),rt=await Promise.allSettled(tt),nt=this.handleResult(rt,"unsubscribe");return this.subscriptionCallbacks.size===0&&this.stopSubscriptionsMaintenance(),nt}async ping(o){log$g.info("Sending keep-alive ping");const rt=(o?[o]:this.getPeers().map(ot=>ot.id)).map(ot=>this.pingSpecificPeer(ot)),nt=await Promise.allSettled(rt);return this.handleResult(nt,"ping")}async unsubscribeAll(){const o=this.getPeers().map(async nt=>this.protocol.unsubscribeAll(this.pubsubTopic,nt)),tt=await Promise.allSettled(o);this.subscriptionCallbacks.clear();const rt=this.handleResult(tt,"unsubscribeAll");return this.stopSubscriptionsMaintenance(),rt}async processIncomingMessage(o,tt){if(this.reliabilityMonitor.notifyMessageReceived(tt,o)){log$g.info("Message already received, skipping");return}const{contentTopic:nt}=o,ot=this.subscriptionCallbacks.get(nt);if(!ot){log$g.error("No subscription callback available for ",nt);return}log$g.info("Processing message with content topic ",nt," on pubsub topic ",this.pubsubTopic),await pushMessage(ot,this.pubsubTopic,o)}async subscribeWithPeerVerification(o,tt){const rt=await this.protocol.subscribe(this.pubsubTopic,o,tt);return await this.sendLightPushCheckMessage(o),rt}handleResult(o,tt){const rt={failures:[],successes:[]};for(const nt of o)if(nt.status==="rejected")log$g.error(`Failed to resolve ${tt} promise successfully: `,nt.reason),rt.failures.push({error:ProtocolError$1.GENERIC_FAIL});else{const ot=nt.value;ot.failure?rt.failures.push(ot.failure):rt.successes.push(ot.success)}return rt}async pingSpecificPeer(o){var nt,ot;const tt=this.getPeers().find(it=>it.id.equals(o));if(!tt)return{success:null,failure:{peerId:o,error:ProtocolError$1.NO_PEER_AVAILABLE}};let rt;try{rt=await this.protocol.ping(tt)}catch{rt={success:null,failure:{peerId:o,error:ProtocolError$1.GENERIC_FAIL}}}return log$g.info(`Received result from filter ping peerId:${o.toString()} success:${(nt=rt.success)==null?void 0:nt.toString()} failure:${(ot=rt.failure)==null?void 0:ot.error}`),await this.reliabilityMonitor.handlePingResult(o,rt),rt}startSubscriptionsMaintenance(o){log$g.info("Starting subscriptions maintenance"),this.startKeepAlivePings(o),this.startConnectionListener()}stopSubscriptionsMaintenance(){log$g.info("Stopping subscriptions maintenance"),this.stopKeepAlivePings(),this.stopConnectionListener()}startConnectionListener(){this.connectionManager.addEventListener(EConnectionStateEvents.CONNECTION_STATUS,this.connectionListener.bind(this))}stopConnectionListener(){this.connectionManager.removeEventListener(EConnectionStateEvents.CONNECTION_STATUS,this.connectionListener.bind(this))}async connectionListener({detail:o}){if(!o){this.stopKeepAlivePings();return}try{await this.ping()}catch(tt){log$g.error(`networkStateListener failed to recover: ${tt}`)}this.startKeepAlivePings(this.keepAliveTimeout)}startKeepAlivePings(o){if(this.keepAliveInterval){log$g.info("Recurring pings already set up.");return}this.keepAliveInterval=setInterval(()=>{this.ping()},o)}stopKeepAlivePings(){if(!this.keepAliveInterval){log$g.info("Already stopped recurring pings.");return}log$g.info("Stopping recurring pings."),clearInterval(this.keepAliveInterval),this.keepAliveInterval=null}async sendLightPushCheckMessage(o){if(this.lightPush&&this.libp2p&&this.reliabilityMonitor.shouldVerifyPeer(o.id)){const tt=createEncoder({contentTopic:this.buildLightPushContentTopic(),pubsubTopic:this.pubsubTopic,ephemeral:!0}),rt={payload:new Uint8Array(1)},nt=await tt.toProtoObj(rt);setTimeout(async()=>{const ot=await this.lightPush.protocol.send(tt,rt,o);if(this.reliabilityMonitor.notifyMessageSent(o.id,nt),ot.failure){log$g.error(`failed to send lightPush ping message to peer:${o.id.toString()} ${ot.failure.error}`);return}},DEFAULT_LIGHT_PUSH_FILTER_CHECK_INTERVAL)}}buildLightPushContentTopic(){return`/js-waku-subscription-ping/1/${this.libp2p.peerId.toString()}/utf8`}}async function pushMessage(et,o,tt){const{decoders:rt,callback:nt}=et,{contentTopic:ot}=tt;if(!ot){log$g.warn("Message has no content topic, skipping");return}try{const it=rt.map(at=>at.fromProtoObj(o,tt).then(ct=>ct||Promise.reject("Decoding failed"))),st=await Promise.any(it);await nt(st)}catch(it){log$g.error("Error decoding message",it)}}const log$f=new Logger$1("sdk:filter");class Filter extends BaseProtocolSDK{constructor(tt,rt,nt,ot){super(new FilterCore(async(it,st,at)=>{const ct=this.getActiveSubscription(it);if(!ct){log$f.error(`No subscription locally registered for topic ${it}`);return}await ct.processIncomingMessage(st,at)},tt.configuredPubsubTopics,rt),tt,{numPeersToUse:ot==null?void 0:ot.numPeersToUse});wt(this,"libp2p");wt(this,"lightPush");wt(this,"protocol");wt(this,"activeSubscriptions",new Map);this.libp2p=rt,this.lightPush=nt,this.protocol=this.core,this.activeSubscriptions=new Map}async subscribe(tt,rt,nt,ot=DEFAULT_SUBSCRIBE_OPTIONS){const it=this.getUniquePubsubTopics(tt);if(it.length!==1)return{subscription:null,error:ProtocolError$1.INVALID_DECODER_TOPICS,results:null};const st=it[0],{subscription:at,error:ct}=await this.createSubscription(st,nt);if(ct)return{subscription:null,error:ct,results:null};const{failures:lt,successes:dt}=await at.subscribe(tt,rt,ot);return{subscription:at,error:null,results:{failures:lt,successes:dt}}}async createSubscription(tt,rt){var st;rt={autoRetry:!0,...rt};const nt=typeof tt=="string"?tt:(st=shardInfoToPubsubTopics(tt))==null?void 0:st[0];return ensurePubsubTopicIsConfigured(nt,this.protocol.pubsubTopics),await this.hasPeers(rt)?(log$f.info(`Creating filter subscription with ${this.connectedPeers.length} peers: `,this.connectedPeers.map(at=>at.id.toString())),{error:null,subscription:this.getActiveSubscription(nt)??this.setActiveSubscription(nt,new SubscriptionManager(nt,this.protocol,this.connectionManager,()=>this.connectedPeers,this.renewPeer.bind(this),this.libp2p,this.lightPush))}):{error:ProtocolError$1.NO_PEER_AVAILABLE,subscription:null}}async subscribeWithUnsubscribe(tt,rt,nt=DEFAULT_SUBSCRIBE_OPTIONS){const ot=this.getUniquePubsubTopics(tt);if(ot.length===0)throw Error("Failed to subscribe: no pubsubTopic found on decoders provided.");if(ot.length>1)throw Error("Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.");const{subscription:it,error:st}=await this.createSubscription(ot[0]);if(st)throw Error(`Failed to create subscription: ${st}`);await it.subscribe(tt,rt,nt);const at=Array.from(groupByContentTopic(Array.isArray(tt)?tt:[tt]).keys());return async()=>{await it.unsubscribe(at)}}toSubscriptionIterator(tt){return toAsyncIterator(this,tt)}getActiveSubscription(tt){return this.activeSubscriptions.get(tt)}setActiveSubscription(tt,rt){return this.activeSubscriptions.set(tt,rt),rt}getUniquePubsubTopics(tt){return Array.isArray(tt)?tt.length===0?[]:[...new Set(tt.map(nt=>nt.pubsubTopic))]:[tt.pubsubTopic]}}function wakuFilter(et,o,tt){return rt=>new Filter(et,rt,o,tt)}const log$e=new Logger$1("sdk:light-push"),DEFAULT_MAX_ATTEMPTS=3,DEFAULT_SEND_OPTIONS={autoRetry:!1,maxAttempts:DEFAULT_MAX_ATTEMPTS};class LightPush{constructor(o,tt,rt){wt(this,"libp2p");wt(this,"numPeersToUse",DEFAULT_NUM_PEERS_TO_USE);wt(this,"protocol");this.libp2p=tt,this.numPeersToUse=(rt==null?void 0:rt.numPeersToUse)??DEFAULT_NUM_PEERS_TO_USE,this.protocol=new LightPushCore(o.configuredPubsubTopics,tt)}async send(o,tt,rt=DEFAULT_SEND_OPTIONS){const nt=[],ot=[],{pubsubTopic:it}=o;try{ensurePubsubTopicIsConfigured(it,this.protocol.pubsubTopics)}catch{return log$e.error("Failed to send waku light push: pubsub topic not configured"),{successes:nt,failures:[{error:ProtocolError$1.TOPIC_NOT_CONFIGURED}]}}const st=await this.getConnectedPeers();if(st.length===0)return{successes:nt,failures:[{error:ProtocolError$1.NO_PEER_AVAILABLE}]};const at=await Promise.allSettled(st.map(ct=>this.protocol.send(o,tt,ct)));for(const ct of at){if(ct.status!=="fulfilled"){log$e.error("Failed unexpectedly while sending:",ct.reason),ot.push({error:ProtocolError$1.GENERIC_FAIL});continue}const{failure:lt,success:dt}=ct.value;if(dt){nt.push(dt);continue}lt&&(ot.push(lt),rt!=null&&rt.autoRetry&&this.attemptRetries(ht=>this.protocol.send(o,tt,ht),rt.maxAttempts))}return getHealthManager().updateProtocolHealth(this.protocol.multicodec,nt.length),{successes:nt,failures:ot}}async attemptRetries(o,tt){var nt;tt=tt||DEFAULT_MAX_ATTEMPTS;const rt=await this.getConnectedPeers();if(rt.length===0){log$e.warn("Cannot retry with no connected peers.");return}for(let ot=0;ot{try{return await this.libp2p.peerStore.get(rt)}catch{return null}}))).filter(rt=>!!rt).filter(rt=>rt.protocols.includes(LightPushCodec)).slice(0,this.numPeersToUse)}}function wakuLightPush(et,o={}){return tt=>new LightPush(et,tt,o)}const DEFAULT_NUM_PEERS=1,log$d=new Logger$1("waku:store:sdk");class Store extends BaseProtocolSDK{constructor(tt,rt,nt){super(new StoreCore(tt.configuredPubsubTopics,rt),tt,{numPeersToUse:DEFAULT_NUM_PEERS});wt(this,"peerIdStrToUse");wt(this,"protocol");this.peerIdStrToUse=nt,this.protocol=this.core}async*queryGenerator(tt,rt){const{pubsubTopic:nt,contentTopics:ot,decodersAsMap:it}=this.validateDecodersAndPubsubTopic(tt),st={pubsubTopic:nt,contentTopics:ot,includeData:!0,paginationForward:!0,...rt},at=(await this.protocol.getPeers({numPeers:this.numPeersToUse,maxBootstrapPeers:1,peerIdStr:this.peerIdStrToUse}))[0];if(!at)throw log$d.error("No peers available to query"),new Error("No peers available to query");log$d.info(`Querying store with options: ${JSON.stringify(rt)}`);const ct=this.protocol.queryPerPage(st,it,at);for await(const lt of ct)yield lt}async queryWithOrderedCallback(tt,rt,nt){log$d.info("Querying store with ordered callback");for await(const ot of this.queryGenerator(tt,nt))if(await this.processMessages(ot,rt))break}async queryWithPromiseCallback(tt,rt,nt){log$d.info("Querying store with promise callback");let ot=!1;for await(const it of this.queryGenerator(tt,nt)){const st=it.map(async at=>{ot||(ot=!!await rt(at))});if(await Promise.all(st),ot)break}}async processMessages(tt,rt){let nt=!1;const it=(await Promise.all(tt)).filter(isDefined);return await Promise.all(it.map(async st=>{st&&!nt&&(nt=!!await rt(st))})),nt}createCursor(tt){return messageHash(tt.pubsubTopic,tt)}validateDecodersAndPubsubTopic(tt){if(tt.length===0)throw log$d.error("No decoders provided"),new Error("No decoders provided");const rt=Array.from(new Set(tt.map(st=>st.pubsubTopic)));if(rt.length>1)throw log$d.error("API does not support querying multiple pubsub topics at once"),new Error("API does not support querying multiple pubsub topics at once");const nt=rt[0];ensurePubsubTopicIsConfigured(nt,this.protocol.pubsubTopics);const ot=new Map;tt.forEach(st=>{if(ot.has(st.contentTopic))throw log$d.error("API does not support different decoder per content topic"),new Error("API does not support different decoder per content topic");ot.set(st.contentTopic,st)});const it=tt.filter(st=>st.pubsubTopic===nt).map(st=>st.contentTopic);if(it.length===0)throw log$d.error(`No decoders found for topic ${nt}`),new Error("No decoders found for topic "+nt);return{pubsubTopic:nt,contentTopics:it,decodersAsMap:ot}}}function wakuStore(et,o){return tt=>new Store(et,tt,o)}const log$c=new Logger$1("wait-for-remote-peer");async function waitForRemotePeer(et,o,tt){o=o!=null&&o.length?o:getEnabledProtocols(et);const rt=et.libp2p.getConnections();if(!et.isStarted())throw Error("Waku node is not started");if(rt.length>0&&!o.includes(Protocols.Relay)&&await waitForMetadata(et,o))return;const nt=[];if(o.includes(Protocols.Relay)){if(!et.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");nt.push(et.relay.waitForPeers())}if(o.includes(Protocols.Store)){if(!et.store)throw Error("Cannot wait for Store peer: protocol not mounted");nt.push(waitForConnectedPeer(StoreCodec,et.libp2p))}if(o.includes(Protocols.LightPush)){if(!et.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");nt.push(waitForConnectedPeer(LightPushCodec,et.libp2p))}if(o.includes(Protocols.Filter)){if(!et.filter)throw new Error("Cannot wait for Filter peer: protocol not mounted");nt.push(waitForConnectedPeer(FilterCodecs.SUBSCRIBE,et.libp2p))}tt?await rejectOnTimeout(Promise.all(nt),tt,"Timed out waiting for a remote peer."):await Promise.all(nt)}async function waitForConnectedPeer(et,o){log$c.info(`Waiting for ${et} peer.`),await new Promise(tt=>{const rt=async nt=>{var ot,it;if((it=(ot=nt.detail)==null?void 0:ot.protocols)!=null&&it.includes(et)){const st=o.services.metadata;if(!st){o.removeEventListener("peer:identify",rt),tt();return}try{await st.confirmOrAttemptHandshake(nt.detail.peerId),o.removeEventListener("peer:identify",rt),tt()}catch(at){at.code==="ERR_CONNECTION_BEING_CLOSED"&&log$c.error("Connection closed. Some peers can be on different shard."),log$c.error(`Error waiting for metadata: ${at}`)}}};o.addEventListener("peer:identify",rt)})}async function waitForMetadata(et,o){const tt=et.libp2p.getPeers(),rt=et.libp2p.services.metadata,nt=mapProtocolsToCodecs(o);if(!tt.length||!rt)return log$c.info(`Skipping waitForMetadata due to missing connections:${tt.length} or metadataService:${!!rt}`),!1;for(const ot of tt)try{const it=await et.libp2p.peerStore.get(ot);if(it.protocols.some(at=>nt.has(at))&&!(await rt.confirmOrAttemptHandshake(ot)).error&&(it.protocols.forEach(lt=>{nt.has(lt)&&nt.set(lt,!0)}),Array.from(nt.values()).every(lt=>lt)))return!0}catch(it){it.code==="ERR_CONNECTION_BEING_CLOSED"&&log$c.error("Connection closed. Some peers can be on different shard."),log$c.error(`Error while iterating through peers: ${it}`);continue}return!1}const awaitTimeout=(et,o)=>new Promise((tt,rt)=>setTimeout(()=>rt(Error(o)),et));async function rejectOnTimeout(et,o,tt){await Promise.race([et,awaitTimeout(o,tt)])}function getEnabledProtocols(et){const o=[];return et.relay&&o.push(Protocols.Relay),et.filter&&o.push(Protocols.Filter),et.store&&o.push(Protocols.Store),et.lightPush&&o.push(Protocols.LightPush),o}function mapProtocolsToCodecs(et){const o=new Map,tt={[Protocols.Filter]:FilterCodecs.SUBSCRIBE,[Protocols.LightPush]:LightPushCodec,[Protocols.Store]:StoreCodec};for(const rt of et)tt[rt]&&o.set(tt[rt],!1);return o}const DefaultPingKeepAliveValueSecs=5*60,DefaultRelayKeepAliveValueSecs=5*60,DefaultUserAgent="js-waku",DefaultPingMaxInboundStreams=10,log$b=new Logger$1("waku");class WakuNode{constructor(o,tt,rt,nt,ot){wt(this,"pubsubTopics");wt(this,"libp2p");wt(this,"relay");wt(this,"store");wt(this,"filter");wt(this,"lightPush");wt(this,"connectionManager");wt(this,"health");var ct;this.pubsubTopics=o,this.relay=ot,this.libp2p=rt,nt={filter:!1,lightpush:!1,store:!1,...nt};const it=tt.pingKeepAlive||DefaultPingKeepAliveValueSecs,st=this.relay?tt.relayKeepAlive||DefaultRelayKeepAliveValueSecs:0,at=this.libp2p.peerId.toString();if(this.connectionManager=ConnectionManager.create(at,rt,{pingKeepAlive:it,relayKeepAlive:st},this.pubsubTopics,this.relay),this.health=getHealthManager(),nt.store){let lt;(ct=tt.nodeToUse)!=null&&ct.store&&this.dialMultiaddr(tt.nodeToUse.store,StoreCodec).catch(ht=>{log$b.error("Failed to dial store peer",ht)});const dt=wakuStore(this.connectionManager,lt);this.store=dt(rt)}if(nt.lightpush){const lt=wakuLightPush(this.connectionManager,tt);this.lightPush=lt(rt)}if(nt.filter){const lt=wakuFilter(this.connectionManager,this.lightPush,tt);this.filter=lt(rt)}log$b.info("Waku node created",at,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}async dial(o,tt){const rt=tt??[],nt=this.mapToPeerIdOrMultiaddr(o);typeof tt>"u"&&(this.relay&&rt.push(Protocols.Relay),this.store&&rt.push(Protocols.Store),this.filter&&rt.push(Protocols.Filter),this.lightPush&&rt.push(Protocols.LightPush));const ot=[];return rt.includes(Protocols.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach(it=>ot.push(it)):log$b.error("Relay codec not included in dial codec: protocol not mounted locally")),rt.includes(Protocols.Store)&&(this.store?ot.push(this.store.protocol.multicodec):log$b.error("Store codec not included in dial codec: protocol not mounted locally")),rt.includes(Protocols.LightPush)&&(this.lightPush?ot.push(this.lightPush.protocol.multicodec):log$b.error("Light Push codec not included in dial codec: protocol not mounted locally")),rt.includes(Protocols.Filter)&&(this.filter?ot.push(this.filter.protocol.multicodec):log$b.error("Filter codec not included in dial codec: protocol not mounted locally")),log$b.info(`Dialing to ${nt.toString()} with protocols ${rt}`),this.libp2p.dialProtocol(nt,ot)}async start(){await this.libp2p.start()}async stop(){ReliabilityMonitorManager.stopAll(),this.connectionManager.stop(),await this.libp2p.stop()}async waitForPeers(o,tt){return waitForRemotePeer(this,o,tt)}isStarted(){return this.libp2p.status=="started"}isConnected(){return this.connectionManager.isConnected()}async dialMultiaddr(o,tt){const rt=multiaddr(o);if(!rt.getPeerId())throw new Error("Failed to dial multiaddr: missing peer ID");return await this.libp2p.dialProtocol(rt,[tt]),rt.getPeerId()}mapToPeerIdOrMultiaddr(o){return isPeerId$2(o)?o:multiaddr(o)}}var ds;let InvalidParametersError$3=(ds=class extends Error{constructor(o="Invalid parameters"){super(o),this.name="InvalidParametersError"}},wt(ds,"name","InvalidParametersError"),ds);class InvalidPublicKeyError extends Error{constructor(o="Invalid public key"){super(o),this.name="InvalidPublicKeyError"}}wt(InvalidPublicKeyError,"name","InvalidPublicKeyError");var hs;let UnsupportedKeyTypeError$1=(hs=class extends Error{constructor(o="Unsupported key type"){super(o),this.name="UnsupportedKeyTypeError"}},wt(hs,"name","UnsupportedKeyTypeError"),hs);function equals$b(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;tt=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$i=base$i,_brrp__multiformats_scope_baseX$h=src$i;let Encoder$i=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$i=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$j(this,o)}},ComposedDecoder$h=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$j(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$j(et,o){return new ComposedDecoder$h({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$h=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$i(o,tt,rt),this.decoder=new Decoder$i(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$k({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$h(et,o,tt,rt)}function baseX$h({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$h(tt,et);return from$k({prefix:o,name:et,encode:rt,decode:ot=>coerce$i(nt(ot))})}function decode$O(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$G(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<=INT$4;)o[tt++]=et&255|MSB$6,et/=128;for(;et&MSBALL$4;)o[tt++]=et&255|MSB$6,et>>>=7;return o[tt]=et|0,encode$F.bytes=tt-rt+1,o}var decode$N=read$5,MSB$1$4=128,REST$1$4=127;function read$5(et,rt){var tt=0,rt=rt||0,nt=0,ot=rt,it,st=et.length;do{if(ot>=st)throw read$5.bytes=0,new RangeError("Could not decode varint");it=et[ot++],tt+=nt<28?(it&REST$1$4)<=MSB$1$4);return read$5.bytes=ot-rt,tt}var N1$4=Math.pow(2,7),N2$4=Math.pow(2,14),N3$4=Math.pow(2,21),N4$4=Math.pow(2,28),N5$4=Math.pow(2,35),N6$4=Math.pow(2,42),N7$4=Math.pow(2,49),N8$4=Math.pow(2,56),N9$4=Math.pow(2,63),length$4=function(et){return et{const[dt,ht]=decode$M(o.subarray(tt));return tt+=ht,dt};let nt=rt(),ot=DAG_PB_CODE$2;if(nt===18?(nt=0,tt=0):ot=rt(),nt!==0&&nt!==1)throw new RangeError(`Invalid CID version ${nt}`);const it=tt,st=rt(),at=rt(),ct=tt+at,lt=ct-it;return{version:nt,codec:ot,multihashCode:st,digestSize:at,multihashSize:lt,size:ct}}static parse(o,tt){const[rt,nt]=parseCIDtoBytes$2(o,tt),ot=Nr.decode(nt);if(ot.version===0&&o[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$2(ot).set(rt,o),ot}};function parseCIDtoBytes$2(et,o){switch(et[0]){case"Q":{const tt=o??base58btc$h;return[base58btc$h.prefix,tt.decode(`${base58btc$h.prefix}${et}`)]}case base58btc$h.prefix:{const tt=o??base58btc$h;return[base58btc$h.prefix,tt.decode(et)]}case base32$u.prefix:{const tt=o??base32$u;return[base32$u.prefix,tt.decode(et)]}case base36$r.prefix:{const tt=o??base36$r;return[base36$r.prefix,tt.decode(et)]}default:{if(o==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[et[0],o.decode(et)]}}}function toStringV0$2(et,o,tt){const{prefix:rt}=tt;if(rt!==base58btc$h.prefix)throw Error(`Cannot string encode V0 in ${tt.name} encoding`);const nt=o.get(rt);if(nt==null){const ot=tt.encode(et).slice(1);return o.set(rt,ot),ot}else return nt}function toStringV1$2(et,o,tt){const{prefix:rt}=tt,nt=o.get(rt);if(nt==null){const ot=tt.encode(et);return o.set(rt,ot),ot}else return nt}const DAG_PB_CODE$2=112,SHA_256_CODE$2=18;function encodeCID$2(et,o,tt){const rt=encodingLength$4(et),nt=rt+encodingLength$4(o),ot=new Uint8Array(nt+tt.byteLength);return encodeTo$2(et,ot,0),encodeTo$2(o,ot,rt),ot.set(tt,nt),ot}const cidSymbol$2=Symbol.for("@ipld/js-cid/CID"),code$2=0,name$4="identity",encode$E=coerce$i;function digest$1(et){return create$5(code$2,encode$E(et))}const identity$f={code:code$2,name:name$4,encode:encode$E,digest:digest$1};function equals$9(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;ttBigInt(et))),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends HashMD{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:o,Al:tt,Bh:rt,Bl:nt,Ch:ot,Cl:it,Dh:st,Dl:at,Eh:ct,El:lt,Fh:dt,Fl:ht,Gh:mt,Gl:ft,Hh:pt,Hl:gt}=this;return[o,tt,rt,nt,ot,it,st,at,ct,lt,dt,ht,mt,ft,pt,gt]}set(o,tt,rt,nt,ot,it,st,at,ct,lt,dt,ht,mt,ft,pt,gt){this.Ah=o|0,this.Al=tt|0,this.Bh=rt|0,this.Bl=nt|0,this.Ch=ot|0,this.Cl=it|0,this.Dh=st|0,this.Dl=at|0,this.Eh=ct|0,this.El=lt|0,this.Fh=dt|0,this.Fl=ht|0,this.Gh=mt|0,this.Gl=ft|0,this.Hh=pt|0,this.Hl=gt|0}process(o,tt){for(let xt=0;xt<16;xt++,tt+=4)SHA512_W_H[xt]=o.getUint32(tt),SHA512_W_L[xt]=o.getUint32(tt+=4);for(let xt=16;xt<80;xt++){const vt=SHA512_W_H[xt-15]|0,Et=SHA512_W_L[xt-15]|0,Ct=u64.rotrSH(vt,Et,1)^u64.rotrSH(vt,Et,8)^u64.shrSH(vt,Et,7),St=u64.rotrSL(vt,Et,1)^u64.rotrSL(vt,Et,8)^u64.shrSL(vt,Et,7),At=SHA512_W_H[xt-2]|0,kt=SHA512_W_L[xt-2]|0,It=u64.rotrSH(At,kt,19)^u64.rotrBH(At,kt,61)^u64.shrSH(At,kt,6),Ot=u64.rotrSL(At,kt,19)^u64.rotrBL(At,kt,61)^u64.shrSL(At,kt,6),Nt=u64.add4L(St,Ot,SHA512_W_L[xt-7],SHA512_W_L[xt-16]),Yt=u64.add4H(Nt,Ct,It,SHA512_W_H[xt-7],SHA512_W_H[xt-16]);SHA512_W_H[xt]=Yt|0,SHA512_W_L[xt]=Nt|0}let{Ah:rt,Al:nt,Bh:ot,Bl:it,Ch:st,Cl:at,Dh:ct,Dl:lt,Eh:dt,El:ht,Fh:mt,Fl:ft,Gh:pt,Gl:gt,Hh:yt,Hl:bt}=this;for(let xt=0;xt<80;xt++){const vt=u64.rotrSH(dt,ht,14)^u64.rotrSH(dt,ht,18)^u64.rotrBH(dt,ht,41),Et=u64.rotrSL(dt,ht,14)^u64.rotrSL(dt,ht,18)^u64.rotrBL(dt,ht,41),Ct=dt&mt^~dt&pt,St=ht&ft^~ht>,At=u64.add5L(bt,Et,St,SHA512_Kl[xt],SHA512_W_L[xt]),kt=u64.add5H(At,yt,vt,Ct,SHA512_Kh[xt],SHA512_W_H[xt]),It=At|0,Ot=u64.rotrSH(rt,nt,28)^u64.rotrBH(rt,nt,34)^u64.rotrBH(rt,nt,39),Nt=u64.rotrSL(rt,nt,28)^u64.rotrBL(rt,nt,34)^u64.rotrBL(rt,nt,39),Yt=rt&ot^rt&st^ot&st,Ft=nt&it^nt&at^it&at;yt=pt|0,bt=gt|0,pt=mt|0,gt=ft|0,mt=dt|0,ft=ht|0,{h:dt,l:ht}=u64.add(ct|0,lt|0,kt|0,It|0),ct=st|0,lt=at|0,st=ot|0,at=it|0,ot=rt|0,it=nt|0;const Ht=u64.add3L(It,Nt,Ft);rt=u64.add3H(Ht,kt,Ot,Yt),nt=Ht|0}({h:rt,l:nt}=u64.add(this.Ah|0,this.Al|0,rt|0,nt|0)),{h:ot,l:it}=u64.add(this.Bh|0,this.Bl|0,ot|0,it|0),{h:st,l:at}=u64.add(this.Ch|0,this.Cl|0,st|0,at|0),{h:ct,l:lt}=u64.add(this.Dh|0,this.Dl|0,ct|0,lt|0),{h:dt,l:ht}=u64.add(this.Eh|0,this.El|0,dt|0,ht|0),{h:mt,l:ft}=u64.add(this.Fh|0,this.Fl|0,mt|0,ft|0),{h:pt,l:gt}=u64.add(this.Gh|0,this.Gl|0,pt|0,gt|0),{h:yt,l:bt}=u64.add(this.Hh|0,this.Hl|0,yt|0,bt|0),this.set(rt,nt,ot,it,st,at,ct,lt,dt,ht,mt,ft,pt,gt,yt,bt)}roundClean(){SHA512_W_H.fill(0),SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha512=wrapConstructor(()=>new SHA512);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$3=BigInt(1),_2n$2=BigInt(2),_8n$2=BigInt(8),VERIFY_DEFAULT={zip215:!0};function validateOpts$1(et){const o=validateBasic(et);return validateObject(et,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...o})}function twistedEdwards(et){const o=validateOpts$1(et),{Fp:tt,n:rt,prehash:nt,hash:ot,randomBytes:it,nByteLength:st,h:at}=o,ct=_2n$2<{try{return{isValid:!0,value:tt.sqrt(Qt*tt.inv(Vt))}}catch{return{isValid:!1,value:_0n$2}}}),mt=o.adjustScalarBytes||(Qt=>Qt),ft=o.domain||((Qt,Vt,Bt)=>{if(abool("phflag",Bt),Vt.length||Bt)throw new Error("Contexts/pre-hash are not supported");return Qt});function pt(Qt,Vt){aInRange("coordinate "+Qt,Vt,_0n$2,ct)}function gt(Qt){if(!(Qt instanceof xt))throw new Error("ExtendedPoint expected")}const yt=memoized((Qt,Vt)=>{const{ex:Bt,ey:Wt,ez:jt}=Qt,Xt=Qt.is0();Vt==null&&(Vt=Xt?_8n$2:tt.inv(jt));const Kt=lt(Bt*Vt),Pt=lt(Wt*Vt),Gt=lt(jt*Vt);if(Xt)return{x:_0n$2,y:_1n$3};if(Gt!==_1n$3)throw new Error("invZ was invalid");return{x:Kt,y:Pt}}),bt=memoized(Qt=>{const{a:Vt,d:Bt}=o;if(Qt.is0())throw new Error("bad point: ZERO");const{ex:Wt,ey:jt,ez:Xt,et:Kt}=Qt,Pt=lt(Wt*Wt),Gt=lt(jt*jt),tr=lt(Xt*Xt),zt=lt(tr*tr),lr=lt(Pt*Vt),rr=lt(tr*lt(lr+Gt)),Jt=lt(zt+lt(Bt*lt(Pt*Gt)));if(rr!==Jt)throw new Error("bad point: equation left != right (1)");const Rt=lt(Wt*jt),Mt=lt(Xt*Kt);if(Rt!==Mt)throw new Error("bad point: equation left != right (2)");return!0});class xt{constructor(Vt,Bt,Wt,jt){this.ex=Vt,this.ey=Bt,this.ez=Wt,this.et=jt,pt("x",Vt),pt("y",Bt),pt("z",Wt),pt("t",jt),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(Vt){if(Vt instanceof xt)throw new Error("extended point not allowed");const{x:Bt,y:Wt}=Vt||{};return pt("x",Bt),pt("y",Wt),new xt(Bt,Wt,_1n$3,lt(Bt*Wt))}static normalizeZ(Vt){const Bt=tt.invertBatch(Vt.map(Wt=>Wt.ez));return Vt.map((Wt,jt)=>Wt.toAffine(Bt[jt])).map(xt.fromAffine)}static msm(Vt,Bt){return pippenger(xt,dt,Vt,Bt)}_setWindowSize(Vt){Ct.setWindowSize(this,Vt)}assertValidity(){bt(this)}equals(Vt){gt(Vt);const{ex:Bt,ey:Wt,ez:jt}=this,{ex:Xt,ey:Kt,ez:Pt}=Vt,Gt=lt(Bt*Pt),tr=lt(Xt*jt),zt=lt(Wt*Pt),lr=lt(Kt*jt);return Gt===tr&&zt===lr}is0(){return this.equals(xt.ZERO)}negate(){return new xt(lt(-this.ex),this.ey,this.ez,lt(-this.et))}double(){const{a:Vt}=o,{ex:Bt,ey:Wt,ez:jt}=this,Xt=lt(Bt*Bt),Kt=lt(Wt*Wt),Pt=lt(_2n$2*lt(jt*jt)),Gt=lt(Vt*Xt),tr=Bt+Wt,zt=lt(lt(tr*tr)-Xt-Kt),lr=Gt+Kt,rr=lr-Pt,Jt=Gt-Kt,Rt=lt(zt*rr),Mt=lt(lr*Jt),Ut=lt(zt*Jt),Zt=lt(rr*lr);return new xt(Rt,Mt,Zt,Ut)}add(Vt){gt(Vt);const{a:Bt,d:Wt}=o,{ex:jt,ey:Xt,ez:Kt,et:Pt}=this,{ex:Gt,ey:tr,ez:zt,et:lr}=Vt;if(Bt===BigInt(-1)){const gr=lt((Xt-jt)*(tr+Gt)),Pr=lt((Xt+jt)*(tr-Gt)),_r=lt(Pr-gr);if(_r===_0n$2)return this.double();const Rr=lt(Kt*_2n$2*lr),mr=lt(Pt*_2n$2*zt),wr=mr+Rr,ir=Pr+gr,Tt=mr-Rr,$t=lt(wr*_r),_t=lt(ir*Tt),Dt=lt(wr*Tt),qt=lt(_r*ir);return new xt($t,_t,qt,Dt)}const rr=lt(jt*Gt),Jt=lt(Xt*tr),Rt=lt(Pt*Wt*lr),Mt=lt(Kt*zt),Ut=lt((jt+Xt)*(Gt+tr)-rr-Jt),Zt=Mt-Rt,nr=Mt+Rt,ar=lt(Jt-Bt*rr),dr=lt(Ut*Zt),cr=lt(nr*ar),yr=lt(Ut*ar),pr=lt(Zt*nr);return new xt(dr,cr,pr,yr)}subtract(Vt){return this.add(Vt.negate())}wNAF(Vt){return Ct.wNAFCached(this,Vt,xt.normalizeZ)}multiply(Vt){const Bt=Vt;aInRange("scalar",Bt,_1n$3,rt);const{p:Wt,f:jt}=this.wNAF(Bt);return xt.normalizeZ([Wt,jt])[0]}multiplyUnsafe(Vt){const Bt=Vt;return aInRange("scalar",Bt,_0n$2,rt),Bt===_0n$2?Et:this.equals(Et)||Bt===_1n$3?this:this.equals(vt)?this.wNAF(Bt).p:Ct.unsafeLadder(this,Bt)}isSmallOrder(){return this.multiplyUnsafe(at).is0()}isTorsionFree(){return Ct.unsafeLadder(this,rt).is0()}toAffine(Vt){return yt(this,Vt)}clearCofactor(){const{h:Vt}=o;return Vt===_1n$3?this:this.multiplyUnsafe(Vt)}static fromHex(Vt,Bt=!1){const{d:Wt,a:jt}=o,Xt=tt.BYTES;Vt=ensureBytes$1("pointHex",Vt,Xt),abool("zip215",Bt);const Kt=Vt.slice(),Pt=Vt[Xt-1];Kt[Xt-1]=Pt&-129;const Gt=bytesToNumberLE(Kt),tr=Bt?ct:tt.ORDER;aInRange("pointHex.y",Gt,_0n$2,tr);const zt=lt(Gt*Gt),lr=lt(zt-_1n$3),rr=lt(Wt*zt-jt);let{isValid:Jt,value:Rt}=ht(lr,rr);if(!Jt)throw new Error("Point.fromHex: invalid y coordinate");const Mt=(Rt&_1n$3)===_1n$3,Ut=(Pt&128)!==0;if(!Bt&&Rt===_0n$2&&Ut)throw new Error("Point.fromHex: x=0 and x_0=1");return Ut!==Mt&&(Rt=lt(-Rt)),xt.fromAffine({x:Rt,y:Gt})}static fromPrivateKey(Vt){return kt(Vt).point}toRawBytes(){const{x:Vt,y:Bt}=this.toAffine(),Wt=numberToBytesLE(Bt,tt.BYTES);return Wt[Wt.length-1]|=Vt&_1n$3?128:0,Wt}toHex(){return bytesToHex$2(this.toRawBytes())}}xt.BASE=new xt(o.Gx,o.Gy,_1n$3,lt(o.Gx*o.Gy)),xt.ZERO=new xt(_0n$2,_1n$3,_1n$3,_0n$2);const{BASE:vt,ZERO:Et}=xt,Ct=wNAF(xt,st*8);function St(Qt){return mod$1(Qt,rt)}function At(Qt){return St(bytesToNumberLE(Qt))}function kt(Qt){const Vt=st;Qt=ensureBytes$1("private key",Qt,Vt);const Bt=ensureBytes$1("hashed private key",ot(Qt),2*Vt),Wt=mt(Bt.slice(0,Vt)),jt=Bt.slice(Vt,2*Vt),Xt=At(Wt),Kt=vt.multiply(Xt),Pt=Kt.toRawBytes();return{head:Wt,prefix:jt,scalar:Xt,point:Kt,pointBytes:Pt}}function It(Qt){return kt(Qt).pointBytes}function Ot(Qt=new Uint8Array,...Vt){const Bt=concatBytes$1(...Vt);return At(ot(ft(Bt,ensureBytes$1("context",Qt),!!nt)))}function Nt(Qt,Vt,Bt={}){Qt=ensureBytes$1("message",Qt),nt&&(Qt=nt(Qt));const{prefix:Wt,scalar:jt,pointBytes:Xt}=kt(Vt),Kt=Ot(Bt.context,Wt,Qt),Pt=vt.multiply(Kt).toRawBytes(),Gt=Ot(Bt.context,Pt,Xt,Qt),tr=St(Kt+Gt*jt);aInRange("signature.s",tr,_0n$2,rt);const zt=concatBytes$1(Pt,numberToBytesLE(tr,tt.BYTES));return ensureBytes$1("result",zt,st*2)}const Yt=VERIFY_DEFAULT;function Ft(Qt,Vt,Bt,Wt=Yt){const{context:jt,zip215:Xt}=Wt,Kt=tt.BYTES;Qt=ensureBytes$1("signature",Qt,2*Kt),Vt=ensureBytes$1("message",Vt),Xt!==void 0&&abool("zip215",Xt),nt&&(Vt=nt(Vt));const Pt=bytesToNumberLE(Qt.slice(Kt,2*Kt));let Gt,tr,zt;try{Gt=xt.fromHex(Bt,Xt),tr=xt.fromHex(Qt.slice(0,Kt),Xt),zt=vt.multiplyUnsafe(Pt)}catch{return!1}if(!Xt&&Gt.isSmallOrder())return!1;const lr=Ot(jt,tr.toRawBytes(),Gt.toRawBytes(),Vt);return tr.add(Gt.multiplyUnsafe(lr)).subtract(zt).clearCofactor().equals(xt.ZERO)}return vt._setWindowSize(8),{CURVE:o,getPublicKey:It,sign:Nt,verify:Ft,ExtendedPoint:xt,utils:{getExtendedPublicKey:kt,randomPrivateKey:()=>it(tt.BYTES),precompute(Qt=8,Vt=xt.BASE){return Vt._setWindowSize(Qt),Vt.multiply(BigInt(3)),Vt}}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$1=BigInt(0),_1n$2=BigInt(1);function validateOpts(et){return validateObject(et,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...et})}function montgomery(et){const o=validateOpts(et),{P:tt}=o,rt=bt=>mod$1(bt,tt),nt=o.montgomeryBits,ot=Math.ceil(nt/8),it=o.nByteLength,st=o.adjustScalarBytes||(bt=>bt),at=o.powPminus2||(bt=>pow(bt,tt-BigInt(2),tt));function ct(bt,xt,vt){const Et=rt(bt*(xt-vt));return xt=rt(xt-Et),vt=rt(vt+Et),[xt,vt]}const lt=(o.a-BigInt(2))/BigInt(4);function dt(bt,xt){aInRange("u",bt,_0n$1,tt),aInRange("scalar",xt,_0n$1,tt);const vt=xt,Et=bt;let Ct=_1n$2,St=_0n$1,At=bt,kt=_1n$2,It=_0n$1,Ot;for(let Yt=BigInt(nt-1);Yt>=_0n$1;Yt--){const Ft=vt>>Yt&_1n$2;It^=Ft,Ot=ct(It,Ct,At),Ct=Ot[0],At=Ot[1],Ot=ct(It,St,kt),St=Ot[0],kt=Ot[1],It=Ft;const Ht=Ct+St,Qt=rt(Ht*Ht),Vt=Ct-St,Bt=rt(Vt*Vt),Wt=Qt-Bt,jt=At+kt,Xt=At-kt,Kt=rt(Xt*Ht),Pt=rt(jt*Vt),Gt=Kt+Pt,tr=Kt-Pt;At=rt(Gt*Gt),kt=rt(Et*rt(tr*tr)),Ct=rt(Qt*Bt),St=rt(Wt*(Qt+rt(lt*Wt)))}Ot=ct(It,Ct,At),Ct=Ot[0],At=Ot[1],Ot=ct(It,St,kt),St=Ot[0],kt=Ot[1];const Nt=at(St);return rt(Ct*Nt)}function ht(bt){return numberToBytesLE(rt(bt),ot)}function mt(bt){const xt=ensureBytes$1("u coordinate",bt,ot);return it===32&&(xt[31]&=127),bytesToNumberLE(xt)}function ft(bt){const xt=ensureBytes$1("scalar",bt),vt=xt.length;if(vt!==ot&&vt!==it)throw new Error(`Expected ${ot} or ${it} bytes, got ${vt}`);return bytesToNumberLE(st(xt))}function pt(bt,xt){const vt=mt(xt),Et=ft(bt),Ct=dt(vt,Et);if(Ct===_0n$1)throw new Error("Invalid private or public key received");return ht(Ct)}const gt=ht(o.Gu);function yt(bt){return pt(bt,gt)}return{scalarMult:pt,scalarMultBase:yt,getSharedSecret:(bt,xt)=>pt(bt,xt),getPublicKey:bt=>yt(bt),utils:{randomPrivateKey:()=>o.randomBytes(o.nByteLength)},GuBytes:gt}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ED25519_P=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const _1n$1=BigInt(1),_2n$1=BigInt(2),_3n$1=BigInt(3),_5n=BigInt(5),_8n$1=BigInt(8);function ed25519_pow_2_252_3(et){const o=BigInt(10),tt=BigInt(20),rt=BigInt(40),nt=BigInt(80),ot=ED25519_P,st=et*et%ot*et%ot,at=pow2$1(st,_2n$1,ot)*st%ot,ct=pow2$1(at,_1n$1,ot)*et%ot,lt=pow2$1(ct,_5n,ot)*ct%ot,dt=pow2$1(lt,o,ot)*lt%ot,ht=pow2$1(dt,tt,ot)*dt%ot,mt=pow2$1(ht,rt,ot)*ht%ot,ft=pow2$1(mt,nt,ot)*mt%ot,pt=pow2$1(ft,nt,ot)*mt%ot,gt=pow2$1(pt,o,ot)*lt%ot;return{pow_p_5_8:pow2$1(gt,_2n$1,ot)*et%ot,b2:st}}function adjustScalarBytes(et){return et[0]&=248,et[31]&=127,et[31]|=64,et}function uvRatio(et,o){const tt=ED25519_P,rt=mod$1(o*o*o,tt),nt=mod$1(rt*rt*o,tt),ot=ed25519_pow_2_252_3(et*nt).pow_p_5_8;let it=mod$1(et*rt*ot,tt);const st=mod$1(o*it*it,tt),at=it,ct=mod$1(it*ED25519_SQRT_M1,tt),lt=st===et,dt=st===mod$1(-et,tt),ht=st===mod$1(-et*ED25519_SQRT_M1,tt);return lt&&(it=at),(dt||ht)&&(it=ct),isNegativeLE(it,tt)&&(it=mod$1(-it,tt)),{isValid:lt||dt,value:it}}const Fp=Field$1(ED25519_P,void 0,!0),ed25519Defaults={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:_8n$1,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sha512,randomBytes:randomBytes$1,adjustScalarBytes,uvRatio},ed25519=twistedEdwards(ed25519Defaults),x25519=montgomery({P:ED25519_P,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:et=>{const o=ED25519_P,{pow_p_5_8:tt,b2:rt}=ed25519_pow_2_252_3(et);return mod$1(pow2$1(tt,_3n$1,o)*rt,o)},adjustScalarBytes,randomBytes:randomBytes$1}),PUBLIC_KEY_BYTE_LENGTH=32,PRIVATE_KEY_BYTE_LENGTH=64,KEYS_BYTE_LENGTH=32;function generateKey(){const et=ed25519.utils.randomPrivateKey(),o=ed25519.getPublicKey(et);return{privateKey:concatKeys(et,o),publicKey:o}}function hashAndSign(et,o){const tt=et.subarray(0,KEYS_BYTE_LENGTH);return ed25519.sign(o instanceof Uint8Array?o:o.subarray(),tt)}function hashAndVerify$2(et,o,tt){return ed25519.verify(o,tt instanceof Uint8Array?tt:tt.subarray(),et)}function concatKeys(et,o){const tt=new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);for(let rt=0;rtenumeration(__KeyTypeValues)})(KeyType||(KeyType={}));var PublicKey;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.Type!=null&&(rt.uint32(8),KeyType.codec().encode(tt.Type,rt)),tt.Data!=null&&(rt.uint32(18),rt.bytes(tt.Data)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.Type=KeyType.codec().decode(tt);break}case 2:{ot.Data=tt.bytes();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PublicKey||(PublicKey={}));var PrivateKey;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.Type!=null&&(rt.uint32(8),KeyType.codec().encode(tt.Type,rt)),tt.Data!=null&&(rt.uint32(18),rt.bytes(tt.Data)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.Type=KeyType.codec().decode(tt);break}case 2:{ot.Data=tt.bytes();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PrivateKey||(PrivateKey={}));/*! + * MIT License + * + * Copyright (c) 2017-2022 Peculiar Ventures, LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */const ARRAY_BUFFER_NAME="[object ArrayBuffer]";class BufferSourceConverter{static isArrayBuffer(o){return Object.prototype.toString.call(o)===ARRAY_BUFFER_NAME}static toArrayBuffer(o){return this.isArrayBuffer(o)?o:o.byteLength===o.buffer.byteLength||o.byteOffset===0&&o.byteLength===o.buffer.byteLength?o.buffer:this.toUint8Array(o.buffer).slice(o.byteOffset,o.byteOffset+o.byteLength).buffer}static toUint8Array(o){return this.toView(o,Uint8Array)}static toView(o,tt){if(o.constructor===tt)return o;if(this.isArrayBuffer(o))return new tt(o);if(this.isArrayBufferView(o))return new tt(o.buffer,o.byteOffset,o.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(o){return this.isArrayBufferView(o)||this.isArrayBuffer(o)}static isArrayBufferView(o){return ArrayBuffer.isView(o)||o&&this.isArrayBuffer(o.buffer)}static isEqual(o,tt){const rt=BufferSourceConverter.toUint8Array(o),nt=BufferSourceConverter.toUint8Array(tt);if(rt.length!==nt.byteLength)return!1;for(let ot=0;ot=0;rt--)tt+=et[et.length-1-rt]*Math.pow(2,o*rt);return tt}function utilToBase(et,o,tt=-1){const rt=tt;let nt=et,ot=0,it=Math.pow(2,o);for(let st=1;st<8;st++){if(et=0;lt--){const dt=Math.pow(2,lt*o);ct[ot-lt-1]=Math.floor(nt/dt),nt-=ct[ot-lt-1]*dt}return at}it*=Math.pow(2,o)}return new ArrayBuffer(0)}function utilConcatView(...et){let o=0,tt=0;for(const ot of et)o+=ot.length;const rt=new ArrayBuffer(o),nt=new Uint8Array(rt);for(const ot of et)nt.set(ot,tt),tt+=ot.length;return nt}function utilDecodeTC(){const et=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const st=et[0]===255&&et[1]&128,at=et[0]===0&&(et[1]&128)===0;(st||at)&&this.warnings.push("Needlessly long format")}const o=new ArrayBuffer(this.valueHex.byteLength),tt=new Uint8Array(o);for(let st=0;st"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function concat$2(et){let o=0,tt=0;for(let nt=0;nt=ot.length)return this.error="End of input reached before message was fully decoded",-1;if(at===lt){lt+=255;const ht=new Uint8Array(lt);for(let mt=0;mt8)return this.error="Too big integer",-1;if(it+1>ot.length)return this.error="End of input reached before message was fully decoded",-1;const st=tt+1,at=nt.subarray(st,st+it);return at[it-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=utilFromBase(at,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=it+1,tt+this.blockLength}toBER(o=!1){let tt,rt;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return tt=new ArrayBuffer(1),o===!1&&(rt=new Uint8Array(tt),rt[0]=128),tt;if(this.longFormUsed){const nt=utilToBase(this.length,8);if(nt.byteLength>127)return this.error="Too big length",EMPTY_BUFFER$1;if(tt=new ArrayBuffer(nt.byteLength+1),o)return tt;const ot=new Uint8Array(nt);rt=new Uint8Array(tt),rt[0]=nt.byteLength|128;for(let it=0;it=37&&nt.idBlock.isHexOnly===!1)return nt.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:nt};switch(nt.idBlock.tagNumber){case 0:if(nt.idBlock.isConstructed&&nt.lenBlock.length>0)return nt.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:nt};at=typeStore.EndOfContent;break;case 1:at=typeStore.Boolean;break;case 2:at=typeStore.Integer;break;case 3:at=typeStore.BitString;break;case 4:at=typeStore.OctetString;break;case 5:at=typeStore.Null;break;case 6:at=typeStore.ObjectIdentifier;break;case 10:at=typeStore.Enumerated;break;case 12:at=typeStore.Utf8String;break;case 13:at=typeStore.RelativeObjectIdentifier;break;case 14:at=typeStore.TIME;break;case 15:return nt.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:nt};case 16:at=typeStore.Sequence;break;case 17:at=typeStore.Set;break;case 18:at=typeStore.NumericString;break;case 19:at=typeStore.PrintableString;break;case 20:at=typeStore.TeletexString;break;case 21:at=typeStore.VideotexString;break;case 22:at=typeStore.IA5String;break;case 23:at=typeStore.UTCTime;break;case 24:at=typeStore.GeneralizedTime;break;case 25:at=typeStore.GraphicString;break;case 26:at=typeStore.VisibleString;break;case 27:at=typeStore.GeneralString;break;case 28:at=typeStore.UniversalString;break;case 29:at=typeStore.CharacterString;break;case 30:at=typeStore.BmpString;break;case 31:at=typeStore.DATE;break;case 32:at=typeStore.TimeOfDay;break;case 33:at=typeStore.DateTime;break;case 34:at=typeStore.Duration;break;default:{const ct=nt.idBlock.isConstructed?new typeStore.Constructed:new typeStore.Primitive;ct.idBlock=nt.idBlock,ct.lenBlock=nt.lenBlock,ct.warnings=nt.warnings,nt=ct}}break;case 2:case 3:case 4:default:at=nt.idBlock.isConstructed?typeStore.Constructed:typeStore.Primitive}return nt=localChangeType(nt,at),st=nt.fromBER(et,o,nt.lenBlock.isIndefiniteForm?tt:nt.lenBlock.length),nt.valueBeforeDecodeView=et.subarray(rt,rt+nt.blockLength),{offset:st,result:nt}}function fromBER(et){if(!et.byteLength){const o=new BaseBlock({},ValueBlock);return o.error="Input buffer has zero length",{offset:-1,result:o}}return localFromBER(BufferSourceConverter.toUint8Array(et).slice(),0,et.byteLength)}function checkLen(et,o){return et?1:o}class LocalConstructedValueBlock extends ValueBlock{constructor({value:o=[],isIndefiniteForm:tt=!1,...rt}={}){super(rt),this.value=o,this.isIndefiniteForm=tt}fromBER(o,tt,rt){const nt=BufferSourceConverter.toUint8Array(o);if(!checkBufferParams(this,nt,tt,rt))return-1;if(this.valueBeforeDecodeView=nt.subarray(tt,tt+rt),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),tt;let ot=tt;for(;checkLen(this.isIndefiniteForm,rt)>0;){const it=localFromBER(nt,ot,rt);if(it.offset===-1)return this.error=it.result.error,this.warnings.concat(it.result.warnings),-1;if(ot=it.offset,this.blockLength+=it.result.blockLength,rt-=it.result.blockLength,this.value.push(it.result),this.isIndefiniteForm&&it.result.constructor.NAME===END_OF_CONTENT_NAME)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===END_OF_CONTENT_NAME?this.value.pop():this.warnings.push("No EndOfContent block encoded")),ot}toBER(o,tt){const rt=tt||new ViewWriter;for(let nt=0;nt` ${nt}`).join(` +`));const tt=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return o.length?`${tt} : +${o.join(` +`)}`:`${tt} :`}}_a$v=Constructed;typeStore.Constructed=_a$v;Constructed.NAME="CONSTRUCTED";class LocalEndOfContentValueBlock extends ValueBlock{fromBER(o,tt,rt){return tt}toBER(o){return EMPTY_BUFFER$1}}LocalEndOfContentValueBlock.override="EndOfContentValueBlock";var _a$u;class EndOfContent extends BaseBlock{constructor(o={}){super(o,LocalEndOfContentValueBlock),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}_a$u=EndOfContent;typeStore.EndOfContent=_a$u;EndOfContent.NAME=END_OF_CONTENT_NAME;var _a$t;class Null extends BaseBlock{constructor(o={}){super(o,ValueBlock),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(o,tt,rt){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=rt,tt+rt>o.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):tt+rt}toBER(o,tt){const rt=new ArrayBuffer(2);if(!o){const nt=new Uint8Array(rt);nt[0]=5,nt[1]=0}return tt&&tt.write(rt),rt}onAsciiEncoding(){return`${this.constructor.NAME}`}}_a$t=Null;typeStore.Null=_a$t;Null.NAME="NULL";class LocalBooleanValueBlock extends HexBlock(ValueBlock){constructor({value:o,...tt}={}){super(tt),tt.valueHex?this.valueHexView=BufferSourceConverter.toUint8Array(tt.valueHex):this.valueHexView=new Uint8Array(1),o&&(this.value=o)}get value(){for(const o of this.valueHexView)if(o>0)return!0;return!1}set value(o){this.valueHexView[0]=o?255:0}fromBER(o,tt,rt){const nt=BufferSourceConverter.toUint8Array(o);return checkBufferParams(this,nt,tt,rt)?(this.valueHexView=nt.subarray(tt,tt+rt),rt>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,utilDecodeTC.call(this),this.blockLength=rt,tt+rt):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}LocalBooleanValueBlock.NAME="BooleanValueBlock";var _a$s;let Boolean$1=class extends BaseBlock{constructor(o={}){super(o,LocalBooleanValueBlock),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(o){this.valueBlock.value=o}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};_a$s=Boolean$1;typeStore.Boolean=_a$s;Boolean$1.NAME="BOOLEAN";class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock){constructor({isConstructed:o=!1,...tt}={}){super(tt),this.isConstructed=o}fromBER(o,tt,rt){let nt=0;if(this.isConstructed){if(this.isHexOnly=!1,nt=LocalConstructedValueBlock.prototype.fromBER.call(this,o,tt,rt),nt===-1)return nt;for(let ot=0;ot0&&ct.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=ct.unusedBits}return nt}const ot=BufferSourceConverter.toUint8Array(o);if(!checkBufferParams(this,ot,tt,rt))return-1;const it=ot.subarray(tt,tt+rt);if(this.unusedBits=it[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const st=it.subarray(1);try{if(st.byteLength){const at=localFromBER(st,0,st.byteLength);at.offset!==-1&&at.offset===rt-1&&(this.value=[at.result])}}catch{}}return this.valueHexView=it.subarray(1),this.blockLength=it.length,tt+rt}toBER(o,tt){if(this.isConstructed)return LocalConstructedValueBlock.prototype.toBER.call(this,o,tt);if(o)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return EMPTY_BUFFER$1;const rt=new Uint8Array(this.valueHexView.length+1);return rt[0]=this.unusedBits,rt.set(this.valueHexView,1),rt.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}LocalBitStringValueBlock.NAME="BitStringValueBlock";var _a$q;class BitString extends BaseBlock{constructor({idBlock:o={},lenBlock:tt={},...rt}={}){var nt,ot;(nt=rt.isConstructed)!==null&&nt!==void 0||(rt.isConstructed=!!(!((ot=rt.value)===null||ot===void 0)&&ot.length)),super({idBlock:{isConstructed:rt.isConstructed,...o},lenBlock:{...tt,isIndefiniteForm:!!rt.isIndefiniteForm},...rt},LocalBitStringValueBlock),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(o,tt,rt){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(o,tt,rt)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Constructed.prototype.onAsciiEncoding.call(this);{const o=[],tt=this.valueBlock.valueHexView;for(const nt of tt)o.push(nt.toString(2).padStart(8,"0"));const rt=o.join("");return`${this.constructor.NAME} : ${rt.substring(0,rt.length-this.valueBlock.unusedBits)}`}}}_a$q=BitString;typeStore.BitString=_a$q;BitString.NAME=BIT_STRING_NAME;var _a$p;function viewAdd(et,o){const tt=new Uint8Array([0]),rt=new Uint8Array(et),nt=new Uint8Array(o);let ot=rt.slice(0);const it=ot.length-1,st=nt.slice(0),at=st.length-1;let ct=0;const lt=at=0;ht--,dt++){switch(!0){case dt=ot.length:ot=utilConcatView(new Uint8Array([ct%10]),ot);break;default:ot[it-dt]=ct%10}}return tt[0]>0&&(ot=utilConcatView(tt,ot)),ot}function power2(et){if(et>=powers2.length)for(let o=powers2.length;o<=et;o++){const tt=new Uint8Array([0]);let rt=powers2[o-1].slice(0);for(let nt=rt.length-1;nt>=0;nt--){const ot=new Uint8Array([(rt[nt]<<1)+tt[0]]);tt[0]=ot[0]/10,rt[nt]=ot[0]%10}tt[0]>0&&(rt=utilConcatView(tt,rt)),powers2.push(rt)}return powers2[et]}function viewSub(et,o){let tt=0;const rt=new Uint8Array(et),nt=new Uint8Array(o),ot=rt.slice(0),it=ot.length-1,st=nt.slice(0),at=st.length-1;let ct,lt=0;for(let dt=at;dt>=0;dt--,lt++)switch(ct=ot[it-lt]-st[at-lt]-tt,!0){case ct<0:tt=1,ot[it-lt]=ct+10;break;default:tt=0,ot[it-lt]=ct}if(tt>0)for(let dt=it-at+1;dt>=0;dt--,lt++)if(ct=ot[it-lt]-tt,ct<0)tt=1,ot[it-lt]=ct+10;else{tt=0,ot[it-lt]=ct;break}return ot.slice()}class LocalIntegerValueBlock extends HexBlock(ValueBlock){constructor({value:o,...tt}={}){super(tt),this._valueDec=0,tt.valueHex&&this.setValueHex(),o!==void 0&&(this.valueDec=o)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=utilDecodeTC.call(this)))}set valueDec(o){this._valueDec=o,this.isHexOnly=!1,this.valueHexView=new Uint8Array(utilEncodeTC(o))}get valueDec(){return this._valueDec}fromDER(o,tt,rt,nt=0){const ot=this.fromBER(o,tt,rt);if(ot===-1)return ot;const it=this.valueHexView;return it[0]===0&&it[1]&128?this.valueHexView=it.subarray(1):nt!==0&&it.length1&&(nt=it.length+1),this.valueHexView=it.subarray(nt-it.length)),ot}toDER(o=!1){const tt=this.valueHexView;switch(!0){case(tt[0]&128)!==0:{const rt=new Uint8Array(this.valueHexView.length+1);rt[0]=0,rt.set(tt,1),this.valueHexView=rt}break;case(tt[0]===0&&(tt[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(o)}fromBER(o,tt,rt){const nt=super.fromBER(o,tt,rt);return nt===-1||this.setValueHex(),nt}toBER(o){return o?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const o=this.valueHexView.length*8-1;let tt=new Uint8Array(this.valueHexView.length*8/3),rt=0,nt;const ot=this.valueHexView;let it="",st=!1;for(let at=ot.byteLength-1;at>=0;at--){nt=ot[at];for(let ct=0;ct<8;ct++){if((nt&1)===1)switch(rt){case o:tt=viewSub(power2(rt),tt),it="-";break;default:tt=viewAdd(tt,power2(rt))}rt++,nt>>=1}}for(let at=0;at0;){const ot=new LocalSidValueBlock;if(nt=ot.fromBER(o,nt,rt),nt===-1)return this.blockLength=0,this.error=ot.error,nt;this.value.length===0&&(ot.isFirstSid=!0),this.blockLength+=ot.blockLength,rt-=ot.blockLength,this.value.push(ot)}return nt}toBER(o){const tt=[];for(let rt=0;rtNumber.MAX_SAFE_INTEGER){assertBigInt();const st=BigInt(nt);it.valueBigInt=st}else if(it.valueDec=parseInt(nt,10),isNaN(it.valueDec))return;this.value.length||(it.isFirstSid=!0,ot=!0),this.value.push(it)}while(rt!==-1)}toString(){let o="",tt=!1;for(let rt=0;rt0;){const ot=new LocalRelativeSidValueBlock;if(nt=ot.fromBER(o,nt,rt),nt===-1)return this.blockLength=0,this.error=ot.error,nt;this.blockLength+=ot.blockLength,rt-=ot.blockLength,this.value.push(ot)}return nt}toBER(o,tt){const rt=[];for(let nt=0;nt4)continue;const st=4-it.length;for(let at=it.length-1;at>=0;at--)rt[nt*4+at+st]=it[at]}this.valueBlock.value=o}}LocalUniversalStringValueBlock.NAME="UniversalStringValueBlock";var _a$g;class UniversalString extends LocalUniversalStringValueBlock{constructor({...o}={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}_a$g=UniversalString;typeStore.UniversalString=_a$g;UniversalString.NAME="UniversalString";var _a$f;class NumericString extends LocalSimpleStringBlock{constructor(o={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}_a$f=NumericString;typeStore.NumericString=_a$f;NumericString.NAME="NumericString";var _a$e;class PrintableString extends LocalSimpleStringBlock{constructor(o={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}_a$e=PrintableString;typeStore.PrintableString=_a$e;PrintableString.NAME="PrintableString";var _a$d;class TeletexString extends LocalSimpleStringBlock{constructor(o={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}_a$d=TeletexString;typeStore.TeletexString=_a$d;TeletexString.NAME="TeletexString";var _a$c;class VideotexString extends LocalSimpleStringBlock{constructor(o={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}_a$c=VideotexString;typeStore.VideotexString=_a$c;VideotexString.NAME="VideotexString";var _a$b;class IA5String extends LocalSimpleStringBlock{constructor(o={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}_a$b=IA5String;typeStore.IA5String=_a$b;IA5String.NAME="IA5String";var _a$a;class GraphicString extends LocalSimpleStringBlock{constructor(o={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}_a$a=GraphicString;typeStore.GraphicString=_a$a;GraphicString.NAME="GraphicString";var _a$9;class VisibleString extends LocalSimpleStringBlock{constructor(o={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}_a$9=VisibleString;typeStore.VisibleString=_a$9;VisibleString.NAME="VisibleString";var _a$8;class GeneralString extends LocalSimpleStringBlock{constructor(o={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}_a$8=GeneralString;typeStore.GeneralString=_a$8;GeneralString.NAME="GeneralString";var _a$7;class CharacterString extends LocalSimpleStringBlock{constructor(o={}){super(o),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}_a$7=CharacterString;typeStore.CharacterString=_a$7;CharacterString.NAME="CharacterString";var _a$6;class UTCTime extends VisibleString{constructor({value:o,valueDate:tt,...rt}={}){if(super(rt),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,o){this.fromString(o),this.valueBlock.valueHexView=new Uint8Array(o.length);for(let nt=0;nt=50?this.year=1900+nt:this.year=2e3+nt,this.month=parseInt(rt[2],10),this.day=parseInt(rt[3],10),this.hour=parseInt(rt[4],10),this.minute=parseInt(rt[5],10),this.second=parseInt(rt[6],10)}toString(o="iso"){if(o==="iso"){const tt=new Array(7);return tt[0]=padNumber(this.year<2e3?this.year-1900:this.year-2e3,2),tt[1]=padNumber(this.month,2),tt[2]=padNumber(this.day,2),tt[3]=padNumber(this.hour,2),tt[4]=padNumber(this.minute,2),tt[5]=padNumber(this.second,2),tt[6]="Z",tt.join("")}return super.toString(o)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}_a$6=UTCTime;typeStore.UTCTime=_a$6;UTCTime.NAME="UTCTime";var _a$5;class GeneralizedTime extends UTCTime{constructor(o={}){var tt;super(o),(tt=this.millisecond)!==null&&tt!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(o){super.fromDate(o),this.millisecond=o.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(o){let tt=!1,rt="",nt="",ot=0,it,st=0,at=0;if(o[o.length-1]==="Z")rt=o.substring(0,o.length-1),tt=!0;else{const dt=new Number(o[o.length-1]);if(isNaN(dt.valueOf()))throw new Error("Wrong input string for conversion");rt=o}if(tt){if(rt.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(rt.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let dt=1,ht=rt.indexOf("+"),mt="";if(ht===-1&&(ht=rt.indexOf("-"),dt=-1),ht!==-1){if(mt=rt.substring(ht+1),rt=rt.substring(0,ht),mt.length!==2&&mt.length!==4)throw new Error("Wrong input string for conversion");let ft=parseInt(mt.substring(0,2),10);if(isNaN(ft.valueOf()))throw new Error("Wrong input string for conversion");if(st=dt*ft,mt.length===4){if(ft=parseInt(mt.substring(2,4),10),isNaN(ft.valueOf()))throw new Error("Wrong input string for conversion");at=dt*ft}}}let ct=rt.indexOf(".");if(ct===-1&&(ct=rt.indexOf(",")),ct!==-1){const dt=new Number(`0${rt.substring(ct)}`);if(isNaN(dt.valueOf()))throw new Error("Wrong input string for conversion");ot=dt.valueOf(),nt=rt.substring(0,ct)}else nt=rt;switch(!0){case nt.length===8:if(it=/(\d{4})(\d{2})(\d{2})/ig,ct!==-1)throw new Error("Wrong input string for conversion");break;case nt.length===10:if(it=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,ct!==-1){let dt=60*ot;this.minute=Math.floor(dt),dt=60*(dt-this.minute),this.second=Math.floor(dt),dt=1e3*(dt-this.second),this.millisecond=Math.floor(dt)}break;case nt.length===12:if(it=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,ct!==-1){let dt=60*ot;this.second=Math.floor(dt),dt=1e3*(dt-this.second),this.millisecond=Math.floor(dt)}break;case nt.length===14:if(it=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,ct!==-1){const dt=1e3*ot;this.millisecond=Math.floor(dt)}break;default:throw new Error("Wrong input string for conversion")}const lt=it.exec(nt);if(lt===null)throw new Error("Wrong input string for conversion");for(let dt=1;dt(et[tt]=o,et),[]),alphabetCharsToBytes$d=alphabet$d.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$D(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$d[tt],o),"")}function decode$K(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$d[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$q=from$k({prefix:"🚀",name:"base256emoji",encode:encode$D,decode:decode$K}),base256emoji$r=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$q},Symbol.toStringTag,{value:"Module"})),base64$t=rfc4648$g({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$d=rfc4648$g({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$e=rfc4648$g({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$d=rfc4648$g({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$u=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$t,base64pad:base64pad$d,base64url:base64url$e,base64urlpad:base64urlpad$d},Symbol.toStringTag,{value:"Module"})),base8$q=rfc4648$g({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$r=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$q},Symbol.toStringTag,{value:"Module"})),identity$e=from$k({prefix:"\0",name:"identity",encode:et=>toString$r(et),decode:et=>fromString$q(et)}),identityBase$d=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$e},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;function from$j({name:et,code:o,encode:tt}){return new Hasher$1(et,o,tt)}let Hasher$1=class{constructor(o,tt,rt){wt(this,"name");wt(this,"code");wt(this,"encode");this.name=o,this.code=tt,this.encode=rt}digest(o){if(o instanceof Uint8Array){const tt=this.encode(o);return tt instanceof Uint8Array?create$5(this.code,tt):tt.then(rt=>create$5(this.code,rt))}else throw Error("Unknown type, must be binary type")}};function sha$1(et){return async o=>new Uint8Array(await crypto.subtle.digest(et,o))}const sha256$1=from$j({name:"sha2-256",code:18,encode:sha$1("SHA-256")}),bases$d={...identityBase$d,...base2$r,...base8$r,...base10$r,...base16$r,...base32$v,...base36$s,...base58$d,...base64$u,...base256emoji$r};function allocUnsafe$c(et=0){return new Uint8Array(et)}function createCodec$d(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$h=createCodec$d("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$d=createCodec$d("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$c(et.length);for(let tt=0;tt0&&(o=`0${o}`);const tt=o.length/2,rt=new Uint8Array(tt);let nt=0,ot=0;for(;nt0&&(rt=`0${rt}`),o.push(rt)}),BigInt("0x"+o.join(""))}function pkixToRSAPublicKey(et){const o=pkixToJwk(et);if(rsaKeySize(o)>MAX_RSA_KEY_SIZE)throw new InvalidPublicKeyError("Key size is too large");const tt=sha256$3(PublicKey.encode({Type:KeyType.RSA,Data:et})),rt=create$5(SHA2_256_CODE,tt);return new RSAPublicKey(o,rt)}function isPromise$3(et){return et==null?!1:typeof et.then=="function"&&typeof et.catch=="function"&&typeof et.finally=="function"}function hashAndVerify(et,o,tt){const rt=sha256$1.digest(tt instanceof Uint8Array?tt:tt.subarray());if(isPromise$3(rt))return rt.then(({digest:nt})=>secp256k1.verify(o,nt,et)).catch(nt=>{throw new VerificationError(String(nt))});try{return secp256k1.verify(o,rt.digest,et)}catch(nt){throw new VerificationError(String(nt))}}class Secp256k1PublicKey{constructor(o){wt(this,"type","secp256k1");wt(this,"raw");wt(this,"_key");this._key=validateSecp256k1PublicKey(o),this.raw=compressSecp256k1PublicKey(this._key)}toMultihash(){return identity$f.digest(publicKeyToProtobuf(this))}toCID(){return CID$2.createV1(114,this.toMultihash())}toString(){return base58btc$h.encode(this.toMultihash().bytes).substring(1)}equals(o){return o==null||!(o.raw instanceof Uint8Array)?!1:equals$9(this.raw,o.raw)}verify(o,tt){return hashAndVerify(this._key,tt,o)}}function unmarshalSecp256k1PublicKey(et){return new Secp256k1PublicKey(et)}function compressSecp256k1PublicKey(et){return secp256k1.ProjectivePoint.fromHex(et).toRawBytes(!0)}function validateSecp256k1PublicKey(et){try{return secp256k1.ProjectivePoint.fromHex(et),et}catch(o){throw new InvalidPublicKeyError(String(o))}}async function generateKeyPair(et,o){return generateEd25519KeyPair()}function publicKeyFromProtobuf(et){const{Type:o,Data:tt}=PublicKey.decode(et),rt=tt??new Uint8Array;switch(o){case KeyType.RSA:return pkixToRSAPublicKey(rt);case KeyType.Ed25519:return unmarshalEd25519PublicKey(rt);case KeyType.secp256k1:return unmarshalSecp256k1PublicKey(rt);default:throw new UnsupportedKeyTypeError$1}}function publicKeyFromRaw(et){return et.byteLength===32?unmarshalEd25519PublicKey(et):et.byteLength===33?unmarshalSecp256k1PublicKey(et):pkixToRSAPublicKey(et)}function publicKeyFromMultihash(et){const{Type:o,Data:tt}=PublicKey.decode(et.digest),rt=tt??new Uint8Array;switch(o){case KeyType.Ed25519:return unmarshalEd25519PublicKey(rt);case KeyType.secp256k1:return unmarshalSecp256k1PublicKey(rt);default:throw new UnsupportedKeyTypeError$1}}function publicKeyToProtobuf(et){return PublicKey.encode({Type:KeyType[et.type],Data:et.raw})}const peerIdSymbol$2=Symbol.for("@libp2p/peer-id");var ps;let InvalidParametersError$2=(ps=class extends Error{constructor(o="Invalid parameters"){super(o),this.name="InvalidParametersError"}},wt(ps,"name","InvalidParametersError"),ps);class InvalidCIDError extends Error{constructor(o="Invalid CID"){super(o),this.name="InvalidCIDError"}}wt(InvalidCIDError,"name","InvalidCIDError");class InvalidMultihashError extends Error{constructor(o="Invalid Multihash"){super(o),this.name="InvalidMultihashError"}}wt(InvalidMultihashError,"name","InvalidMultihashError");class UnsupportedKeyTypeError extends Error{constructor(o="Unsupported key type"){super(o),this.name="UnsupportedKeyTypeError"}}wt(UnsupportedKeyTypeError,"name","UnsupportedKeyTypeError");function equals$8(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;tt=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$h=base$h,_brrp__multiformats_scope_baseX$g=src$h;let Encoder$h=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$h=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$i(this,o)}},ComposedDecoder$g=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$i(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$i(et,o){return new ComposedDecoder$g({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$g=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$h(o,tt,rt),this.decoder=new Decoder$h(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$i({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$g(et,o,tt,rt)}function baseX$g({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$g(tt,et);return from$i({prefix:o,name:et,encode:rt,decode:ot=>coerce$h(nt(ot))})}function decode$J(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$C(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<=INT$3;)o[tt++]=et&255|MSB$5,et/=128;for(;et&MSBALL$3;)o[tt++]=et&255|MSB$5,et>>>=7;return o[tt]=et|0,encode$B.bytes=tt-rt+1,o}var decode$I=read$4,MSB$1$3=128,REST$1$3=127;function read$4(et,rt){var tt=0,rt=rt||0,nt=0,ot=rt,it,st=et.length;do{if(ot>=st)throw read$4.bytes=0,new RangeError("Could not decode varint");it=et[ot++],tt+=nt<28?(it&REST$1$3)<=MSB$1$3);return read$4.bytes=ot-rt,tt}var N1$3=Math.pow(2,7),N2$3=Math.pow(2,14),N3$3=Math.pow(2,21),N4$3=Math.pow(2,28),N5$3=Math.pow(2,35),N6$3=Math.pow(2,42),N7$3=Math.pow(2,49),N8$3=Math.pow(2,56),N9$3=Math.pow(2,63),length$3=function(et){return et{const[dt,ht]=decode$H(o.subarray(tt));return tt+=ht,dt};let nt=rt(),ot=DAG_PB_CODE$1;if(nt===18?(nt=0,tt=0):ot=rt(),nt!==0&&nt!==1)throw new RangeError(`Invalid CID version ${nt}`);const it=tt,st=rt(),at=rt(),ct=tt+at,lt=ct-it;return{version:nt,codec:ot,multihashCode:st,digestSize:at,multihashSize:lt,size:ct}}static parse(o,tt){const[rt,nt]=parseCIDtoBytes$1(o,tt),ot=Dr.decode(nt);if(ot.version===0&&o[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$1(ot).set(rt,o),ot}};function parseCIDtoBytes$1(et,o){switch(et[0]){case"Q":{const tt=o??base58btc$g;return[base58btc$g.prefix,tt.decode(`${base58btc$g.prefix}${et}`)]}case base58btc$g.prefix:{const tt=o??base58btc$g;return[base58btc$g.prefix,tt.decode(et)]}case base32$s.prefix:{const tt=o??base32$s;return[base32$s.prefix,tt.decode(et)]}case base36$p.prefix:{const tt=o??base36$p;return[base36$p.prefix,tt.decode(et)]}default:{if(o==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[et[0],o.decode(et)]}}}function toStringV0$1(et,o,tt){const{prefix:rt}=tt;if(rt!==base58btc$g.prefix)throw Error(`Cannot string encode V0 in ${tt.name} encoding`);const nt=o.get(rt);if(nt==null){const ot=tt.encode(et).slice(1);return o.set(rt,ot),ot}else return nt}function toStringV1$1(et,o,tt){const{prefix:rt}=tt,nt=o.get(rt);if(nt==null){const ot=tt.encode(et);return o.set(rt,ot),ot}else return nt}const DAG_PB_CODE$1=112,SHA_256_CODE$1=18;function encodeCID$1(et,o,tt){const rt=encodingLength$3(et),nt=rt+encodingLength$3(o),ot=new Uint8Array(nt+tt.byteLength);return encodeTo$1(et,ot,0),encodeTo$1(o,ot,rt),ot.set(tt,nt),ot}const cidSymbol$1=Symbol.for("@ipld/js-cid/CID"),code$1=0,name$3="identity",encode$A=coerce$h;function digest(et){return create$4(code$1,encode$A(et))}const identity$d={code:code$1,name:name$3,encode:encode$A,digest};function from$h({name:et,code:o,encode:tt}){return new Hasher(et,o,tt)}class Hasher{constructor(o,tt,rt){wt(this,"name");wt(this,"code");wt(this,"encode");this.name=o,this.code=tt,this.encode=rt}digest(o){if(o instanceof Uint8Array){const tt=this.encode(o);return tt instanceof Uint8Array?create$4(this.code,tt):tt.then(rt=>create$4(this.code,rt))}else throw Error("Unknown type, must be binary type")}}function sha(et){return async o=>new Uint8Array(await crypto.subtle.digest(et,o))}const sha256=from$h({name:"sha2-256",code:18,encode:sha("SHA-256")}),base10$o=baseX$g({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$p=Object.freeze(Object.defineProperty({__proto__:null,base10:base10$o},Symbol.toStringTag,{value:"Module"})),base16$o=rfc4648$f({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper$c=rfc4648$f({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$p=Object.freeze(Object.defineProperty({__proto__:null,base16:base16$o,base16upper:base16upper$c},Symbol.toStringTag,{value:"Module"})),base2$o=rfc4648$f({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$p=Object.freeze(Object.defineProperty({__proto__:null,base2:base2$o},Symbol.toStringTag,{value:"Module"})),alphabet$c=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),alphabetBytesToChars$c=alphabet$c.reduce((et,o,tt)=>(et[tt]=o,et),[]),alphabetCharsToBytes$c=alphabet$c.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$z(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$c[tt],o),"")}function decode$F(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$c[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$o=from$i({prefix:"🚀",name:"base256emoji",encode:encode$z,decode:decode$F}),base256emoji$p=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$o},Symbol.toStringTag,{value:"Module"})),base64$r=rfc4648$f({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$c=rfc4648$f({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$d=rfc4648$f({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$c=rfc4648$f({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$s=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$r,base64pad:base64pad$c,base64url:base64url$d,base64urlpad:base64urlpad$c},Symbol.toStringTag,{value:"Module"})),base8$o=rfc4648$f({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$p=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$o},Symbol.toStringTag,{value:"Module"})),identity$c=from$i({prefix:"\0",name:"identity",encode:et=>toString$p(et),decode:et=>fromString$o(et)}),identityBase$c=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$c},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$c={...identityBase$c,...base2$p,...base8$p,...base10$p,...base16$p,...base32$t,...base36$q,...base58$c,...base64$s,...base256emoji$p};function allocUnsafe$b(et=0){return new Uint8Array(et)}function createCodec$c(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$g=createCodec$c("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$c=createCodec$c("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$b(et.length);for(let tt=0;tt{rt=()=>{it(nt)},o.addEventListener("abort",rt)})])}finally{rt!=null&&o.removeEventListener("abort",rt)}}class QueuelessPushable{constructor(){wt(this,"readNext");wt(this,"haveNext");wt(this,"ended");wt(this,"nextResult");this.ended=!1,this.readNext=pDefer(),this.haveNext=pDefer()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");const o=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=pDefer(),o}async throw(o){return this.ended=!0,o!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(o)),{done:!0,value:void 0}}async return(){const o={done:!0,value:void 0};return await this._push(void 0),o}async push(o,tt){await this._push(o,tt)}async end(o,tt){o!=null?await this.throw(o):await this._push(void 0,tt)}async _push(o,tt){if(o!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;o!=null?this.nextResult={done:!1,value:o}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=pDefer(),await raceSignal(this.readNext.promise,tt==null?void 0:tt.signal,tt)}}function queuelessPushable(){return new QueuelessPushable}class UnexpectedEOFError extends Error{constructor(){super(...arguments);wt(this,"name","UnexpectedEOFError");wt(this,"code","ERR_UNEXPECTED_EOF")}}class CodeError extends Error{constructor(tt,rt){super(tt);wt(this,"code");this.code=rt}}let AbortError$7=class extends CodeError{constructor(tt){super(tt,"ABORT_ERR");wt(this,"type");this.type="aborted",this.name="AbortError"}};function byteStream(et,o){const tt=queuelessPushable();et.sink(tt).catch(async it=>{await tt.end(it)}),et.sink=async it=>{for await(const st of it)await tt.push(st);await tt.end()};let rt=et.source;et.source[Symbol.iterator]!=null?rt=et.source[Symbol.iterator]():et.source[Symbol.asyncIterator]!=null&&(rt=et.source[Symbol.asyncIterator]());const nt=new Uint8ArrayList;return{read:async(it,st)=>{var lt,dt;(lt=st==null?void 0:st.signal)==null||lt.throwIfAborted();let at;const ct=new Promise((ht,mt)=>{var ft;at=()=>{mt(new AbortError$7("Read aborted"))},(ft=st==null?void 0:st.signal)==null||ft.addEventListener("abort",at)});try{if(it==null){const{done:mt,value:ft}=await Promise.race([rt.next(),ct]);return mt===!0?new Uint8ArrayList:ft}for(;nt.byteLength{var at;(at=st==null?void 0:st.signal)==null||at.throwIfAborted(),it instanceof Uint8Array?await tt.push(it,st):await tt.push(it.subarray(),st)},unwrap:()=>{if(nt.byteLength>0){const it=et.source;et.source=async function*(){(o==null?void 0:o.yieldBytes)===!1?yield nt:yield*nt,yield*it}()}return et}}}class InvalidMessageLengthError extends Error{constructor(){super(...arguments);wt(this,"name","InvalidMessageLengthError");wt(this,"code","ERR_INVALID_MSG_LENGTH")}}class InvalidDataLengthError extends Error{constructor(){super(...arguments);wt(this,"name","InvalidDataLengthError");wt(this,"code","ERR_MSG_DATA_TOO_LONG")}}class InvalidDataLengthLengthError extends Error{constructor(){super(...arguments);wt(this,"name","InvalidDataLengthLengthError");wt(this,"code","ERR_MSG_LENGTH_TOO_LONG")}}function lpStream(et,o={}){const tt=byteStream(et,o);o.maxDataLength!=null&&o.maxLengthLength==null&&(o.maxLengthLength=encodingLength$6(o.maxDataLength));const rt=(o==null?void 0:o.lengthDecoder)??decode$Z,nt=(o==null?void 0:o.lengthEncoder)??encode$P;return{read:async it=>{let st=-1;const at=new Uint8ArrayList;for(;;){at.append(await tt.read(1,it));try{st=rt(at)}catch(ct){if(ct instanceof RangeError)continue;throw ct}if(st<0)throw new InvalidMessageLengthError("Invalid message length");if((o==null?void 0:o.maxLengthLength)!=null&&at.byteLength>o.maxLengthLength)throw new InvalidDataLengthLengthError("message length length too long");if(st>-1)break}if((o==null?void 0:o.maxDataLength)!=null&&st>o.maxDataLength)throw new InvalidDataLengthError("message length too long");return tt.read(st,it)},write:async(it,st)=>{await tt.write(new Uint8ArrayList(nt(it.byteLength),it),st)},writeV:async(it,st)=>{const at=new Uint8ArrayList(...it.flatMap(ct=>[nt(ct.byteLength),ct]));await tt.write(at,st)},unwrap:()=>tt.unwrap()}}function pair(){const et=pDefer();let o=!1;return{sink:async tt=>{if(o)throw new Error("already piped");o=!0,et.resolve(tt)},source:async function*(){yield*await et.promise}()}}function duplexPair(){const et=pair(),o=pair();return[{source:et.source,sink:o.sink},{source:o.source,sink:et.sink}]}function alloc$4(et=0){return new Uint8Array(et)}function allocUnsafe$a(et=0){return new Uint8Array(et)}const NOISE_MSG_MAX_LENGTH_BYTES=65535,NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG=NOISE_MSG_MAX_LENGTH_BYTES-16;var yl,xl;const DUMP_SESSION_KEYS=!!((xl=(yl=globalThis.process)==null?void 0:yl.env)!=null&&xl.DUMP_SESSION_KEYS);function number$2(et){if(!Number.isSafeInteger(et)||et<0)throw new Error(`positive integer expected, not ${et}`)}function bool(et){if(typeof et!="boolean")throw new Error(`boolean expected, not ${et}`)}function isBytes$1(et){return et instanceof Uint8Array||et!=null&&typeof et=="object"&&et.constructor.name==="Uint8Array"}function bytes(et,...o){if(!isBytes$1(et))throw new Error("Uint8Array expected");if(o.length>0&&!o.includes(et.length))throw new Error(`Uint8Array expected of length ${o}, not of length=${et.length}`)}function exists(et,o=!0){if(et.destroyed)throw new Error("Hash instance has been destroyed");if(o&&et.finished)throw new Error("Hash#digest() has already been called")}function output(et,o){bytes(et);const tt=o.outputLen;if(et.lengthnew Uint32Array(et.buffer,et.byteOffset,Math.floor(et.byteLength/4)),createView=et=>new DataView(et.buffer,et.byteOffset,et.byteLength),isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes(et){if(typeof et!="string")throw new Error(`string expected, got ${typeof et}`);return new Uint8Array(new TextEncoder().encode(et))}function toBytes(et){if(typeof et=="string")et=utf8ToBytes(et);else if(isBytes$1(et))et=copyBytes(et);else throw new Error(`Uint8Array expected, got ${typeof et}`);return et}function checkOpts(et,o){if(o==null||typeof o!="object")throw new Error("options must be defined");return Object.assign(et,o)}function equalBytes(et,o){if(et.length!==o.length)return!1;let tt=0;for(let rt=0;rt(Object.assign(o,et),o);function setBigUint64(et,o,tt,rt){if(typeof et.setBigUint64=="function")return et.setBigUint64(o,tt,rt);const nt=BigInt(32),ot=BigInt(4294967295),it=Number(tt>>nt&ot),st=Number(tt&ot),at=4,ct=0;et.setUint32(o+at,it,rt),et.setUint32(o+ct,st,rt)}function copyBytes(et){return Uint8Array.from(et)}function clean(...et){for(let o=0;oUint8Array.from(et.split("").map(o=>o.charCodeAt(0))),sigma16=_utf8ToBytes("expand 16-byte k"),sigma32=_utf8ToBytes("expand 32-byte k"),sigma16_32=u32(sigma16),sigma32_32=u32(sigma32);sigma32_32.slice();function rotl(et,o){return et<>>32-o}function isAligned32(et){return et.byteOffset%4===0}const BLOCK_LEN=64,BLOCK_LEN32=16,MAX_COUNTER=2**32-1,U32_EMPTY=new Uint32Array;function runCipher(et,o,tt,rt,nt,ot,it,st){const at=nt.length,ct=new Uint8Array(BLOCK_LEN),lt=u32(ct),dt=isAligned32(nt)&&isAligned32(ot),ht=dt?u32(nt):U32_EMPTY,mt=dt?u32(ot):U32_EMPTY;for(let ft=0;ft=MAX_COUNTER)throw new Error("arx: counter overflow");const pt=Math.min(BLOCK_LEN,at-ft);if(dt&&pt===BLOCK_LEN){const gt=ft/4;if(ft%4!==0)throw new Error("arx: invalid block position");for(let yt=0,bt;yt{bytes(st),bytes(at),bytes(ct);const ht=ct.length;if(lt===void 0&&(lt=new Uint8Array(ht)),bytes(lt),number$2(dt),dt<0||dt>=MAX_COUNTER)throw new Error("arx: counter overflow");if(lt.lengthet[o++]&255|(et[o++]&255)<<8;class Poly1305{constructor(o){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,o=toBytes(o),bytes(o,32);const tt=u8to16(o,0),rt=u8to16(o,2),nt=u8to16(o,4),ot=u8to16(o,6),it=u8to16(o,8),st=u8to16(o,10),at=u8to16(o,12),ct=u8to16(o,14);this.r[0]=tt&8191,this.r[1]=(tt>>>13|rt<<3)&8191,this.r[2]=(rt>>>10|nt<<6)&7939,this.r[3]=(nt>>>7|ot<<9)&8191,this.r[4]=(ot>>>4|it<<12)&255,this.r[5]=it>>>1&8190,this.r[6]=(it>>>14|st<<2)&8191,this.r[7]=(st>>>11|at<<5)&8065,this.r[8]=(at>>>8|ct<<8)&8191,this.r[9]=ct>>>5&127;for(let lt=0;lt<8;lt++)this.pad[lt]=u8to16(o,16+2*lt)}process(o,tt,rt=!1){const nt=rt?0:2048,{h:ot,r:it}=this,st=it[0],at=it[1],ct=it[2],lt=it[3],dt=it[4],ht=it[5],mt=it[6],ft=it[7],pt=it[8],gt=it[9],yt=u8to16(o,tt+0),bt=u8to16(o,tt+2),xt=u8to16(o,tt+4),vt=u8to16(o,tt+6),Et=u8to16(o,tt+8),Ct=u8to16(o,tt+10),St=u8to16(o,tt+12),At=u8to16(o,tt+14);let kt=ot[0]+(yt&8191),It=ot[1]+((yt>>>13|bt<<3)&8191),Ot=ot[2]+((bt>>>10|xt<<6)&8191),Nt=ot[3]+((xt>>>7|vt<<9)&8191),Yt=ot[4]+((vt>>>4|Et<<12)&8191),Ft=ot[5]+(Et>>>1&8191),Ht=ot[6]+((Et>>>14|Ct<<2)&8191),Qt=ot[7]+((Ct>>>11|St<<5)&8191),Vt=ot[8]+((St>>>8|At<<8)&8191),Bt=ot[9]+(At>>>5|nt),Wt=0,jt=Wt+kt*st+It*(5*gt)+Ot*(5*pt)+Nt*(5*ft)+Yt*(5*mt);Wt=jt>>>13,jt&=8191,jt+=Ft*(5*ht)+Ht*(5*dt)+Qt*(5*lt)+Vt*(5*ct)+Bt*(5*at),Wt+=jt>>>13,jt&=8191;let Xt=Wt+kt*at+It*st+Ot*(5*gt)+Nt*(5*pt)+Yt*(5*ft);Wt=Xt>>>13,Xt&=8191,Xt+=Ft*(5*mt)+Ht*(5*ht)+Qt*(5*dt)+Vt*(5*lt)+Bt*(5*ct),Wt+=Xt>>>13,Xt&=8191;let Kt=Wt+kt*ct+It*at+Ot*st+Nt*(5*gt)+Yt*(5*pt);Wt=Kt>>>13,Kt&=8191,Kt+=Ft*(5*ft)+Ht*(5*mt)+Qt*(5*ht)+Vt*(5*dt)+Bt*(5*lt),Wt+=Kt>>>13,Kt&=8191;let Pt=Wt+kt*lt+It*ct+Ot*at+Nt*st+Yt*(5*gt);Wt=Pt>>>13,Pt&=8191,Pt+=Ft*(5*pt)+Ht*(5*ft)+Qt*(5*mt)+Vt*(5*ht)+Bt*(5*dt),Wt+=Pt>>>13,Pt&=8191;let Gt=Wt+kt*dt+It*lt+Ot*ct+Nt*at+Yt*st;Wt=Gt>>>13,Gt&=8191,Gt+=Ft*(5*gt)+Ht*(5*pt)+Qt*(5*ft)+Vt*(5*mt)+Bt*(5*ht),Wt+=Gt>>>13,Gt&=8191;let tr=Wt+kt*ht+It*dt+Ot*lt+Nt*ct+Yt*at;Wt=tr>>>13,tr&=8191,tr+=Ft*st+Ht*(5*gt)+Qt*(5*pt)+Vt*(5*ft)+Bt*(5*mt),Wt+=tr>>>13,tr&=8191;let zt=Wt+kt*mt+It*ht+Ot*dt+Nt*lt+Yt*ct;Wt=zt>>>13,zt&=8191,zt+=Ft*at+Ht*st+Qt*(5*gt)+Vt*(5*pt)+Bt*(5*ft),Wt+=zt>>>13,zt&=8191;let lr=Wt+kt*ft+It*mt+Ot*ht+Nt*dt+Yt*lt;Wt=lr>>>13,lr&=8191,lr+=Ft*ct+Ht*at+Qt*st+Vt*(5*gt)+Bt*(5*pt),Wt+=lr>>>13,lr&=8191;let rr=Wt+kt*pt+It*ft+Ot*mt+Nt*ht+Yt*dt;Wt=rr>>>13,rr&=8191,rr+=Ft*lt+Ht*ct+Qt*at+Vt*st+Bt*(5*gt),Wt+=rr>>>13,rr&=8191;let Jt=Wt+kt*gt+It*pt+Ot*ft+Nt*mt+Yt*ht;Wt=Jt>>>13,Jt&=8191,Jt+=Ft*dt+Ht*lt+Qt*ct+Vt*at+Bt*st,Wt+=Jt>>>13,Jt&=8191,Wt=(Wt<<2)+Wt|0,Wt=Wt+jt|0,jt=Wt&8191,Wt=Wt>>>13,Xt+=Wt,ot[0]=jt,ot[1]=Xt,ot[2]=Kt,ot[3]=Pt,ot[4]=Gt,ot[5]=tr,ot[6]=zt,ot[7]=lr,ot[8]=rr,ot[9]=Jt}finalize(){const{h:o,pad:tt}=this,rt=new Uint16Array(10);let nt=o[1]>>>13;o[1]&=8191;for(let st=2;st<10;st++)o[st]+=nt,nt=o[st]>>>13,o[st]&=8191;o[0]+=nt*5,nt=o[0]>>>13,o[0]&=8191,o[1]+=nt,nt=o[1]>>>13,o[1]&=8191,o[2]+=nt,rt[0]=o[0]+5,nt=rt[0]>>>13,rt[0]&=8191;for(let st=1;st<10;st++)rt[st]=o[st]+nt,nt=rt[st]>>>13,rt[st]&=8191;rt[9]-=8192;let ot=(nt^1)-1;for(let st=0;st<10;st++)rt[st]&=ot;ot=~ot;for(let st=0;st<10;st++)o[st]=o[st]&ot|rt[st];o[0]=(o[0]|o[1]<<13)&65535,o[1]=(o[1]>>>3|o[2]<<10)&65535,o[2]=(o[2]>>>6|o[3]<<7)&65535,o[3]=(o[3]>>>9|o[4]<<4)&65535,o[4]=(o[4]>>>12|o[5]<<1|o[6]<<14)&65535,o[5]=(o[6]>>>2|o[7]<<11)&65535,o[6]=(o[7]>>>5|o[8]<<8)&65535,o[7]=(o[8]>>>8|o[9]<<5)&65535;let it=o[0]+tt[0];o[0]=it&65535;for(let st=1;st<8;st++)it=(o[st]+tt[st]|0)+(it>>>16)|0,o[st]=it&65535;clean(rt)}update(o){exists(this);const{buffer:tt,blockLen:rt}=this;o=toBytes(o);const nt=o.length;for(let ot=0;ot>>0,o[ot++]=rt[it]>>>8;return o}digest(){const{buffer:o,outputLen:tt}=this;this.digestInto(o);const rt=o.slice(0,tt);return this.destroy(),rt}}function wrapConstructorWithKey(et){const o=(rt,nt)=>et(nt).update(toBytes(rt)).digest(),tt=et(new Uint8Array(32));return o.outputLen=tt.outputLen,o.blockLen=tt.blockLen,o.create=rt=>et(rt),o}const poly1305=wrapConstructorWithKey(et=>new Poly1305(et));function chachaCore(et,o,tt,rt,nt,ot=20){let it=et[0],st=et[1],at=et[2],ct=et[3],lt=o[0],dt=o[1],ht=o[2],mt=o[3],ft=o[4],pt=o[5],gt=o[6],yt=o[7],bt=nt,xt=tt[0],vt=tt[1],Et=tt[2],Ct=it,St=st,At=at,kt=ct,It=lt,Ot=dt,Nt=ht,Yt=mt,Ft=ft,Ht=pt,Qt=gt,Vt=yt,Bt=bt,Wt=xt,jt=vt,Xt=Et;for(let Pt=0;Pt{et.update(o);const tt=o.length%16;tt&&et.update(ZEROS16.subarray(tt))},ZEROS32=new Uint8Array(32);function computeTag(et,o,tt,rt,nt){const ot=et(o,tt,ZEROS32),it=poly1305.create(ot);nt&&updatePadded(it,nt),updatePadded(it,rt);const st=new Uint8Array(16),at=createView(st);setBigUint64(at,0,BigInt(nt?nt.length:0),!0),setBigUint64(at,8,BigInt(rt.length),!0),it.update(st);const ct=it.digest();return clean(ot,st),ct}const _poly1305_aead=et=>(o,tt,rt)=>(bytes(o,32),bytes(tt),{encrypt(ot,it){const st=ot.length,at=st+16;it?bytes(it,at):it=new Uint8Array(at),et(o,tt,ot,it,1);const ct=computeTag(et,o,tt,it.subarray(0,-16),rt);return it.set(ct,st),clean(ct),it},decrypt(ot,it){const st=ot.length,at=st-16;if(st<16)throw new Error("encrypted data must be at least 16 bytes");it?bytes(it,at):it=new Uint8Array(at);const ct=ot.subarray(0,-16),lt=ot.subarray(-16),dt=computeTag(et,o,tt,ct,rt);if(!equalBytes(lt,dt))throw new Error("invalid tag");return et(o,tt,ct,it,1),clean(dt),it}}),chacha20poly1305=wrapCipher({blockSize:64,nonceLength:12,tagLength:16},_poly1305_aead(chacha20));function extract(et,o,tt){return hash$1(et),tt===void 0&&(tt=new Uint8Array(et.outputLen)),hmac(et,toBytes$2(tt),toBytes$2(o))}const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(et,o,tt,rt=32){if(hash$1(et),number$4(rt),rt>255*et.outputLen)throw new Error("Length should be <= 255*HashLen");const nt=Math.ceil(rt/et.outputLen);tt===void 0&&(tt=EMPTY_BUFFER);const ot=new Uint8Array(nt*et.outputLen),it=hmac.create(et,o),st=it._cloneInto(),at=new Uint8Array(it.outputLen);for(let ct=0;ctet.generateX25519SharedKey(o.privateKey,tt).subarray(0,32),encrypt:et.chaCha20Poly1305Encrypt,decrypt:et.chaCha20Poly1305Decrypt,hash:et.hashSHA256,hkdf:et.getHKDF}}const uint16BEEncode=et=>{const o=allocUnsafe$a(2);return o[0]=et>>8,o[1]=et,o};uint16BEEncode.bytes=2;const uint16BEDecode=et=>{if(et.length<2)throw RangeError("Could not decode int16BE");if(et instanceof Uint8Array){let o=0;return o+=et[0]<<8,o+=et[1],o}return et.getUint16(0)};uint16BEDecode.bytes=2;function registerMetrics(et){return{xxHandshakeSuccesses:et.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:et.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:et.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:et.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:et.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function coerce$g(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$m(et){return new TextEncoder().encode(et)}function toString$n(et){return new TextDecoder().decode(et)}function base$g(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$g=base$g,_brrp__multiformats_scope_baseX$f=src$g;let Encoder$g=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$g=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$h(this,o)}},ComposedDecoder$f=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$h(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$h(et,o){return new ComposedDecoder$f({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$f=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$g(o,tt,rt),this.decoder=new Decoder$g(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$g({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$f(et,o,tt,rt)}function baseX$f({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$f(tt,et);return from$g({prefix:o,name:et,encode:rt,decode:ot=>coerce$g(nt(ot))})}function decode$E(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$y(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$b=alphabet$b.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$x(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$b[tt],o),"")}function decode$D(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$b[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$m=from$g({prefix:"🚀",name:"base256emoji",encode:encode$x,decode:decode$D}),base256emoji$n=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$m},Symbol.toStringTag,{value:"Module"})),base32$q=rfc4648$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$b=rfc4648$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$b=rfc4648$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$b=rfc4648$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$b=rfc4648$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$b=rfc4648$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$b=rfc4648$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$b=rfc4648$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$b=rfc4648$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$r=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$q,base32hex:base32hex$b,base32hexpad:base32hexpad$b,base32hexpadupper:base32hexpadupper$b,base32hexupper:base32hexupper$b,base32pad:base32pad$b,base32padupper:base32padupper$b,base32upper:base32upper$b,base32z:base32z$b},Symbol.toStringTag,{value:"Module"})),base36$n=baseX$f({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$b=baseX$f({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$o=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$n,base36upper:base36upper$b},Symbol.toStringTag,{value:"Module"})),base58btc$f=baseX$f({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$b=baseX$f({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$b=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$f,base58flickr:base58flickr$b},Symbol.toStringTag,{value:"Module"})),base64$p=rfc4648$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$b=rfc4648$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$c=rfc4648$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$b=rfc4648$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$q=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$p,base64pad:base64pad$b,base64url:base64url$c,base64urlpad:base64urlpad$b},Symbol.toStringTag,{value:"Module"})),base8$m=rfc4648$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$n=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$m},Symbol.toStringTag,{value:"Module"})),identity$b=from$g({prefix:"\0",name:"identity",encode:et=>toString$n(et),decode:et=>fromString$m(et)}),identityBase$b=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$b},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$b={...identityBase$b,...base2$n,...base8$n,...base10$n,...base16$n,...base32$r,...base36$o,...base58$b,...base64$q,...base256emoji$n};function createCodec$b(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$f=createCodec$b("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$b=createCodec$b("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$a(et.length);for(let tt=0;ttnt+ot.length,0));const tt=allocUnsafe$a(o);let rt=0;for(const nt of et)tt.set(nt,rt),rt+=nt.length;return tt}function fromString$l(et,o="utf8"){const tt=BASES$b[o];if(tt==null)throw new Error(`Unsupported encoding "${o}"`);return tt.decoder.decode(`${tt.prefix}${et}`)}const is=class is extends Error{constructor(tt="Invalid crypto exchange"){super(tt);wt(this,"code");this.code=is.code}};wt(is,"code","ERR_INVALID_CRYPTO_EXCHANGE");let InvalidCryptoExchangeError=is;const MIN_NONCE=0,MAX_NONCE=4294967295,ERR_MAX_NONCE="Cipherstate has reached maximum n, a new handshake must be performed";class Nonce{constructor(o=MIN_NONCE){wt(this,"n");wt(this,"bytes");wt(this,"view");this.n=o,this.bytes=alloc$4(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,o,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>MAX_NONCE)throw new Error(ERR_MAX_NONCE)}}const ZEROLEN=alloc$4(0);class CipherState{constructor(o,tt=void 0,rt=0){wt(this,"k");wt(this,"n");wt(this,"crypto");this.crypto=o,this.k=tt,this.n=new Nonce(rt)}hasKey(){return!!this.k}encryptWithAd(o,tt){if(!this.hasKey())return tt;this.n.assertValue();const rt=this.crypto.encrypt(tt,this.n.getBytes(),o,this.k);return this.n.increment(),rt}decryptWithAd(o,tt,rt){if(!this.hasKey())return tt;this.n.assertValue();const nt=this.crypto.decrypt(tt,this.n.getBytes(),o,this.k,rt);return this.n.increment(),nt}}class SymmetricState{constructor(o,tt){wt(this,"cs");wt(this,"ck");wt(this,"h");wt(this,"crypto");this.crypto=o;const rt=fromString$l(tt,"utf-8");this.h=hashProtocolName(o,rt),this.ck=this.h,this.cs=new CipherState(o)}mixKey(o){const[tt,rt]=this.crypto.hkdf(this.ck,o);this.ck=tt,this.cs=new CipherState(this.crypto,rt)}mixHash(o){this.h=this.crypto.hash(new Uint8ArrayList(this.h,o))}encryptAndHash(o){const tt=this.cs.encryptWithAd(this.h,o);return this.mixHash(tt),tt}decryptAndHash(o){const tt=this.cs.decryptWithAd(this.h,o);return this.mixHash(o),tt}split(){const[o,tt]=this.crypto.hkdf(this.ck,ZEROLEN);return[new CipherState(this.crypto,o),new CipherState(this.crypto,tt)]}}class AbstractHandshakeState{constructor(o){wt(this,"ss");wt(this,"s");wt(this,"e");wt(this,"rs");wt(this,"re");wt(this,"initiator");wt(this,"crypto");const{crypto:tt,protocolName:rt,prologue:nt,initiator:ot,s:it,e:st,rs:at,re:ct}=o;this.crypto=tt,this.ss=new SymmetricState(tt,rt),this.ss.mixHash(nt),this.initiator=ot,this.s=it,this.e=st,this.rs=at,this.re=ct}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const o=this.crypto.generateKeypair();return this.ss.mixHash(o.publicKey),this.e=o,o.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(o,tt=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(o.byteLength(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.webtransportCerthashes!=null)for(const ot of tt.webtransportCerthashes)rt.uint32(10),rt.bytes(ot);nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt)=>{const nt={webtransportCerthashes:[]},ot=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{nt.webtransportCerthashes.push(tt.bytes());break}default:{tt.skipType(it&7);break}}}return nt})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=tt=>decodeMessage(tt,et.codec())})(NoiseExtensions||(NoiseExtensions={}));var NoiseHandshakePayload;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.identityKey!=null&&tt.identityKey.byteLength>0&&(rt.uint32(10),rt.bytes(tt.identityKey)),tt.identitySig!=null&&tt.identitySig.byteLength>0&&(rt.uint32(18),rt.bytes(tt.identitySig)),tt.extensions!=null&&(rt.uint32(34),NoiseExtensions.codec().encode(tt.extensions,rt)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt)=>{const nt={identityKey:alloc$4(0),identitySig:alloc$4(0)},ot=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{nt.identityKey=tt.bytes();break}case 2:{nt.identitySig=tt.bytes();break}case 4:{nt.extensions=NoiseExtensions.codec().decode(tt,tt.uint32());break}default:{tt.skipType(it&7);break}}}return nt})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=tt=>decodeMessage(tt,et.codec())})(NoiseHandshakePayload||(NoiseHandshakePayload={}));async function createHandshakePayload(et,o,tt){const rt=await et.sign(getSignaturePayload(o));return NoiseHandshakePayload.encode({identityKey:publicKeyToProtobuf(et.publicKey),identitySig:rt,extensions:tt})}async function decodeHandshakePayload(et,o,tt){try{const rt=NoiseHandshakePayload.decode(et),nt=publicKeyFromProtobuf(rt.identityKey);if((tt==null?void 0:tt.equals(nt))===!1)throw new Error(`Payload identity key ${nt} does not match expected remote identity key ${tt}`);if(!o)throw new Error("Remote static does not exist");const ot=getSignaturePayload(o);if(!await nt.verify(ot,rt.identitySig))throw new Error("Invalid payload signature");return rt}catch(rt){throw new UnexpectedPeerError(rt.message)}}function getSignaturePayload(et){const o=fromString$l("noise-libp2p-static-key:");return et instanceof Uint8Array?concat$1([o,et],o.length+et.length):(et.prepend(o),et)}async function performHandshakeInitiator(et,o){const{log:tt,connection:rt,crypto:nt,privateKey:ot,prologue:it,s:st,remoteIdentityKey:at,extensions:ct}=et,lt=await createHandshakePayload(ot,st.publicKey,ct),dt=new XXHandshakeState({crypto:nt,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:it,s:st});logLocalStaticKeys(dt.s,tt),tt.trace("Stage 0 - Initiator starting to send first message."),await rt.write(dt.writeMessageA(ZEROLEN),o),tt.trace("Stage 0 - Initiator finished sending first message."),logLocalEphemeralKeys(dt.e,tt),tt.trace("Stage 1 - Initiator waiting to receive first message from responder...");const ht=dt.readMessageB(await rt.read(o));tt.trace("Stage 1 - Initiator received the message."),logRemoteEphemeralKey(dt.re,tt),logRemoteStaticKey(dt.rs,tt),tt.trace("Initiator going to check remote's signature...");const mt=await decodeHandshakePayload(ht,dt.rs,at);tt.trace("All good with the signature!"),tt.trace("Stage 2 - Initiator sending third handshake message."),await rt.write(dt.writeMessageC(lt),o),tt.trace("Stage 2 - Initiator sent message with signed payload.");const[ft,pt]=dt.ss.split();return logCipherState(ft,pt,tt),{payload:mt,encrypt:gt=>ft.encryptWithAd(ZEROLEN,gt),decrypt:(gt,yt)=>pt.decryptWithAd(ZEROLEN,gt,yt)}}async function performHandshakeResponder(et,o){const{log:tt,connection:rt,crypto:nt,privateKey:ot,prologue:it,s:st,remoteIdentityKey:at,extensions:ct}=et,lt=await createHandshakePayload(ot,st.publicKey,ct),dt=new XXHandshakeState({crypto:nt,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:it,s:st});logLocalStaticKeys(dt.s,tt),tt.trace("Stage 0 - Responder waiting to receive first message."),dt.readMessageA(await rt.read(o)),tt.trace("Stage 0 - Responder received first message."),logRemoteEphemeralKey(dt.re,tt),tt.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await rt.write(dt.writeMessageB(lt),o),tt.trace("Stage 1 - Responder sent the second handshake message with signed payload."),logLocalEphemeralKeys(dt.e,tt),tt.trace("Stage 2 - Responder waiting for third handshake message...");const ht=dt.readMessageC(await rt.read(o));tt.trace("Stage 2 - Responder received the message, finished handshake.");const mt=await decodeHandshakePayload(ht,dt.rs,at),[ft,pt]=dt.ss.split();return logCipherState(ft,pt,tt),{payload:mt,encrypt:gt=>pt.encryptWithAd(ZEROLEN,gt),decrypt:(gt,yt)=>ft.decryptWithAd(ZEROLEN,gt,yt)}}const CHACHA_TAG_LENGTH=16;function encryptStream(et,o){return async function*(tt){for await(const rt of tt)for(let nt=0;ntrt.length&&(ot=rt.length);let it;rt instanceof Uint8Array?it=et.encrypt(rt.subarray(nt,ot)):it=et.encrypt(rt.sublist(nt,ot)),o==null||o.encryptedPackets.increment(),yield new Uint8ArrayList(uint16BEEncode(it.byteLength),it)}}}function decryptStream(et,o){return async function*(tt){for await(const rt of tt)for(let nt=0;ntrt.length&&(ot=rt.length),ot-CHACHA_TAG_LENGTHdecode$U(it,{lengthDecoder:uint16BEDecode}),decryptStream(tt,this.metrics),rt),nt}}function noise(et={}){return o=>new Noise(o,et)}const peerDiscoverySymbol$1=Symbol.for("@libp2p/peer-discovery");function setMaxListeners$7(){}const setMaxListeners$6=(et,...o)=>{try{[...o]}catch{}};var Xr,Cl;let TypedEventEmitter$2=(Cl=class extends EventTarget{constructor(){super();hr(this,Xr,new Map);setMaxListeners$6(1/0,this)}listenerCount(tt){const rt=Lt(this,Xr).get(tt);return rt==null?0:rt.length}addEventListener(tt,rt,nt){super.addEventListener(tt,rt,nt);let ot=Lt(this,Xr).get(tt);ot==null&&(ot=[],Lt(this,Xr).set(tt,ot)),ot.push({callback:rt,once:(nt!==!0&&nt!==!1&&(nt==null?void 0:nt.once))??!1})}removeEventListener(tt,rt,nt){super.removeEventListener(tt.toString(),rt??null,nt);let ot=Lt(this,Xr).get(tt);ot!=null&&(ot=ot.filter(({callback:it})=>it!==rt),Lt(this,Xr).set(tt,ot))}dispatchEvent(tt){const rt=super.dispatchEvent(tt);let nt=Lt(this,Xr).get(tt.type);return nt==null||(nt=nt.filter(({once:ot})=>!ot),Lt(this,Xr).set(tt.type,nt)),rt}safeDispatchEvent(tt,rt={}){return this.dispatchEvent(new CustomEvent(tt,rt))}},Xr=new WeakMap,Cl);const serviceCapabilities$4=Symbol.for("@libp2p/service-capabilities"),DNS4=base$f("dns4"),DNS6=base$f("dns6"),DNSADDR=base$f("dnsaddr"),DNS$1=or$g(base$f("dns"),DNSADDR,DNS4,DNS6),IP=or$g(base$f("ip4"),base$f("ip6")),TCP$1=or$g(and$1(IP,base$f("tcp")),and$1(DNS$1,base$f("tcp"))),UDP=and$1(IP,base$f("udp")),UTP=and$1(UDP,base$f("utp")),QUIC=and$1(UDP,base$f("quic")),QUICV1=and$1(UDP,base$f("quic-v1")),_WebSockets$1=or$g(and$1(TCP$1,base$f("ws")),and$1(DNS$1,base$f("ws"))),WebSockets$2=or$g(and$1(_WebSockets$1,base$f("p2p")),_WebSockets$1),_WebSocketsSecure$1=or$g(and$1(TCP$1,base$f("wss")),and$1(DNS$1,base$f("wss")),and$1(TCP$1,base$f("tls"),base$f("ws")),and$1(DNS$1,base$f("tls"),base$f("ws"))),WebSocketsSecure$1=or$g(and$1(_WebSocketsSecure$1,base$f("p2p")),_WebSocketsSecure$1),HTTP=or$g(and$1(TCP$1,base$f("http")),and$1(IP,base$f("http")),and$1(DNS$1,base$f("http"))),HTTPS=or$g(and$1(TCP$1,base$f("https")),and$1(IP,base$f("https")),and$1(DNS$1,base$f("https"))),_WebRTCDirect$1=and$1(UDP,base$f("webrtc-direct"),base$f("certhash")),WebRTCDirect$1=or$g(and$1(_WebRTCDirect$1,base$f("p2p")),_WebRTCDirect$1),_WebTransport$1=and$1(QUICV1,base$f("webtransport"),base$f("certhash"),base$f("certhash")),WebTransport$1=or$g(and$1(_WebTransport$1,base$f("p2p")),_WebTransport$1),P2PWebRTCStar=or$g(and$1(WebSockets$2,base$f("p2p-webrtc-star"),base$f("p2p")),and$1(WebSocketsSecure$1,base$f("p2p-webrtc-star"),base$f("p2p")),and$1(WebSockets$2,base$f("p2p-webrtc-star")),and$1(WebSocketsSecure$1,base$f("p2p-webrtc-star"))),P2PWebRTCDirect=or$g(and$1(HTTP,base$f("p2p-webrtc-direct"),base$f("p2p")),and$1(HTTPS,base$f("p2p-webrtc-direct"),base$f("p2p")),and$1(HTTP,base$f("p2p-webrtc-direct")),and$1(HTTPS,base$f("p2p-webrtc-direct"))),Reliable=or$g(_WebSockets$1,_WebSocketsSecure$1,HTTP,HTTPS,P2PWebRTCStar,P2PWebRTCDirect,TCP$1,UTP,QUIC,DNS$1,WebRTCDirect$1,WebTransport$1),_P2P$1=or$g(and$1(Reliable,base$f("p2p")),P2PWebRTCStar,P2PWebRTCDirect,WebRTCDirect$1,WebTransport$1,base$f("p2p")),_Circuit$1=or$g(and$1(_P2P$1,base$f("p2p-circuit"),_P2P$1),and$1(_P2P$1,base$f("p2p-circuit")),and$1(base$f("p2p-circuit"),_P2P$1),and$1(Reliable,base$f("p2p-circuit")),and$1(base$f("p2p-circuit"),Reliable),base$f("p2p-circuit")),CircuitRecursive=()=>or$g(and$1(_Circuit$1,CircuitRecursive),_Circuit$1),Circuit$1=CircuitRecursive(),P2P=or$g(and$1(Circuit$1,_P2P$1,Circuit$1),and$1(_P2P$1,Circuit$1),and$1(Circuit$1,_P2P$1),Circuit$1,_P2P$1);function makeMatchesFunction(et){function o(tt){let rt;try{rt=multiaddr(tt)}catch{return!1}const nt=et(rt.protoNames());return nt===null?!1:nt===!0||nt===!1?nt:nt.length===0}return o}function and$1(...et){function o(tt){if(tt.length(rt=typeof nt=="function"?nt().partialMatch(tt):nt.partialMatch(tt),Array.isArray(rt)&&(tt=rt),rt===null)),rt}return{toString:function(){return"{ "+et.join(" ")+" }"},input:et,matches:makeMatchesFunction(o),partialMatch:o}}function or$g(...et){function o(rt){let nt=null;return et.some(ot=>{const it=typeof ot=="function"?ot().partialMatch(rt):ot.partialMatch(rt);return it!=null?(nt=it,!0):!1}),nt}return{toString:function(){return"{ "+et.join(" ")+" }"},input:et,matches:makeMatchesFunction(o),partialMatch:o}}function base$f(et){const o=et;function tt(nt){let ot;try{ot=multiaddr(nt)}catch{return!1}const it=ot.protoNames();return it.length===1&&it[0]===o}function rt(nt){return nt.length===0?null:nt[0]===o?nt.slice(1):null}return{toString:function(){return o},matches:tt,partialMatch:rt}}const DEFAULT_BOOTSTRAP_TAG_NAME$1="bootstrap",DEFAULT_BOOTSTRAP_TAG_VALUE$1=50,DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT=1e3;var Sl,Al,$l,_l;class Bootstrap extends(_l=TypedEventEmitter$2,$l=peerDiscoverySymbol$1,Al=Symbol.toStringTag,Sl=serviceCapabilities$4,_l){constructor(tt,rt={list:[]}){if(rt.list==null||rt.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super();wt(this,"log");wt(this,"timer");wt(this,"list");wt(this,"timeout");wt(this,"components");wt(this,"_init");wt(this,$l,this);wt(this,Al,"@libp2p/bootstrap");wt(this,Sl,["@libp2p/peer-discovery"]);this.components=tt,this.log=tt.logger.forComponent("libp2p:bootstrap"),this.timeout=rt.timeout??DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT,this.list=[];for(const nt of rt.list){if(!P2P.matches(nt)){this.log.error("Invalid multiaddr");continue}const ot=multiaddr(nt),it=ot.getPeerId();if(it==null){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const st={id:peerIdFromString$1(it),multiaddrs:[ot]};this.list.push(st)}this._init=rt}isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(tt=>{this.log.error(tt)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(const tt of this.list){if(await this.components.peerStore.merge(tt.id,{tags:{[this._init.tagName??DEFAULT_BOOTSTRAP_TAG_NAME$1]:{value:this._init.tagValue??DEFAULT_BOOTSTRAP_TAG_VALUE$1,ttl:this._init.tagTTL}},multiaddrs:tt.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:tt}),this.components.connectionManager.openConnection(tt.id).catch(rt=>{this.log.error("could not dial bootstrap peer %p",tt.id,rt)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}}wt(Bootstrap,"tag","bootstrap");function bootstrap(et){return o=>new Bootstrap(o,et)}var gs;let UnsupportedProtocolError$1=(gs=class extends Error{constructor(o="Unsupported protocol error"){super(o),this.name="UnsupportedProtocolError"}},wt(gs,"name","UnsupportedProtocolError"),gs);var ys;let InvalidMessageError$2=(ys=class extends Error{constructor(o="Invalid message"){super(o),this.name="InvalidMessageError"}},wt(ys,"name","InvalidMessageError"),ys);function setMaxListeners$5(){}const setMaxListeners$4=(et,...o)=>{try{[...o]}catch{}},serviceCapabilities$3=Symbol.for("@libp2p/service-capabilities");function equals$5(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;tt=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$f=base$e,_brrp__multiformats_scope_baseX$e=src$f;let Encoder$f=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$f=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$f(this,o)}},ComposedDecoder$e=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$f(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$f(et,o){return new ComposedDecoder$e({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$e=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$f(o,tt,rt),this.decoder=new Decoder$f(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$f({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$e(et,o,tt,rt)}function baseX$e({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$e(tt,et);return from$f({prefix:o,name:et,encode:rt,decode:ot=>coerce$f(nt(ot))})}function decode$C(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$w(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$a=alphabet$a.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$v(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$a[tt],o),"")}function decode$B(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$a[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$k=from$f({prefix:"🚀",name:"base256emoji",encode:encode$v,decode:decode$B}),base256emoji$l=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$k},Symbol.toStringTag,{value:"Module"})),base32$o=rfc4648$d({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$a=rfc4648$d({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$a=rfc4648$d({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$a=rfc4648$d({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$a=rfc4648$d({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$a=rfc4648$d({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$a=rfc4648$d({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$a=rfc4648$d({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$a=rfc4648$d({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$p=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$o,base32hex:base32hex$a,base32hexpad:base32hexpad$a,base32hexpadupper:base32hexpadupper$a,base32hexupper:base32hexupper$a,base32pad:base32pad$a,base32padupper:base32padupper$a,base32upper:base32upper$a,base32z:base32z$a},Symbol.toStringTag,{value:"Module"})),base36$l=baseX$e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$a=baseX$e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$m=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$l,base36upper:base36upper$a},Symbol.toStringTag,{value:"Module"})),base58btc$e=baseX$e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$a=baseX$e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$a=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$e,base58flickr:base58flickr$a},Symbol.toStringTag,{value:"Module"})),base64$n=rfc4648$d({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$a=rfc4648$d({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$b=rfc4648$d({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$a=rfc4648$d({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$o=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$n,base64pad:base64pad$a,base64url:base64url$b,base64urlpad:base64urlpad$a},Symbol.toStringTag,{value:"Module"})),base8$k=rfc4648$d({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$l=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$k},Symbol.toStringTag,{value:"Module"})),identity$a=from$f({prefix:"\0",name:"identity",encode:et=>toString$l(et),decode:et=>fromString$k(et)}),identityBase$a=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$a},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;var encode_1$2=encode$u,MSB$4=128,REST$4=127,MSBALL$2=~REST$4,INT$2=Math.pow(2,31);function encode$u(et,o,tt){o=o||[],tt=tt||0;for(var rt=tt;et>=INT$2;)o[tt++]=et&255|MSB$4,et/=128;for(;et&MSBALL$2;)o[tt++]=et&255|MSB$4,et>>>=7;return o[tt]=et|0,encode$u.bytes=tt-rt+1,o}var decode$A=read$3,MSB$1$2=128,REST$1$2=127;function read$3(et,rt){var tt=0,rt=rt||0,nt=0,ot=rt,it,st=et.length;do{if(ot>=st)throw read$3.bytes=0,new RangeError("Could not decode varint");it=et[ot++],tt+=nt<28?(it&REST$1$2)<=MSB$1$2);return read$3.bytes=ot-rt,tt}var N1$2=Math.pow(2,7),N2$2=Math.pow(2,14),N3$2=Math.pow(2,21),N4$2=Math.pow(2,28),N5$2=Math.pow(2,35),N6$2=Math.pow(2,42),N7$2=Math.pow(2,49),N8$2=Math.pow(2,56),N9$2=Math.pow(2,63),length$2=function(et){return et"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$a=createCodec$a("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$9(et.length);for(let tt=0;tt(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.publicKey!=null&&tt.publicKey.byteLength>0&&(rt.uint32(10),rt.bytes(tt.publicKey)),tt.payloadType!=null&&tt.payloadType.byteLength>0&&(rt.uint32(18),rt.bytes(tt.payloadType)),tt.payload!=null&&tt.payload.byteLength>0&&(rt.uint32(26),rt.bytes(tt.payload)),tt.signature!=null&&tt.signature.byteLength>0&&(rt.uint32(42),rt.bytes(tt.signature)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={publicKey:alloc$3(0),payloadType:alloc$3(0),payload:alloc$3(0),signature:alloc$3(0)},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.publicKey=tt.bytes();break}case 2:{ot.payloadType=tt.bytes();break}case 3:{ot.payload=tt.bytes();break}case 5:{ot.signature=tt.bytes();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(Envelope||(Envelope={}));class InvalidSignatureError extends Error{constructor(o="Invalid signature"){super(o),this.name="InvalidSignatureError"}}const dn=class dn{constructor(o){wt(this,"publicKey");wt(this,"payloadType");wt(this,"payload");wt(this,"signature");wt(this,"marshaled");const{publicKey:tt,payloadType:rt,payload:nt,signature:ot}=o;this.publicKey=tt,this.payloadType=rt,this.payload=nt,this.signature=ot}marshal(){return this.marshaled==null&&(this.marshaled=Envelope.encode({publicKey:publicKeyToProtobuf(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(o){return equals$5(this.marshal(),o.marshal())}async validate(o){const tt=formatSignaturePayload(o,this.payloadType,this.payload);return this.publicKey.verify(tt.subarray(),this.signature)}};wt(dn,"createFromProtobuf",async o=>{const tt=Envelope.decode(o),rt=publicKeyFromProtobuf(tt.publicKey);return new dn({publicKey:rt,payloadType:tt.payloadType,payload:tt.payload,signature:tt.signature})}),wt(dn,"seal",async(o,tt)=>{if(tt==null)throw new Error("Missing private key");const rt=o.domain,nt=o.codec,ot=o.marshal(),it=formatSignaturePayload(rt,nt,ot),st=await tt.sign(it.subarray());return new dn({publicKey:tt.publicKey,payloadType:nt,payload:ot,signature:st})}),wt(dn,"openAndCertify",async(o,tt)=>{const rt=await dn.createFromProtobuf(o);if(!await rt.validate(tt))throw new InvalidSignatureError("Envelope signature is not valid for the given domain");return rt});let RecordEnvelope=dn;const formatSignaturePayload=(et,o,tt)=>{const rt=fromString$j(et),nt=encode$P(rt.byteLength),ot=encode$P(o.length),it=encode$P(tt.length);return new Uint8ArrayList(nt,rt,ot,o,it,tt)};function arrayEquals(et,o){const tt=(rt,nt)=>rt.toString().localeCompare(nt.toString());return et.length!==o.length?!1:(o.sort(tt),et.sort(tt).every((rt,nt)=>o[nt].equals(rt)))}const ENVELOPE_DOMAIN_PEER_RECORD="libp2p-peer-record",ENVELOPE_PAYLOAD_TYPE_PEER_RECORD=Uint8Array.from([3,1]);var PeerRecord$1;(function(et){(function(tt){let rt;tt.codec=()=>(rt==null&&(rt=message$1((nt,ot,it={})=>{it.lengthDelimited!==!1&&ot.fork(),nt.multiaddr!=null&&nt.multiaddr.byteLength>0&&(ot.uint32(10),ot.bytes(nt.multiaddr)),it.lengthDelimited!==!1&&ot.ldelim()},(nt,ot,it={})=>{const st={multiaddr:alloc$3(0)},at=ot==null?nt.len:nt.pos+ot;for(;nt.pos>>3){case 1:{st.multiaddr=nt.bytes();break}default:{nt.skipType(ct&7);break}}}return st})),rt),tt.encode=nt=>encodeMessage(nt,tt.codec()),tt.decode=(nt,ot)=>decodeMessage(nt,tt.codec(),ot)})(et.AddressInfo||(et.AddressInfo={}));let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.peerId!=null&&tt.peerId.byteLength>0&&(rt.uint32(10),rt.bytes(tt.peerId)),tt.seq!=null&&tt.seq!==0n&&(rt.uint32(16),rt.uint64(tt.seq)),tt.addresses!=null)for(const ot of tt.addresses)rt.uint32(26),et.AddressInfo.codec().encode(ot,rt);nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={peerId:alloc$3(0),seq:0n,addresses:[]},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.peerId=tt.bytes();break}case 2:{ot.seq=tt.uint64();break}case 3:{if(((st=nt.limits)==null?void 0:st.addresses)!=null&&ot.addresses.length===nt.limits.addresses)throw new MaxLengthError('Decode error - map field "addresses" had too many elements');ot.addresses.push(et.AddressInfo.codec().decode(tt,tt.uint32(),{limits:(at=nt.limits)==null?void 0:at.addresses$}));break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(PeerRecord$1||(PeerRecord$1={}));const on=class on{constructor(o){wt(this,"peerId");wt(this,"multiaddrs");wt(this,"seqNumber");wt(this,"domain",on.DOMAIN);wt(this,"codec",on.CODEC);wt(this,"marshaled");const{peerId:tt,multiaddrs:rt,seqNumber:nt}=o;this.peerId=tt,this.multiaddrs=rt??[],this.seqNumber=nt??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=PeerRecord$1.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(o=>({multiaddr:o.bytes}))})),this.marshaled}equals(o){return!(!(o instanceof on)||!this.peerId.equals(o.peerId)||this.seqNumber!==o.seqNumber||!arrayEquals(this.multiaddrs,o.multiaddrs))}};wt(on,"createFromProtobuf",o=>{const tt=PeerRecord$1.decode(o),rt=peerIdFromMultihash(decode$y(tt.peerId)),nt=(tt.addresses??[]).map(it=>multiaddr(it.multiaddr)),ot=tt.seq;return new on({peerId:rt,multiaddrs:nt,seqNumber:ot})}),wt(on,"DOMAIN",ENVELOPE_DOMAIN_PEER_RECORD),wt(on,"CODEC",ENVELOPE_PAYLOAD_TYPE_PEER_RECORD);let PeerRecord=on;function isAsyncIterable$4(et){return et[Symbol.asyncIterator]!=null}function drain(et){if(isAsyncIterable$4(et))return(async()=>{for await(const o of et);})();for(const o of et);}const CustomEvent$1=globalThis.CustomEvent??Event;async function*parallel(et,o={}){let tt=o.concurrency??1/0;tt<1&&(tt=1/0);const rt=o.ordered==null?!1:o.ordered,nt=new EventTarget,ot=[];let it=pDefer(),st=pDefer(),at=!1,ct,lt=!1;nt.addEventListener("task-complete",()=>{st.resolve()}),Promise.resolve().then(async()=>{try{for await(const ft of et){if(ot.length===tt&&(it=pDefer(),await it.promise),lt)break;const pt={done:!1};ot.push(pt),ft().then(gt=>{pt.done=!0,pt.ok=!0,pt.value=gt,nt.dispatchEvent(new CustomEvent$1("task-complete"))},gt=>{pt.done=!0,pt.err=gt,nt.dispatchEvent(new CustomEvent$1("task-complete"))})}at=!0,nt.dispatchEvent(new CustomEvent$1("task-complete"))}catch(ft){ct=ft,nt.dispatchEvent(new CustomEvent$1("task-complete"))}});function dt(){var ft;return rt?(ft=ot[0])==null?void 0:ft.done:!!ot.find(pt=>pt.done)}function*ht(){for(;ot.length>0&&ot[0].done;){const ft=ot[0];if(ot.shift(),ft.ok)yield ft.value;else throw lt=!0,it.resolve(),ft.err;it.resolve()}}function*mt(){for(;dt();)for(let ft=0;ft{const it=await tt.read(ot);return nt.decode(it)},write:async(nt,ot,it)=>{await tt.write(ot.encode(nt),it)},writeV:async(nt,ot,it)=>{await tt.writeV(nt.map(st=>ot.encode(st)),it)},pb:nt=>({read:async ot=>rt.read(nt,ot),write:async(ot,it)=>rt.write(ot,nt,it),writeV:async(ot,it)=>rt.writeV(ot,nt,it),unwrap:()=>rt}),unwrap:()=>tt.unwrap()};return rt}function coerce$e(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$i(et){return new TextEncoder().encode(et)}function toString$k(et){return new TextDecoder().decode(et)}function base$d(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$e=base$d,_brrp__multiformats_scope_baseX$d=src$e;let Encoder$e=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$e=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$e(this,o)}},ComposedDecoder$d=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$e(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$e(et,o){return new ComposedDecoder$d({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$d=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$e(o,tt,rt),this.decoder=new Decoder$e(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$e({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$d(et,o,tt,rt)}function baseX$d({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$d(tt,et);return from$e({prefix:o,name:et,encode:rt,decode:ot=>coerce$e(nt(ot))})}function decode$x(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$t(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$9=alphabet$9.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$s(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$9[tt],o),"")}function decode$w(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$9[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$i=from$e({prefix:"🚀",name:"base256emoji",encode:encode$s,decode:decode$w}),base256emoji$j=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$i},Symbol.toStringTag,{value:"Module"})),base32$m=rfc4648$c({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$9=rfc4648$c({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$9=rfc4648$c({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$9=rfc4648$c({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$9=rfc4648$c({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$9=rfc4648$c({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$9=rfc4648$c({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$9=rfc4648$c({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$9=rfc4648$c({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$n=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$m,base32hex:base32hex$9,base32hexpad:base32hexpad$9,base32hexpadupper:base32hexpadupper$9,base32hexupper:base32hexupper$9,base32pad:base32pad$9,base32padupper:base32padupper$9,base32upper:base32upper$9,base32z:base32z$9},Symbol.toStringTag,{value:"Module"})),base36$j=baseX$d({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$9=baseX$d({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$k=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$j,base36upper:base36upper$9},Symbol.toStringTag,{value:"Module"})),base58btc$d=baseX$d({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$9=baseX$d({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$9=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$d,base58flickr:base58flickr$9},Symbol.toStringTag,{value:"Module"})),base64$l=rfc4648$c({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$9=rfc4648$c({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$a=rfc4648$c({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$9=rfc4648$c({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$m=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$l,base64pad:base64pad$9,base64url:base64url$a,base64urlpad:base64urlpad$9},Symbol.toStringTag,{value:"Module"})),base8$i=rfc4648$c({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$j=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$i},Symbol.toStringTag,{value:"Module"})),identity$9=from$e({prefix:"\0",name:"identity",encode:et=>toString$k(et),decode:et=>fromString$i(et)}),identityBase$9=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$9},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$9={...identityBase$9,...base2$j,...base8$j,...base10$j,...base16$j,...base32$n,...base36$k,...base58$9,...base64$m,...base256emoji$j};function allocUnsafe$8(et=0){return new Uint8Array(et)}function createCodec$9(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$d=createCodec$9("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$9=createCodec$9("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$8(et.length);for(let tt=0;tt(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.protocolVersion!=null&&(rt.uint32(42),rt.string(tt.protocolVersion)),tt.agentVersion!=null&&(rt.uint32(50),rt.string(tt.agentVersion)),tt.publicKey!=null&&(rt.uint32(10),rt.bytes(tt.publicKey)),tt.listenAddrs!=null)for(const ot of tt.listenAddrs)rt.uint32(18),rt.bytes(ot);if(tt.observedAddr!=null&&(rt.uint32(34),rt.bytes(tt.observedAddr)),tt.protocols!=null)for(const ot of tt.protocols)rt.uint32(26),rt.string(ot);tt.signedPeerRecord!=null&&(rt.uint32(66),rt.bytes(tt.signedPeerRecord)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at;const ot={listenAddrs:[],protocols:[]},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 5:{ot.protocolVersion=tt.string();break}case 6:{ot.agentVersion=tt.string();break}case 1:{ot.publicKey=tt.bytes();break}case 2:{if(((st=nt.limits)==null?void 0:st.listenAddrs)!=null&&ot.listenAddrs.length===nt.limits.listenAddrs)throw new MaxLengthError('Decode error - map field "listenAddrs" had too many elements');ot.listenAddrs.push(tt.bytes());break}case 4:{ot.observedAddr=tt.bytes();break}case 3:{if(((at=nt.limits)==null?void 0:at.protocols)!=null&&ot.protocols.length===nt.limits.protocols)throw new MaxLengthError('Decode error - map field "protocols" had too many elements');ot.protocols.push(tt.string());break}case 8:{ot.signedPeerRecord=tt.bytes();break}default:{tt.skipType(ct&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(Identify$1||(Identify$1={}));function isElectron$1(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}var isElectron_1=isElectron$1;const detectElectron=getDefaultExportFromCjs(isElectron_1),isEnvWithDom=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,isElectron=detectElectron(),isBrowser=isEnvWithDom&&!isElectron,isElectronMain=isElectron&&!isEnvWithDom,isElectronRenderer=isElectron&&isEnvWithDom,isNode=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!isElectron,isWebWorker=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,isReactNative=typeof navigator<"u"&&navigator.product==="ReactNative",defaultValues={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:MAX_IDENTIFY_MESSAGE_SIZE,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:MAX_PUSH_CONCURRENCY};function getCleanMultiaddr(et){if(et!=null&&et.length>0)try{return multiaddr(et)}catch{}}function getAgentVersion(et,o){return o!=null||(o=`${et.name}/${et.version}`,isNode||isElectronMain?o+=` UserAgent=${globalThis.process.version}`:(isBrowser||isWebWorker||isElectronRenderer||isReactNative)&&(o+=` UserAgent=${globalThis.navigator.userAgent}`)),o}async function consumeIdentifyMessage(et,o,tt,rt,nt){if(tt("received identify from %p",rt.remotePeer),nt==null)throw new InvalidMessageError$2("message was null or undefined");const ot={};if(nt.listenAddrs.length>0&&(ot.addresses=nt.listenAddrs.map(at=>({isCertified:!1,multiaddr:multiaddr(at)}))),nt.protocols.length>0&&(ot.protocols=nt.protocols),nt.publicKey!=null){const at=publicKeyFromProtobuf(nt.publicKey);if(!peerIdFromPublicKey(at).equals(rt.remotePeer))throw new InvalidMessageError$2("public key did not match remote PeerId");ot.publicKey=at}let it;if(nt.signedPeerRecord!=null){tt.trace("received signedPeerRecord from %p",rt.remotePeer);let at=nt.signedPeerRecord;const ct=await RecordEnvelope.openAndCertify(at,PeerRecord.DOMAIN);let lt=PeerRecord.createFromProtobuf(ct.payload);const dt=peerIdFromCID(ct.publicKey.toCID());if(!lt.peerId.equals(dt))throw new InvalidMessageError$2("signing key does not match PeerId in the PeerRecord");if(!rt.remotePeer.equals(lt.peerId))throw new InvalidMessageError$2("signing key does not match remote PeerId");let ht;try{ht=await et.get(lt.peerId)}catch(mt){if(mt.name!=="NotFoundError")throw mt}if(ht!=null&&(ot.metadata=ht.metadata,ht.peerRecordEnvelope!=null)){const mt=await RecordEnvelope.createFromProtobuf(ht.peerRecordEnvelope),ft=PeerRecord.createFromProtobuf(mt.payload);ft.seqNumber>=lt.seqNumber&&(tt("sequence number was lower or equal to existing sequence number - stored: %d received: %d",ft.seqNumber,lt.seqNumber),lt=ft,at=ht.peerRecordEnvelope)}ot.peerRecordEnvelope=at,ot.addresses=lt.multiaddrs.map(mt=>({isCertified:!0,multiaddr:mt})),it={seq:lt.seqNumber,addresses:lt.multiaddrs}}else tt("%p did not send a signed peer record",rt.remotePeer);if(tt.trace("patching %p with",rt.remotePeer,ot),await et.patch(rt.remotePeer,ot),nt.agentVersion!=null||nt.protocolVersion!=null){const at={};nt.agentVersion!=null&&(at.AgentVersion=fromString$h(nt.agentVersion)),nt.protocolVersion!=null&&(at.ProtocolVersion=fromString$h(nt.protocolVersion)),tt.trace("merging %p metadata",rt.remotePeer,at),await et.merge(rt.remotePeer,{metadata:at})}const st={peerId:rt.remotePeer,protocolVersion:nt.protocolVersion,agentVersion:nt.agentVersion,publicKey:nt.publicKey,listenAddrs:nt.listenAddrs.map(at=>multiaddr(at)),observedAddr:nt.observedAddr==null?void 0:multiaddr(nt.observedAddr),protocols:nt.protocols,signedPeerRecord:it,connection:rt};return o.safeDispatchEvent("peer:identify",{detail:st}),st}class AbstractIdentify{constructor(o,tt){wt(this,"host");wt(this,"protocol");wt(this,"started");wt(this,"timeout");wt(this,"peerId");wt(this,"privateKey");wt(this,"peerStore");wt(this,"registrar");wt(this,"addressManager");wt(this,"maxInboundStreams");wt(this,"maxOutboundStreams");wt(this,"maxMessageSize");wt(this,"maxObservedAddresses");wt(this,"events");wt(this,"runOnLimitedConnection");wt(this,"log");this.protocol=tt.protocol,this.started=!1,this.peerId=o.peerId,this.privateKey=o.privateKey,this.peerStore=o.peerStore,this.registrar=o.registrar,this.addressManager=o.addressManager,this.events=o.events,this.log=tt.log,this.timeout=tt.timeout??defaultValues.timeout,this.maxInboundStreams=tt.maxInboundStreams??defaultValues.maxInboundStreams,this.maxOutboundStreams=tt.maxOutboundStreams??defaultValues.maxOutboundStreams,this.maxMessageSize=tt.maxMessageSize??defaultValues.maxMessageSize,this.maxObservedAddresses=tt.maxObservedAddresses??defaultValues.maxObservedAddresses,this.runOnLimitedConnection=tt.runOnLimitedConnection??defaultValues.runOnLimitedConnection,this.host={protocolVersion:`${tt.protocolPrefix??defaultValues.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,agentVersion:getAgentVersion(o.nodeInfo,tt.agentVersion)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:fromString$h(this.host.agentVersion),ProtocolVersion:fromString$h(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,o=>{this.handleProtocol(o).catch(tt=>{this.log.error(tt)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}var Netmask_1;(function(){var et,o,tt,rt,nt,ot,it,st;st=function(at){var ct,lt,dt,ht;return ct=(at&255<<24)>>>24,lt=(at&255<<16)>>>16,dt=(at&65280)>>>8,ht=at&255,[ct,lt,dt,ht].join(".")},it=function(at){var ct,lt,dt,ht,mt,ft;for(ct=[],dt=ht=0;ht<=3&&at.length!==0;dt=++ht){if(dt>0){if(at[0]!==".")throw new Error("Invalid IP");at=at.substring(1)}ft=o(at),mt=ft[0],lt=ft[1],at=at.substring(lt),ct.push(mt)}if(at.length!==0)throw new Error("Invalid IP");switch(ct.length){case 1:if(ct[0]>4294967295)throw new Error("Invalid IP");return ct[0]>>>0;case 2:if(ct[0]>255||ct[1]>16777215)throw new Error("Invalid IP");return(ct[0]<<24|ct[1])>>>0;case 3:if(ct[0]>255||ct[1]>255||ct[2]>65535)throw new Error("Invalid IP");return(ct[0]<<24|ct[1]<<16|ct[2])>>>0;case 4:if(ct[0]>255||ct[1]>255||ct[2]>255||ct[3]>255)throw new Error("Invalid IP");return(ct[0]<<24|ct[1]<<16|ct[2]<<8|ct[3])>>>0;default:throw new Error("Invalid IP")}},tt=function(at){return at.charCodeAt(0)},rt=tt("0"),ot=tt("a"),nt=tt("A"),o=function(at){var ct,lt,dt,ht,mt;for(ht=0,ct=10,lt="9",dt=0,at.length>1&&at[dt]==="0"&&(at[dt+1]==="x"||at[dt+1]==="X"?(dt+=2,ct=16):"0"<=at[dt+1]&&at[dt+1]<="9"&&(dt++,ct=8,lt="7")),mt=dt;dt>>0;else if(ct===16)if("a"<=at[dt]&&at[dt]<="f")ht=ht*ct+(10+tt(at[dt])-ot)>>>0;else if("A"<=at[dt]&&at[dt]<="F")ht=ht*ct+(10+tt(at[dt])-nt)>>>0;else break;else break;if(ht>4294967295)throw new Error("too large");dt++}if(dt===mt)throw new Error("empty octet");return[ht,dt]},et=function(){function at(ct,lt){var dt,ht,mt;if(typeof ct!="string")throw new Error("Missing `net' parameter");if(lt||(mt=ct.split("/",2),ct=mt[0],lt=mt[1]),lt||(lt=32),typeof lt=="string"&<.indexOf(".")>-1){try{this.maskLong=it(lt)}catch{throw new Error("Invalid mask: "+lt)}for(dt=ht=32;ht>=0;dt=--ht)if(this.maskLong===4294967295<<32-dt>>>0){this.bitmask=dt;break}}else if(lt||lt===0)this.bitmask=parseInt(lt,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(it(ct)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+ct)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+lt);this.size=Math.pow(2,32-this.bitmask),this.base=st(this.netLong),this.mask=st(this.maskLong),this.hostmask=st(~this.maskLong),this.first=this.bitmask<=30?st(this.netLong+1):this.base,this.last=this.bitmask<=30?st(this.netLong+this.size-2):st(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?st(this.netLong+this.size-1):void 0}return at.prototype.contains=function(ct){return typeof ct=="string"&&(ct.indexOf("/")>0||ct.split(".").length!==4)&&(ct=new at(ct)),ct instanceof at?this.contains(ct.base)&&this.contains(ct.broadcast||ct.last):(it(ct)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},at.prototype.next=function(ct){return ct==null&&(ct=1),new at(st(this.netLong+this.size*ct),this.mask)},at.prototype.forEach=function(ct){var lt,dt,ht;for(ht=it(this.first),dt=it(this.last),lt=0;ht<=dt;)ct(st(ht),ht,lt),lt++,ht++},at.prototype.toString=function(){return this.base+"/"+this.bitmask},at}(),Netmask_1=et}).call(commonjsGlobal);const PRIVATE_IP_RANGES=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],NETMASK_RANGES=PRIVATE_IP_RANGES.map(et=>new Netmask_1(et));function ipv4Check(et){for(const o of NETMASK_RANGES)if(o.contains(et))return!0;return!1}function isIpv4MappedIpv6(et){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(et)}function ipv4MappedIpv6Check(et){const o=et.split(":");if(o.length<2)return!1;const tt=o[o.length-1].padStart(4,"0"),rt=o[o.length-2].padStart(4,"0"),nt=`${parseInt(rt.substring(0,2),16)}.${parseInt(rt.substring(2),16)}.${parseInt(tt.substring(0,2),16)}.${parseInt(tt.substring(2),16)}`;return ipv4Check(nt)}function isIpv4EmbeddedIpv6(et){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(et)}function ipv4EmbeddedIpv6Check(et){const o=et.split(":"),tt=o[o.length-1];return ipv4Check(tt)}function ipv6Check(et){return/^::$/.test(et)||/^::1$/.test(et)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(et)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(et)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(et)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(et)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(et)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(et)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(et)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(et)||/^ff([0-9a-fA-F]{2,2}):/i.test(et)}function isPrivateIp(et){return isIPv4(et)?ipv4Check(et):isIpv4MappedIpv6(et)?ipv4MappedIpv6Check(et):isIpv4EmbeddedIpv6(et)?ipv4EmbeddedIpv6Check(et):isIPv6(et)?ipv6Check(et):void 0}function coerce$d(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function base$c(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$d=base$c,_brrp__multiformats_scope_baseX$c=src$d;let Encoder$d=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$d=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$d(this,o)}},ComposedDecoder$c=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$d(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$d(et,o){return new ComposedDecoder$c({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$c=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$d(o,tt,rt),this.decoder=new Decoder$d(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$d({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$c(et,o,tt,rt)}function baseX$c({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$c(tt,et);return from$d({prefix:o,name:et,encode:rt,decode:ot=>coerce$d(nt(ot))})}function decode$v(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$r(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<et.toString().split("/").slice(1),func=et=>({match:o=>o.length<1?!1:et(o[0])?o.slice(1):!1,pattern:"fn"}),literal=et=>({match:o=>func(tt=>tt===et).match(o),pattern:et}),string$c=()=>({match:et=>func(o=>typeof o=="string").match(et),pattern:"{string}"}),number$1=()=>({match:et=>func(o=>!isNaN(parseInt(o))).match(et),pattern:"{number}"}),peerId=()=>({match:et=>{if(et.length<2||et[0]!=="p2p"&&et[0]!=="ipfs")return!1;if(et[1].startsWith("Q")||et[1].startsWith("1"))try{base58btc$c.decode(`z${et[1]}`)}catch{return!1}else return!1;return et.slice(2)},pattern:"/p2p/{peerid}"}),certhash=()=>({match:et=>{if(et.length<2||et[0]!=="certhash")return!1;try{base64url$9.decode(et[1])}catch{return!1}return et.slice(2)},pattern:"/certhash/{certhash}"}),optional=et=>({match:o=>{const tt=et.match(o);return tt===!1?o:tt},pattern:`optional(${et.pattern})`}),or$c=(...et)=>({match:o=>{let tt;for(const rt of et){const nt=rt.match(o);nt!==!1&&(tt==null||nt.lengtho.pattern).join(", ")})`}),and=(...et)=>({match:o=>{for(const tt of et){const rt=tt.match(o);if(rt===!1)return!1;o=rt}return o},pattern:`and(${et.map(o=>o.pattern).join(", ")})`});function fmt(...et){function o(nt){let ot=toParts(nt);for(const it of et){const st=it.match(ot);if(st===!1)return!1;ot=st}return ot}function tt(nt){return o(nt)!==!1}function rt(nt){const ot=o(nt);return ot===!1?!1:ot.length===0}return{matchers:et,matches:tt,exactMatch:rt}}const _DNS4=and(literal("dns4"),string$c()),_DNS6=and(literal("dns6"),string$c()),_DNSADDR=and(literal("dnsaddr"),string$c()),_DNS=and(literal("dns"),string$c());fmt(_DNS4,optional(peerId()));fmt(_DNS6,optional(peerId()));fmt(_DNSADDR,optional(peerId()));fmt(or$c(_DNS,_DNSADDR,_DNS4,_DNS6),optional(peerId()));const _IP4=and(literal("ip4"),func(isIPv4)),_IP6=and(literal("ip6"),func(isIPv6)),_IP=or$c(_IP4,_IP6),_IP_OR_DOMAIN=or$c(_IP,_DNS,_DNS4,_DNS6,_DNSADDR),IP_OR_DOMAIN=fmt(or$c(_IP,and(or$c(_DNS,_DNSADDR,_DNS4,_DNS6),optional(peerId())))),_TCP=and(_IP_OR_DOMAIN,literal("tcp"),number$1()),_UDP=and(_IP_OR_DOMAIN,literal("udp"),number$1()),TCP=fmt(and(_TCP,optional(peerId()))),_QUIC=and(_UDP,literal("quic")),_QUICV1=and(_UDP,literal("quic-v1")),QUIC_V0_OR_V1=or$c(_QUIC,_QUICV1),_WEB=or$c(_IP_OR_DOMAIN,_TCP,_UDP,_QUIC,_QUICV1),_WebSockets=or$c(and(_WEB,literal("ws"),optional(peerId()))),WebSockets$1=fmt(_WebSockets),_WebSocketsSecure=or$c(and(_WEB,literal("wss"),optional(peerId())),and(_WEB,literal("tls"),literal("ws"),optional(peerId()))),WebSocketsSecure=fmt(_WebSocketsSecure),_WebRTCDirect=and(_UDP,literal("webrtc-direct"),optional(certhash()),optional(certhash()),optional(peerId())),WebRTCDirect=fmt(_WebRTCDirect),_WebTransport=and(_QUICV1,literal("webtransport"),optional(certhash()),optional(certhash()),optional(peerId())),WebTransport=fmt(_WebTransport),_P2P=or$c(_WebSockets,_WebSocketsSecure,and(_TCP,optional(peerId())),and(QUIC_V0_OR_V1,optional(peerId())),and(_IP_OR_DOMAIN,optional(peerId())),_WebRTCDirect,_WebTransport,peerId()),_Circuit=and(_P2P,literal("p2p-circuit"),peerId()),Circuit=fmt(_Circuit),_WebRTC=or$c(and(_P2P,literal("p2p-circuit"),literal("webrtc"),optional(peerId())),and(_P2P,literal("webrtc"),optional(peerId())),literal("webrtc")),WebRTC=fmt(_WebRTC);or$c(and(_IP_OR_DOMAIN,literal("tcp"),number$1(),literal("http"),optional(peerId())),and(_IP_OR_DOMAIN,literal("http"),optional(peerId())));or$c(and(_IP_OR_DOMAIN,literal("tcp"),or$c(and(literal("443"),literal("http")),and(number$1(),literal("https"))),optional(peerId())),and(_IP_OR_DOMAIN,literal("tls"),literal("http"),optional(peerId())),and(_IP_OR_DOMAIN,literal("https"),optional(peerId())));var Rl,Tl;class Identify extends(Tl=AbstractIdentify,Rl=serviceCapabilities$3,Tl){constructor(tt,rt={}){super(tt,{...rt,protocol:`/${rt.protocolPrefix??defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`,log:tt.logger.forComponent("libp2p:identify")});wt(this,Rl,["@libp2p/identify"]);(rt.runOnConnectionOpen??defaultValues.runOnConnectionOpen)&&tt.events.addEventListener("connection:open",nt=>{const ot=nt.detail;this.identify(ot).catch(it=>{it.name!==UnsupportedProtocolError$1.name&&this.log.error("error during identify trigged by connection:open",it)})})}async _identify(tt,rt={}){let nt;if(rt.signal==null){const ot=AbortSignal.timeout(this.timeout);setMaxListeners$4(1/0,ot),rt={...rt,signal:ot}}try{nt=await tt.newStream(this.protocol,{...rt,runOnLimitedConnection:this.runOnLimitedConnection});const it=await pbStream(nt,{maxDataLength:this.maxMessageSize}).pb(Identify$1).read(rt);return await nt.close(rt),it}catch(ot){throw nt==null||nt.abort(ot),ot}}async identify(tt,rt={}){const nt=await this._identify(tt,rt),{publicKey:ot,protocols:it,observedAddr:st}=nt;if(ot==null)throw new InvalidMessageError$2("public key was missing from identify message");const at=publicKeyFromProtobuf(ot),ct=peerIdFromCID(at.toCID());if(!tt.remotePeer.equals(ct))throw new InvalidMessageError$2("identified peer does not match the expected peer");if(this.peerId.equals(ct))throw new InvalidMessageError$2("identified peer is our own peer id?");const lt=getCleanMultiaddr(st);return this.log("identify completed for peer %p and protocols %o",ct,it),lt!=null&&(this.log("our observed address was %a",lt),isPrivateIp(lt==null?void 0:lt.nodeAddress().address)===!0?this.log("our observed address was private"):this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(this.log("storing our observed address"),this.addressManager.addObservedAddr(lt))),consumeIdentifyMessage(this.peerStore,this.events,this.log,tt,nt)}async handleProtocol(tt){const{connection:rt,stream:nt}=tt,ot=AbortSignal.timeout(this.timeout);setMaxListeners$4(1/0,ot);try{const it=await this.peerStore.get(this.peerId),st=this.addressManager.getAddresses().map(dt=>dt.decapsulateCode(getProtocol("p2p").code));let at=it.peerRecordEnvelope;if(st.length>0&&at==null){const dt=new PeerRecord({peerId:this.peerId,multiaddrs:st});at=(await RecordEnvelope.seal(dt,this.privateKey)).marshal().subarray()}let ct=rt.remoteAddr.bytes;IP_OR_DOMAIN.matches(rt.remoteAddr)||(ct=void 0),await pbStream(nt).pb(Identify$1).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:publicKeyToProtobuf(this.privateKey.publicKey),listenAddrs:st.map(dt=>dt.bytes),signedPeerRecord:at,observedAddr:ct,protocols:it.protocols},{signal:ot}),await nt.close({signal:ot})}catch(it){this.log.error("could not respond to identify request",it),nt.abort(it)}}}function identify(et={}){return o=>new Identify(o,et)}class MuxerClosedError extends Error{constructor(o="The muxer is closed"){super(o),this.name="MuxerClosedError"}}wt(MuxerClosedError,"name","MuxerClosedError");var bs;let InvalidMessageError$1=(bs=class extends Error{constructor(o="Invalid message"){super(o),this.name="InvalidMessageError"}},wt(bs,"name","InvalidMessageError"),bs);var xs;let TooManyOutboundProtocolStreamsError$1=(xs=class extends Error{constructor(o="Too many outbound protocol streams"){super(o),this.name="TooManyOutboundProtocolStreamsError"}},wt(xs,"name","TooManyOutboundProtocolStreamsError"),xs);const serviceCapabilities$2=Symbol.for("@libp2p/service-capabilities");function getIterator(et){if(et!=null){if(typeof et[Symbol.iterator]=="function")return et[Symbol.iterator]();if(typeof et[Symbol.asyncIterator]=="function")return et[Symbol.asyncIterator]();if(typeof et.next=="function")return et}throw new Error("argument is not an iterator or iterable")}function isPromise$2(et){return et==null?!1:typeof et.then=="function"&&typeof et.catch=="function"&&typeof et.finally=="function"}function closeSource(et,o){var rt,nt;const tt=(nt=(rt=getIterator(et)).return)==null?void 0:nt.call(rt);isPromise$2(tt)&&tt.catch(ot=>{o.error("could not cause iterator to return",ot)})}const createAbortError=()=>{const et=new Error("Delay aborted");return et.name="AbortError",et},clearMethods=new WeakMap;function createDelay({clearTimeout:et,setTimeout:o}={}){return(tt,{value:rt,signal:nt}={})=>{if(nt!=null&&nt.aborted)return Promise.reject(createAbortError());let ot,it,st;const at=et??clearTimeout,ct=()=>{at(ot),st(createAbortError())},lt=()=>{nt&&nt.removeEventListener("abort",ct)},dt=new Promise((ht,mt)=>{it=()=>{lt(),ht(rt)},st=mt,ot=(o??setTimeout)(it,tt)});return nt&&nt.addEventListener("abort",ct,{once:!0}),clearMethods.set(dt,()=>{at(ot),ot=null,it()}),dt}}const delay=createDelay();class RateLimitError extends Error{constructor(tt="Rate limit exceeded",rt){super(tt);wt(this,"remainingPoints");wt(this,"msBeforeNext");wt(this,"consumedPoints");wt(this,"isFirstInDuration");this.name="RateLimitError",this.remainingPoints=rt.remainingPoints,this.msBeforeNext=rt.msBeforeNext,this.consumedPoints=rt.consumedPoints,this.isFirstInDuration=rt.isFirstInDuration}}class QueueFullError extends Error{constructor(o="The queue was full"){super(o),this.name="QueueFullError"}}wt(QueueFullError,"name","QueueFullError");class RateLimiter{constructor(o={}){wt(this,"memoryStorage");wt(this,"points");wt(this,"duration");wt(this,"blockDuration");wt(this,"execEvenly");wt(this,"execEvenlyMinDelayMs");wt(this,"keyPrefix");this.points=o.points??4,this.duration=o.duration??1,this.blockDuration=o.blockDuration??0,this.execEvenly=o.execEvenly??!1,this.execEvenlyMinDelayMs=o.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=o.keyPrefix??"rlflx",this.memoryStorage=new MemoryStorage}async consume(o,tt=1,rt={}){const nt=this.getKey(o),ot=this._getKeySecDuration(rt);let it=this.memoryStorage.incrby(nt,tt,ot);if(it.remainingPoints=Math.max(this.points-it.consumedPoints,0),it.consumedPoints>this.points)throw this.blockDuration>0&&it.consumedPoints<=this.points+tt&&(it=this.memoryStorage.set(nt,it.consumedPoints,this.blockDuration)),new RateLimitError("Rate limit exceeded",it);if(this.execEvenly&&it.msBeforeNext>0&&!it.isFirstInDuration){let st=Math.ceil(it.msBeforeNext/(it.remainingPoints+2));st=0?rt:this.duration)*1e3;return this.memoryStorage.set(this.getKey(o),tt,rt),{remainingPoints:0,msBeforeNext:nt===0?-1:nt,consumedPoints:tt,isFirstInDuration:!1}}get(o){const tt=this.memoryStorage.get(this.getKey(o));return tt!=null&&(tt.remainingPoints=Math.max(this.points-tt.consumedPoints,0)),tt}delete(o){this.memoryStorage.delete(this.getKey(o))}_getKeySecDuration(o){return(o==null?void 0:o.customDuration)!=null&&o.customDuration>=0?o.customDuration:this.duration}getKey(o){return this.keyPrefix.length>0?`${this.keyPrefix}:${o}`:o}parseKey(o){return o.substring(this.keyPrefix.length)}}class MemoryStorage{constructor(){wt(this,"storage");this.storage=new Map}incrby(o,tt,rt){const nt=this.storage.get(o);if(nt!=null){const ot=nt.expiresAt!=null?nt.expiresAt.getTime()-new Date().getTime():-1;return nt.expiresAt==null||ot>0?(nt.value+=tt,{remainingPoints:0,msBeforeNext:ot,consumedPoints:nt.value,isFirstInDuration:!1}):this.set(o,tt,rt)}return this.set(o,tt,rt)}set(o,tt,rt){const nt=rt*1e3,ot=this.storage.get(o);ot!=null&&clearTimeout(ot.timeoutId);const it={value:tt,expiresAt:nt>0?new Date(Date.now()+nt):void 0};return this.storage.set(o,it),nt>0&&(it.timeoutId=setTimeout(()=>{this.storage.delete(o)},nt),it.timeoutId.unref!=null&&it.timeoutId.unref()),{remainingPoints:0,msBeforeNext:nt===0?-1:nt,consumedPoints:it.value,isFirstInDuration:!0}}get(o){const tt=this.storage.get(o);if(tt!=null)return{remainingPoints:0,msBeforeNext:tt.expiresAt!=null?tt.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:tt.value,isFirstInDuration:!1}}delete(o){const tt=this.storage.get(o);return tt!=null?(tt.timeoutId!=null&&clearTimeout(tt.timeoutId),this.storage.delete(o),!0):!1}}function allocUnsafe$7(et=0){return new Uint8Array(et)}function coerce$c(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$g(et){return new TextEncoder().encode(et)}function toString$j(et){return new TextDecoder().decode(et)}function base$b(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$c=base$b,_brrp__multiformats_scope_baseX$b=src$c;let Encoder$c=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$c=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$b(this,o)}},ComposedDecoder$b=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$b(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$b(et,o){return new ComposedDecoder$b({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$b=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$c(o,tt,rt),this.decoder=new Decoder$c(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$c({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$b(et,o,tt,rt)}function baseX$b({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$b(tt,et);return from$c({prefix:o,name:et,encode:rt,decode:ot=>coerce$c(nt(ot))})}function decode$u(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$q(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$8=alphabet$8.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$p(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$8[tt],o),"")}function decode$t(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$8[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$g=from$c({prefix:"🚀",name:"base256emoji",encode:encode$p,decode:decode$t}),base256emoji$h=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$g},Symbol.toStringTag,{value:"Module"})),base32$k=rfc4648$a({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$8=rfc4648$a({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$8=rfc4648$a({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$8=rfc4648$a({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$8=rfc4648$a({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$8=rfc4648$a({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$8=rfc4648$a({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$8=rfc4648$a({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$8=rfc4648$a({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$l=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$k,base32hex:base32hex$8,base32hexpad:base32hexpad$8,base32hexpadupper:base32hexpadupper$8,base32hexupper:base32hexupper$8,base32pad:base32pad$8,base32padupper:base32padupper$8,base32upper:base32upper$8,base32z:base32z$8},Symbol.toStringTag,{value:"Module"})),base36$h=baseX$b({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$8=baseX$b({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$i=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$h,base36upper:base36upper$8},Symbol.toStringTag,{value:"Module"})),base58btc$b=baseX$b({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$8=baseX$b({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$8=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$b,base58flickr:base58flickr$8},Symbol.toStringTag,{value:"Module"})),base64$j=rfc4648$a({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$8=rfc4648$a({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$8=rfc4648$a({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$8=rfc4648$a({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$k=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$j,base64pad:base64pad$8,base64url:base64url$8,base64urlpad:base64urlpad$8},Symbol.toStringTag,{value:"Module"})),base8$g=rfc4648$a({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$h=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$g},Symbol.toStringTag,{value:"Module"})),identity$8=from$c({prefix:"\0",name:"identity",encode:et=>toString$j(et),decode:et=>fromString$g(et)}),identityBase$8=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$8},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$8={...identityBase$8,...base2$h,...base8$h,...base10$h,...base16$h,...base32$l,...base36$i,...base58$8,...base64$k,...base256emoji$h};function createCodec$8(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$b=createCodec$8("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$8=createCodec$8("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$7(et.length);for(let tt=0;ttthis._maxUnprocessedMessageQueueSize)throw new InvalidMessageError$1("Unprocessed message queue size too large!");const tt=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(ct){if(ct.name==="InvalidMessageError")throw ct;break}const{id:rt,type:nt,length:ot,offset:it}=this._headerInfo;if(this._buffer.length-itthis._maxMessageSize)throw new InvalidMessageError$1("Message size too large");return{id:tt>>3,type:it,offset:rt+ot,length:nt}}};const MSB$3=128,REST$3=127;function readVarInt(et,o=0){let tt=0,rt=0,nt=o,ot;const it=et.length;do{if(nt>=it||rt>49)throw o=0,new RangeError("Could not decode varint");ot=et.get(nt++),tt+=rt<28?(ot&REST$3)<=MSB$3);return o=nt-o,{value:tt,offset:o}}const POOL_SIZE=10*1024;let Encoder$b=class{constructor(){wt(this,"_pool");wt(this,"_poolOffset");this._pool=allocUnsafe$7(POOL_SIZE),this._poolOffset=0}write(o,tt){const rt=this._pool;let nt=this._poolOffset;encode$P(o.id<<3|o.type,rt,nt),nt+=encodingLength$6(o.id<<3|o.type),(o.type===MessageTypes.NEW_STREAM||o.type===MessageTypes.MESSAGE_INITIATOR||o.type===MessageTypes.MESSAGE_RECEIVER)&&o.data!=null?(encode$P(o.data.length,rt,nt),nt+=encodingLength$6(o.data.length)):(encode$P(0,rt,nt),nt+=encodingLength$6(0));const ot=rt.subarray(this._poolOffset,nt);POOL_SIZE-nt<100?(this._pool=allocUnsafe$7(POOL_SIZE),this._poolOffset=0):this._poolOffset=nt,tt.append(ot),(o.type===MessageTypes.NEW_STREAM||o.type===MessageTypes.MESSAGE_INITIATOR||o.type===MessageTypes.MESSAGE_RECEIVER)&&o.data!=null&&tt.append(o.data)}};const encoder$1=new Encoder$b;async function*encode$o(et){for await(const o of et){const tt=new Uint8ArrayList;encoder$1.write(o,tt),yield tt}}class StreamInputBufferError extends Error{constructor(o="Stream input buffer error"){super(o),this.name="StreamInputBufferError"}}var vs;let AbortError$6=(vs=class extends Error{constructor(o="The operation was aborted"){super(o),this.name="AbortError"}},wt(vs,"name","AbortError"),vs);class StreamResetError extends Error{constructor(o="The stream has been reset"){super(o),this.name="StreamResetError"}}wt(StreamResetError,"name","StreamResetError");class StreamStateError extends Error{constructor(o="The stream is in an invalid state"){super(o),this.name="StreamStateError"}}wt(StreamStateError,"name","StreamStateError");function setMaxListeners$3(){}const setMaxListeners$2=(et,...o)=>{try{[...o]}catch{}};var Jr,Il;let TypedEventEmitter$1=(Il=class extends EventTarget{constructor(){super();hr(this,Jr,new Map);setMaxListeners$2(1/0,this)}listenerCount(tt){const rt=Lt(this,Jr).get(tt);return rt==null?0:rt.length}addEventListener(tt,rt,nt){super.addEventListener(tt,rt,nt);let ot=Lt(this,Jr).get(tt);ot==null&&(ot=[],Lt(this,Jr).set(tt,ot)),ot.push({callback:rt,once:(nt!==!0&&nt!==!1&&(nt==null?void 0:nt.once))??!1})}removeEventListener(tt,rt,nt){super.removeEventListener(tt.toString(),rt??null,nt);let ot=Lt(this,Jr).get(tt);ot!=null&&(ot=ot.filter(({callback:it})=>it!==rt),Lt(this,Jr).set(tt,ot))}dispatchEvent(tt){const rt=super.dispatchEvent(tt);let nt=Lt(this,Jr).get(tt.type);return nt==null||(nt=nt.filter(({once:ot})=>!ot),Lt(this,Jr).set(tt.type,nt)),rt}safeDispatchEvent(tt,rt={}){return this.dispatchEvent(new CustomEvent(tt,rt))}},Jr=new WeakMap,Il);const DEFAULT_SEND_CLOSE_WRITE_TIMEOUT=5e3;function isPromise$1(et){return et==null?!1:typeof et.then=="function"&&typeof et.catch=="function"&&typeof et.finally=="function"}class AbstractStream{constructor(o){wt(this,"id");wt(this,"direction");wt(this,"timeline");wt(this,"protocol");wt(this,"metadata");wt(this,"source");wt(this,"status");wt(this,"readStatus");wt(this,"writeStatus");wt(this,"log");wt(this,"sinkController");wt(this,"sinkEnd");wt(this,"closed");wt(this,"endErr");wt(this,"streamSource");wt(this,"onEnd");wt(this,"onCloseRead");wt(this,"onCloseWrite");wt(this,"onReset");wt(this,"onAbort");wt(this,"sendCloseWriteTimeout");wt(this,"sendingData");this.sinkController=new AbortController,this.sinkEnd=pDefer(),this.closed=pDefer(),this.log=o.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=o.id,this.metadata=o.metadata??{},this.direction=o.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=o.sendCloseWriteTimeout??DEFAULT_SEND_CLOSE_WRITE_TIMEOUT,this.onEnd=o.onEnd,this.onCloseRead=o==null?void 0:o.onCloseRead,this.onCloseWrite=o==null?void 0:o.onCloseWrite,this.onReset=o==null?void 0:o.onReset,this.onAbort=o==null?void 0:o.onAbort,this.source=this.streamSource=pushable({onEnd:tt=>{tt!=null?this.log.trace("source ended with error",tt):this.log.trace("source ended"),this.onSourceEnd(tt)}}),this.sink=this.sink.bind(this)}async sink(o){if(this.writeStatus!=="ready")throw new StreamStateError(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const tt={signal:this.sinkController.signal};if(this.direction==="outbound"){const nt=this.sendNewStream(tt);isPromise$1(nt)&&await nt}const rt=()=>{closeSource(o,this.log)};try{this.sinkController.signal.addEventListener("abort",rt),this.log.trace("sink reading from source");for await(let nt of o){nt=nt instanceof Uint8Array?new Uint8ArrayList(nt):nt;const ot=this.sendData(nt,tt);isPromise$1(ot)&&(this.sendingData=pDefer(),await ot,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",rt)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(tt){throw this.log.trace("sink ended with error, calling abort with error",tt),this.abort(tt),tt}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(o){var tt;this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",o!=null&&this.endErr==null&&(this.endErr=o),(tt=this.onCloseRead)==null||tt.call(this),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(o){var tt;this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",o!=null&&this.endErr==null&&(this.endErr=o),(tt=this.onCloseWrite)==null||tt.call(this),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(o){this.log.trace("closing gracefully"),this.status="closing",await raceSignal(Promise.all([this.closeWrite(o),this.closeRead(o),this.closed.promise]),o==null?void 0:o.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(o={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const tt=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(o)),tt==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(o={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await raceSignal(this.sink([]),o.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await raceSignal(this.sendingData.promise,o.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await raceSignal(this.sinkEnd.promise,o.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(o){var rt;if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",o),this.log("try to send reset to remote");const tt=this.sendReset();isPromise$1(tt)&&tt.catch(nt=>{this.log.error("error sending reset message",nt)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(o),(rt=this.onAbort)==null||rt.call(this,o)}reset(){var tt;if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;const o=new StreamResetError("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(o),(tt=this.onReset)==null||tt.call(this)}_closeSinkAndSource(o){this._closeSink(o),this._closeSource(o)}_closeSink(o){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(o)}_closeSource(o){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(o))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(o){this.streamSource.push(o)}sourceReadableLength(){return this.streamSource.readableLength}}class MplexStream extends AbstractStream{constructor(tt){super(tt);wt(this,"name");wt(this,"streamId");wt(this,"send");wt(this,"types");wt(this,"maxDataSize");this.types=tt.direction==="outbound"?InitiatorMessageTypes:ReceiverMessageTypes,this.send=tt.send,this.name=tt.name,this.streamId=tt.streamId,this.maxDataSize=tt.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:InitiatorMessageTypes.NEW_STREAM,data:new Uint8ArrayList(fromString$f(this.name))})}async sendData(tt){for(tt=tt.sublist();tt.byteLength>0;){const rt=Math.min(tt.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:tt.sublist(0,rt)}),tt.consume(rt)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function createStream(et){const{id:o,name:tt,send:rt,onEnd:nt,type:ot="initiator",maxMsgSize:it=MAX_MSG_SIZE}=et;return new MplexStream({id:ot==="initiator"?`i${o}`:`r${o}`,streamId:o,name:`${tt??o}`,direction:ot==="initiator"?"outbound":"inbound",maxDataSize:it,onEnd:nt,send:rt,log:et.logger.forComponent(`libp2p:mplex:stream:${ot}:${o}`)})}const MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION=1024,MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION=1024,MAX_STREAM_BUFFER_SIZE=1024*1024*4,DISCONNECT_THRESHOLD=5,CLOSE_TIMEOUT$2=500;function printMessage(et){const o={...et,type:`${MessageTypeNames[et.type]} (${et.type})`};return et.type===MessageTypes.NEW_STREAM&&(o.data=toString$i(et.data instanceof Uint8Array?et.data:et.data.subarray())),(et.type===MessageTypes.MESSAGE_INITIATOR||et.type===MessageTypes.MESSAGE_RECEIVER)&&(o.data=toString$i(et.data instanceof Uint8Array?et.data:et.data.subarray(),"base16")),o}class MplexStreamMuxer{constructor(o,tt){wt(this,"protocol","/mplex/6.7.0");wt(this,"sink");wt(this,"source");wt(this,"log");wt(this,"_streamId");wt(this,"_streams");wt(this,"_init");wt(this,"_source");wt(this,"closeController");wt(this,"rateLimiter");wt(this,"closeTimeout");wt(this,"logger");tt=tt??{},this.log=o.logger.forComponent("libp2p:mplex"),this.logger=o.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=tt,this.closeTimeout=tt.closeTimeout??CLOSE_TIMEOUT$2,this.sink=this._createSink(),this._source=pushable({objectMode:!0,onEnd:()=>{for(const rt of this._streams.initiators.values())rt.destroy();for(const rt of this._streams.receivers.values())rt.destroy()}}),this.source=pipe(this._source,rt=>encode$o(rt)),this.closeController=new AbortController,this.rateLimiter=new RateLimiter({points:tt.disconnectThreshold??DISCONNECT_THRESHOLD,duration:1})}get streams(){const o=[];for(const tt of this._streams.initiators.values())o.push(tt);for(const tt of this._streams.receivers.values())o.push(tt);return o}newStream(o){if(this.closeController.signal.aborted)throw new MuxerClosedError("Muxer already closed");const tt=this._streamId++;o=o==null?tt.toString():o.toString();const rt=this._streams.initiators;return this._newStream({id:tt,name:o,type:"initiator",registry:rt})}async close(o){if(this.closeController.signal.aborted)return;const tt=(o==null?void 0:o.signal)??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async rt=>rt.close({signal:tt}))),this._source.end(),await this._source.onEmpty({signal:tt}),this.closeController.abort()}catch(rt){this.abort(rt)}}abort(o){this.closeController.signal.aborted||(this.streams.forEach(tt=>{tt.abort(o)}),this.closeController.abort(o))}_newReceiverStream(o){const{id:tt,name:rt}=o,nt=this._streams.receivers;return this._newStream({id:tt,name:rt,type:"receiver",registry:nt})}_newStream(o){const{id:tt,name:rt,type:nt,registry:ot}=o;if(this.log("new %s stream %s",nt,tt),nt==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION))throw new TooManyOutboundProtocolStreamsError$1("Too many outbound streams open");if(ot.has(tt))throw new Error(`${nt} stream ${tt} already exists!`);const at=createStream({id:tt,name:rt,send:async ct=>{this.log.enabled&&this.log.trace("%s stream %s send",nt,tt,printMessage(ct)),this._source.push(ct)},type:nt,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",nt,tt,at.protocol),ot.delete(tt),this._init.onStreamEnd!=null&&this._init.onStreamEnd(at)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return ot.set(tt,at),at}_createSink(){return async tt=>{const rt=()=>{closeSource(tt,this.log)};this.closeController.signal.addEventListener("abort",rt);try{const nt=new Decoder$b(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const ot of tt)for(const it of nt.write(ot))await this._handleIncoming(it);this._source.end()}catch(nt){this.log("error in sink",nt),this._source.end(nt)}finally{this.closeController.signal.removeEventListener("abort",rt)}}}async _handleIncoming(o){const{id:tt,type:rt}=o;if(this.log.enabled&&this.log.trace("incoming message",printMessage(o)),o.type===MessageTypes.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)){this.log("too many inbound streams open"),this._source.push({id:tt,type:MessageTypes.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}const st=this._newReceiverStream({id:tt,name:toString$i(o.data instanceof Uint8Array?o.data:o.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(st);return}const ot=((rt&1)===1?this._streams.initiators:this._streams.receivers).get(tt);if(ot==null){this.log("missing stream %s for message type %s",tt,MessageTypeNames[rt]);try{await this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}const it=this._init.maxStreamBufferSize??MAX_STREAM_BUFFER_SIZE;try{switch(rt){case MessageTypes.MESSAGE_INITIATOR:case MessageTypes.MESSAGE_RECEIVER:if(ot.sourceReadableLength()>it)throw this._source.push({id:o.id,type:rt===MessageTypes.MESSAGE_INITIATOR?MessageTypes.RESET_RECEIVER:MessageTypes.RESET_INITIATOR}),new StreamInputBufferError("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");ot.sourcePush(o.data);break;case MessageTypes.CLOSE_INITIATOR:case MessageTypes.CLOSE_RECEIVER:ot.remoteCloseWrite();break;case MessageTypes.RESET_INITIATOR:case MessageTypes.RESET_RECEIVER:ot.reset();break;default:this.log("unknown message type %s",rt)}}catch(st){this.log.error("error while processing message",st),ot.abort(st)}}}var Pl,Nl;Nl=Symbol.toStringTag,Pl=serviceCapabilities$2;class Mplex{constructor(o,tt={}){wt(this,"protocol","/mplex/6.7.0");wt(this,"_init");wt(this,"components");wt(this,Nl,"@libp2p/mplex");wt(this,Pl,["@libp2p/stream-multiplexing"]);this.components=o,this._init=tt}createStreamMuxer(o={}){return new MplexStreamMuxer(this.components,{...o,...this._init})}}function mplex(et={}){return o=>new Mplex(o,et)}function isAsyncIterable$3(et){return et[Symbol.asyncIterator]!=null}function first(et){if(isAsyncIterable$3(et))return(async()=>{for await(const o of et)return o})();for(const o of et)return o}function equals$4(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;tt{tt==null||tt.abort(new TimeoutError$3("ping timeout"))}),pipe(tt,async function*(ot){let it=0;for await(const st of ot){if(it+=st.byteLength,it>PING_LENGTH$1){tt==null||tt.abort(new InvalidMessageError$3("Too much data received"));return}yield st}},tt).catch(ot=>{this.log.error("incoming ping from %p failed with error",o.connection.remotePeer,ot),tt==null||tt.abort(ot)}).finally(()=>{const ot=Date.now()-rt;this.log("incoming ping from %p complete in %dms",o.connection.remotePeer,ot)})}async ping(o,tt={}){var at,ct;this.log("pinging %p",o);const rt=Date.now(),nt=randomBytes(PING_LENGTH$1),ot=await this.components.connectionManager.openConnection(o,tt);let it,st=()=>{};if(tt.signal==null){const lt=AbortSignal.timeout(this.timeout);tt={...tt,signal:lt}}try{it=await ot.newStream(this.protocol,{...tt,runOnLimitedConnection:this.runOnLimitedConnection}),st=()=>{it==null||it.abort(new AbortError$9)},(at=tt.signal)==null||at.addEventListener("abort",st,{once:!0});const lt=await pipe([nt],it,async ht=>first(ht)),dt=Date.now()-rt;if(lt==null)throw new ProtocolError(`Did not receive a ping ack after ${dt}ms`);if(!equals$4(nt,lt.subarray()))throw new ProtocolError(`Received wrong ping ack after ${dt}ms`);return this.log("ping %p complete in %dms",ot.remotePeer,dt),dt}catch(lt){throw this.log.error("error while pinging %p",ot.remotePeer,lt),it==null||it.abort(lt),lt}finally{(ct=tt.signal)==null||ct.removeEventListener("abort",st),it!=null&&await it.close()}}}function ping(et={}){return o=>new PingService(o,et)}const transportSymbol=Symbol.for("@libp2p/transport");var FaultTolerance$1;(function(et){et[et.FATAL_ALL=0]="FATAL_ALL",et[et.NO_FATAL=1]="NO_FATAL"})(FaultTolerance$1||(FaultTolerance$1={}));var ws;let AbortError$5=(ws=class extends Error{constructor(o="The operation was aborted"){super(o),this.name="AbortError"}},wt(ws,"name","AbortError"),ws);class ConnectionFailedError extends Error{constructor(o="Connection failed"){super(o),this.name="ConnectionFailedError"}}wt(ConnectionFailedError,"name","ConnectionFailedError");const serviceCapabilities$1=Symbol.for("@libp2p/service-capabilities"),ASSUME_HTTP_CODES=[getProtocol("tcp").code,getProtocol("dns").code,getProtocol("dnsaddr").code,getProtocol("dns4").code,getProtocol("dns6").code];function extractSNI(et){let o;try{o=getProtocol("sni").code}catch{return null}for(const[tt,rt]of et)if(tt===o&&rt!==void 0)return rt;return null}function hasTLS(et){return et.some(([o,tt])=>o===getProtocol("tls").code)}function interpretNext(et,o,tt){const rt=interpreters[getProtocol(et).name];if(rt===void 0)throw new Error(`Can't interpret protocol ${getProtocol(et).name}`);const nt=rt(o,tt);return et===getProtocol("ip6").code?`[${nt}]`:nt}const interpreters={ip4:(et,o)=>et,ip6:(et,o)=>o.length===0?et:`[${et}]`,tcp:(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${interpretNext(tt[0],tt[1]??"",o)}:${et}`},udp:(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${interpretNext(tt[0],tt[1]??"",o)}:${et}`},dnsaddr:(et,o)=>et,dns4:(et,o)=>et,dns6:(et,o)=>et,dns:(et,o)=>et,ipfs:(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(tt[0],tt[1]??"",o)}/ipfs/${et}`},p2p:(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(tt[0],tt[1]??"",o)}/p2p/${et}`},http:(et,o)=>{const tt=hasTLS(o),rt=extractSNI(o);if(tt&&rt!==null)return`https://${rt}`;const nt=tt?"https://":"http://",ot=o.pop();if(ot===void 0)throw new Error("Unexpected end of multiaddr");let it=interpretNext(ot[0],ot[1]??"",o);return it=it.replace("tcp://",""),`${nt}${it}`},"http-path":(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");const rt=interpretNext(tt[0],tt[1]??"",o),nt=decodeURIComponent(et);return`${rt}/${nt}`},tls:(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");return interpretNext(tt[0],tt[1]??"",o)},sni:(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");return interpretNext(tt[0],tt[1]??"",o)},https:(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");let rt=interpretNext(tt[0],tt[1]??"",o);return rt=rt.replace("tcp://",""),`https://${rt}`},ws:(et,o)=>{const tt=hasTLS(o),rt=extractSNI(o);if(tt&&rt!==null)return`wss://${rt}`;const nt=tt?"wss://":"ws://",ot=o.pop();if(ot===void 0)throw new Error("Unexpected end of multiaddr");let it=interpretNext(ot[0],ot[1]??"",o);return it=it.replace("tcp://",""),`${nt}${it}`},wss:(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");let rt=interpretNext(tt[0],tt[1]??"",o);return rt=rt.replace("tcp://",""),`wss://${rt}`},"p2p-websocket-star":(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(tt[0],tt[1]??"",o)}/p2p-websocket-star`},"p2p-webrtc-star":(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(tt[0],tt[1]??"",o)}/p2p-webrtc-star`},"p2p-webrtc-direct":(et,o)=>{const tt=o.pop();if(tt===void 0)throw new Error("Unexpected end of multiaddr");return`${interpretNext(tt[0],tt[1]??"",o)}/p2p-webrtc-direct`}};function multiaddrToUri(et,o){const rt=multiaddr(et).stringTuples(),nt=rt.pop();if(nt===void 0)throw new Error("Unexpected end of multiaddr");const ot=getProtocol(nt[0]),it=interpreters[ot.name];if(it==null)throw new Error(`No interpreter found for ${ot.name}`);let st=it(nt[1]??"",rt);return ASSUME_HTTP_CODES.includes(nt[0])&&(st=st.replace(/^.*:\/\//,""),nt[1]==="443"?st=`https://${st}`:st=`http://${st}`),(st.startsWith("http://")||st.startsWith("https://"))&&(st=new URL(st).toString(),st.endsWith("/")&&(st=st.substring(0,st.length-1))),st}const ready=async et=>{if(et.readyState>=2)throw new Error("socket closed");et.readyState!==1&&await new Promise((o,tt)=>{function rt(){et.removeEventListener("open",nt),et.removeEventListener("error",ot)}function nt(){rt(),o()}function ot(it){rt(),tt(it.error??new Error(`connect ECONNREFUSED ${et.url}`))}et.addEventListener("open",nt),et.addEventListener("error",ot)})},sink=(et,o)=>(o=o??{},o.closeOnEnd=o.closeOnEnd!==!1,async rt=>{for await(const nt of rt){try{await ready(et)}catch(ot){if(ot.message==="socket closed")break;throw ot}if(et.readyState===et.CLOSING||et.readyState===et.CLOSED)break;et.send(nt)}o.closeOnEnd!=null&&et.readyState<=1&&await new Promise((nt,ot)=>{et.addEventListener("close",it=>{if(it.wasClean||it.code===1006)nt();else{const st=Object.assign(new Error("ws error"),{event:it});ot(st)}}),setTimeout(()=>{et.close()})})});var dom={},eventIterator={};Object.defineProperty(eventIterator,"__esModule",{value:!0});class EventQueue{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(o){if(this.isStopped)return;const tt={value:o,done:!1};if(this.pullQueue.length){const rt=this.pullQueue.shift();rt&&rt.resolve(tt)}else this.pushQueue.push(Promise.resolve(tt)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const o of this.pullQueue)o.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(o){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const tt of this.pullQueue)tt.reject(o);this.pullQueue.length=0}else{const tt=Promise.reject(o);tt.catch(()=>{}),this.pushQueue.push(tt)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:o=>{const tt=this.pushQueue.shift();return tt?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),tt):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((rt,nt)=>{this.pullQueue.push({resolve:rt,reject:nt})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}let EventIterator$1=class{constructor(o,{highWaterMark:tt=100,lowWaterMark:rt=1}={}){const nt=new EventQueue;nt.highWaterMark=tt,nt.lowWaterMark=rt,nt.removeCallback=o({push:ot=>nt.push(ot),stop:()=>nt.stop(),fail:ot=>nt.fail(ot),on:(ot,it)=>{nt.eventHandlers[ot]=it}})||(()=>{}),this[Symbol.asyncIterator]=()=>nt[Symbol.asyncIterator](),Object.freeze(this)}};eventIterator.EventIterator=EventIterator$1;eventIterator.default=EventIterator$1;Object.defineProperty(dom,"__esModule",{value:!0});const event_iterator_1=eventIterator;var EventIterator=dom.EventIterator=event_iterator_1.EventIterator;function subscribe(et,o,tt){return new event_iterator_1.EventIterator(({push:rt})=>(this.addEventListener(et,rt,o),()=>this.removeEventListener(et,rt,o)),tt)}dom.subscribe=subscribe;dom.default=event_iterator_1.EventIterator;function coerce$b(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$e(et){return new TextEncoder().encode(et)}function toString$h(et){return new TextDecoder().decode(et)}function base$a(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$b=base$a,_brrp__multiformats_scope_baseX$a=src$b;let Encoder$a=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$a=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$a(this,o)}},ComposedDecoder$a=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$a(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$a(et,o){return new ComposedDecoder$a({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$a=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$a(o,tt,rt),this.decoder=new Decoder$a(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$b({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$a(et,o,tt,rt)}function baseX$a({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$a(tt,et);return from$b({prefix:o,name:et,encode:rt,decode:ot=>coerce$b(nt(ot))})}function decode$s(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$n(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$7=alphabet$7.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$m(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$7[tt],o),"")}function decode$r(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$7[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$e=from$b({prefix:"🚀",name:"base256emoji",encode:encode$m,decode:decode$r}),base256emoji$f=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$e},Symbol.toStringTag,{value:"Module"})),base32$i=rfc4648$9({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$7=rfc4648$9({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$7=rfc4648$9({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$7=rfc4648$9({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$7=rfc4648$9({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$7=rfc4648$9({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$7=rfc4648$9({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$7=rfc4648$9({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$7=rfc4648$9({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$j=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$i,base32hex:base32hex$7,base32hexpad:base32hexpad$7,base32hexpadupper:base32hexpadupper$7,base32hexupper:base32hexupper$7,base32pad:base32pad$7,base32padupper:base32padupper$7,base32upper:base32upper$7,base32z:base32z$7},Symbol.toStringTag,{value:"Module"})),base36$f=baseX$a({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$7=baseX$a({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$g=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$f,base36upper:base36upper$7},Symbol.toStringTag,{value:"Module"})),base58btc$a=baseX$a({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$7=baseX$a({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$7=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$a,base58flickr:base58flickr$7},Symbol.toStringTag,{value:"Module"})),base64$h=rfc4648$9({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$7=rfc4648$9({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$7=rfc4648$9({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$7=rfc4648$9({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$i=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$h,base64pad:base64pad$7,base64url:base64url$7,base64urlpad:base64urlpad$7},Symbol.toStringTag,{value:"Module"})),base8$e=rfc4648$9({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$f=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$e},Symbol.toStringTag,{value:"Module"})),identity$7=from$b({prefix:"\0",name:"identity",encode:et=>toString$h(et),decode:et=>fromString$e(et)}),identityBase$7=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$7},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$7={...identityBase$7,...base2$f,...base8$f,...base10$f,...base16$f,...base32$j,...base36$g,...base58$7,...base64$i,...base256emoji$f};function allocUnsafe$6(et=0){return new Uint8Array(et)}function createCodec$7(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$a=createCodec$7("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$7=createCodec$7("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$6(et.length);for(let tt=0;tt{et.binaryType="arraybuffer";const o=async()=>{await new Promise((ot,it)=>{if(rt){ot();return}if(nt!=null){it(nt);return}const st=lt=>{et.removeEventListener("open",at),et.removeEventListener("error",ct),lt()},at=()=>{st(ot)},ct=lt=>{st(()=>{it(lt.error??new Error(`connect ECONNREFUSED ${et.url}`))})};et.addEventListener("open",at),et.addEventListener("error",ct)})},tt=async function*(){const ot=new EventIterator(({push:it,stop:st,fail:at})=>{const ct=dt=>{let ht=null;typeof dt.data=="string"&&(ht=fromString$d(dt.data)),isArrayBuffer(dt.data)&&(ht=new Uint8Array(dt.data)),dt.data instanceof Uint8Array&&(ht=dt.data),ht!=null&&it(ht)},lt=dt=>{at(dt.error??new Error("Socket error"))};return et.addEventListener("message",ct),et.addEventListener("error",lt),et.addEventListener("close",st),()=>{et.removeEventListener("message",ct),et.removeEventListener("error",lt),et.removeEventListener("close",st)}},{highWaterMark:1/0});await o();for await(const it of ot)yield isArrayBuffer(it)?new Uint8Array(it):it}();let rt=et.readyState===1,nt;return et.addEventListener("open",()=>{rt=!0,nt=null}),et.addEventListener("close",()=>{rt=!1,nt=null}),et.addEventListener("error",ot=>{rt||(nt=ot.error??new Error(`connect ECONNREFUSED ${et.url}`))}),Object.assign(tt,{connected:o})},duplex=(et,o)=>{o=o??{};const tt=source(et);let rt=o.remoteAddress,nt=o.remotePort;if(et.url!=null)try{const it=new URL(et.url);rt=it.hostname,nt=parseInt(it.port,10)}catch{}if(rt==null||nt==null)throw new Error("Remote connection did not have address and/or port");return{sink:sink(et,o),source:tt,connected:async()=>{await tt.connected()},close:async()=>{(et.readyState===et.CONNECTING||et.readyState===et.OPEN)&&await new Promise(it=>{et.addEventListener("close",()=>{it()}),et.close()})},destroy:()=>{et.terminate!=null?et.terminate():et.close()},remoteAddress:rt,remotePort:nt,socket:et}},WebSocket$1=WebSocket,map={"http:":"ws:","https:":"wss:"},defaultProtocol="ws:",wsurl=(et,o)=>{if(et.startsWith("//")&&(et=`${(o==null?void 0:o.protocol)??defaultProtocol}${et}`),et.startsWith("/")&&o!=null){const rt=o.protocol??defaultProtocol,nt=o.host,ot=o.port!=null&&(nt==null?void 0:nt.endsWith(`:${o.port}`))!==!0?`:${o.port}`:"";et=`${rt}//${nt}${ot}${et}`}const tt=new URL(et);for(const[rt,nt]of Object.entries(map))tt.protocol===rt&&(tt.protocol=nt);return tt};function connect(et,o){const tt=typeof window>"u"?void 0:window.location;o=o??{};const rt=wsurl(et,tt),nt=new WebSocket$1(rt.toString(),o.websocket);return duplex(nt,o)}class CustomProgressEvent extends Event{constructor(tt,rt){super(tt);wt(this,"type");wt(this,"detail");this.type=tt,this.detail=rt}}const CODE_P2P=421,CODE_CIRCUIT=290,CLOSE_TIMEOUT$1=500;function all$1(et){return et.filter(o=>{if(o.protoCodes().includes(CODE_CIRCUIT))return!1;const tt=o.decapsulateCode(CODE_P2P);return WebSockets$2.matches(tt)||WebSocketsSecure$1.matches(tt)})}function wss(et){return et.filter(o=>{if(o.protoCodes().includes(CODE_CIRCUIT))return!1;const tt=o.decapsulateCode(CODE_P2P);return WebSocketsSecure$1.matches(tt)})}function createListener(){throw new Error("WebSocket Servers can not be created in the browser!")}function socketToMaConn(et,o,tt){const rt=tt.logger.forComponent("libp2p:websockets:maconn"),nt=tt.metrics,ot=tt.metricPrefix??"",it={log:rt,async sink(st){try{await et.sink(async function*(){for await(const at of st)at instanceof Uint8Array?yield at:yield at.subarray()}())}catch(at){at.type!=="aborted"&&rt.error(at)}},source:et.source,remoteAddr:o,timeline:{open:Date.now()},async close(st={}){var lt,dt;const at=Date.now();if(st.signal==null){const ht=AbortSignal.timeout(CLOSE_TIMEOUT$1);st={...st,signal:ht}}const ct=()=>{const{host:ht,port:mt}=it.remoteAddr.toOptions();rt("timeout closing stream to %s:%s after %dms, destroying it manually",ht,mt,Date.now()-at),this.abort(new AbortError$5("Socket close timeout"))};(lt=st.signal)==null||lt.addEventListener("abort",ct);try{await et.close()}catch(ht){rt.error("error closing WebSocket gracefully",ht),this.abort(ht)}finally{(dt=st.signal)==null||dt.removeEventListener("abort",ct),it.timeline.close=Date.now()}},abort(st){const{host:at,port:ct}=it.remoteAddr.toOptions();rt("timeout closing stream to %s:%s due to error",at,ct,st),et.destroy(),it.timeline.close=Date.now(),nt==null||nt.increment({[`${ot}error`]:!0})}};return et.socket.addEventListener("close",()=>{nt==null||nt.increment({[`${ot}close`]:!0}),it.timeline.close==null&&(it.timeline.close=Date.now())},{once:!0}),it}var Ol,Ll,Ml;Ml=transportSymbol,Ll=Symbol.toStringTag,Ol=serviceCapabilities$1;class WebSockets{constructor(o,tt){wt(this,"log");wt(this,"init");wt(this,"logger");wt(this,"metrics");wt(this,"components");wt(this,Ml,!0);wt(this,Ll,"@libp2p/websockets");wt(this,Ol,["@libp2p/transport"]);this.log=o.logger.forComponent("libp2p:websockets"),this.logger=o.logger,this.components=o,this.init=tt,o.metrics!=null&&(this.metrics={dialerEvents:o.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}async dial(o,tt){var it;this.log("dialing %s",o),tt=tt??{};const rt=await this._connect(o,tt),nt=socketToMaConn(rt,o,{logger:this.logger,metrics:(it=this.metrics)==null?void 0:it.dialerEvents});this.log("new outbound connection %s",nt.remoteAddr);const ot=await tt.upgrader.upgradeOutbound(nt,tt);return this.log("outbound connection %s upgraded",nt.remoteAddr),ot}async _connect(o,tt){var it,st,at,ct,lt;(it=tt==null?void 0:tt.signal)==null||it.throwIfAborted();const rt=o.toOptions();this.log("dialing %s:%s",rt.host,rt.port);const nt=pDefer(),ot=connect(multiaddrToUri(o),this.init);ot.socket.addEventListener("error",()=>{var ht;const dt=new ConnectionFailedError(`Could not connect to ${o.toString()}`);this.log.error("connection error:",dt),(ht=this.metrics)==null||ht.dialerEvents.increment({error:!0}),nt.reject(dt)});try{(st=tt.onProgress)==null||st.call(tt,new CustomProgressEvent("websockets:open-connection")),await raceSignal(Promise.race([ot.connected(),nt.promise]),tt.signal)}catch(dt){throw((at=tt.signal)==null?void 0:at.aborted)===!0&&((ct=this.metrics)==null||ct.dialerEvents.increment({abort:!0})),ot.close().catch(ht=>{this.log.error("error closing raw socket",ht)}),dt}return this.log("connected %s",o),(lt=this.metrics)==null||lt.dialerEvents.increment({connect:!0}),ot}createListener(o){return createListener({logger:this.logger,metrics:this.components.metrics},{...this.init,...o})}listenFilter(o){var tt,rt;return o=Array.isArray(o)?o:[o],((tt=this.init)==null?void 0:tt.filter)!=null?(rt=this.init)==null?void 0:rt.filter(o):isBrowser||isWebWorker?wss(o):all$1(o)}dialFilter(o){return this.listenFilter(o)}}function webSockets(et={}){return o=>new WebSockets(o,et)}const connectionSymbol=Symbol.for("@libp2p/connection"),contentRoutingSymbol=Symbol.for("@libp2p/content-routing"),peerDiscoverySymbol=Symbol.for("@libp2p/peer-discovery"),peerIdSymbol$1=Symbol.for("@libp2p/peer-id");function isPeerId$1(et){return!!(et!=null&&et[peerIdSymbol$1])}const peerRoutingSymbol=Symbol.for("@libp2p/peer-routing"),KEEP_ALIVE="keep-alive";var FaultTolerance;(function(et){et[et.FATAL_ALL=0]="FATAL_ALL",et[et.NO_FATAL=1]="NO_FATAL"})(FaultTolerance||(FaultTolerance={}));var Es;let AbortError$4=(Es=class extends Error{constructor(o="The operation was aborted"){super(o),this.name="AbortError"}},wt(Es,"name","AbortError"),Es);var Cs;let InvalidParametersError$1=(Cs=class extends Error{constructor(o="Invalid parameters"){super(o),this.name="InvalidParametersError"}},wt(Cs,"name","InvalidParametersError"),Cs);class ConnectionClosingError extends Error{constructor(o="The connection is closing"){super(o),this.name="ConnectionClosingError"}}wt(ConnectionClosingError,"name","ConnectionClosingError");class ConnectionClosedError extends Error{constructor(o="The connection is closed"){super(o),this.name="ConnectionClosedError"}}wt(ConnectionClosedError,"name","ConnectionClosedError");var Ss;let NotFoundError$1=(Ss=class extends Error{constructor(o="Not found"){super(o),this.name="NotFoundError"}},wt(Ss,"name","NotFoundError"),Ss);class InvalidPeerIdError extends Error{constructor(o="Invalid PeerID"){super(o),this.name="InvalidPeerIdError"}}wt(InvalidPeerIdError,"name","InvalidPeerIdError");class InvalidMultiaddrError extends Error{constructor(o="Invalid multiaddr"){super(o),this.name="InvalidMultiaddrError"}}wt(InvalidMultiaddrError,"name","InvalidMultiaddrError");var As;let TimeoutError$2=(As=class extends Error{constructor(o="Timed out"){super(o),this.name="TimeoutError"}},wt(As,"name","TimeoutError"),As);class NotStartedError extends Error{constructor(o="Not started"){super(o),this.name="NotStartedError"}}wt(NotStartedError,"name","NotStartedError");class DialError extends Error{constructor(o="Dial error"){super(o),this.name="DialError"}}wt(DialError,"name","DialError");class LimitedConnectionError extends Error{constructor(o="Limited connection"){super(o),this.name="LimitedConnectionError"}}wt(LimitedConnectionError,"name","LimitedConnectionError");class TooManyInboundProtocolStreamsError extends Error{constructor(o="Too many inbound protocol streams"){super(o),this.name="TooManyInboundProtocolStreamsError"}}wt(TooManyInboundProtocolStreamsError,"name","TooManyInboundProtocolStreamsError");class TooManyOutboundProtocolStreamsError extends Error{constructor(o="Too many outbound protocol streams"){super(o),this.name="TooManyOutboundProtocolStreamsError"}}wt(TooManyOutboundProtocolStreamsError,"name","TooManyOutboundProtocolStreamsError");function setMaxListeners$1(){}const setMaxListeners=(et,...o)=>{try{[...o]}catch{}};var en;class TypedEventEmitter extends EventTarget{constructor(){super();hr(this,en,new Map);setMaxListeners(1/0,this)}listenerCount(tt){const rt=Lt(this,en).get(tt);return rt==null?0:rt.length}addEventListener(tt,rt,nt){super.addEventListener(tt,rt,nt);let ot=Lt(this,en).get(tt);ot==null&&(ot=[],Lt(this,en).set(tt,ot)),ot.push({callback:rt,once:(nt!==!0&&nt!==!1&&(nt==null?void 0:nt.once))??!1})}removeEventListener(tt,rt,nt){super.removeEventListener(tt.toString(),rt??null,nt);let ot=Lt(this,en).get(tt);ot!=null&&(ot=ot.filter(({callback:it})=>it!==rt),Lt(this,en).set(tt,ot))}dispatchEvent(tt){const rt=super.dispatchEvent(tt);let nt=Lt(this,en).get(tt.type);return nt==null||(nt=nt.filter(({once:ot})=>!ot),Lt(this,en).set(tt.type,nt)),rt}safeDispatchEvent(tt,rt={}){return this.dispatchEvent(new CustomEvent(tt,rt))}}en=new WeakMap;function isStartable(et){return et!=null&&typeof et.start=="function"&&typeof et.stop=="function"}async function start(...et){const o=[];for(const tt of et)isStartable(tt)&&o.push(tt);await Promise.all(o.map(async tt=>{tt.beforeStart!=null&&await tt.beforeStart()})),await Promise.all(o.map(async tt=>{await tt.start()})),await Promise.all(o.map(async tt=>{tt.afterStart!=null&&await tt.afterStart()}))}async function stop(...et){const o=[];for(const tt of et)isStartable(tt)&&o.push(tt);await Promise.all(o.map(async tt=>{tt.beforeStop!=null&&await tt.beforeStop()})),await Promise.all(o.map(async tt=>{await tt.stop()})),await Promise.all(o.map(async tt=>{tt.afterStop!=null&&await tt.afterStop()}))}const serviceCapabilities=Symbol.for("@libp2p/service-capabilities"),serviceDependencies=Symbol.for("@libp2p/service-dependencies");let TimeoutError$1=class extends Error{constructor(o){super(o),this.name="TimeoutError"}},AbortError$3=class extends Error{constructor(o){super(),this.name="AbortError",this.message=o}};const getDOMException=et=>globalThis.DOMException===void 0?new AbortError$3(et):new DOMException(et),getAbortedReason=et=>{const o=et.reason===void 0?getDOMException("This operation was aborted."):et.reason;return o instanceof Error?o:getDOMException(o)};function pTimeout(et,o){const{milliseconds:tt,fallback:rt,message:nt,customTimers:ot={setTimeout,clearTimeout}}=o;let it;const at=new Promise((ct,lt)=>{if(typeof tt!="number"||Math.sign(tt)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${tt}\``);if(o.signal){const{signal:ht}=o;ht.aborted&<(getAbortedReason(ht));const mt=()=>{lt(getAbortedReason(ht))};ht.addEventListener("abort",mt,{once:!0}),et.finally(()=>{ht.removeEventListener("abort",mt)})}if(tt===Number.POSITIVE_INFINITY){et.then(ct,lt);return}const dt=new TimeoutError$1;it=ot.setTimeout.call(void 0,()=>{if(rt){try{ct(rt())}catch(ht){lt(ht)}return}typeof et.cancel=="function"&&et.cancel(),nt===!1?ct():nt instanceof Error?lt(nt):(dt.message=nt??`Promise timed out after ${tt} milliseconds`,lt(dt))},tt),(async()=>{try{ct(await et)}catch(ht){lt(ht)}})()}).finally(()=>{at.clear()});return at.clear=()=>{ot.clearTimeout.call(void 0,it),it=void 0},at}function lowerBound(et,o,tt){let rt=0,nt=et.length;for(;nt>0;){const ot=Math.trunc(nt/2);let it=rt+ot;tt(et[it],o)<=0?(rt=++it,nt-=ot+1):nt=ot}return rt}var tn,Bl;let PriorityQueue$1=(Bl=class{constructor(){hr(this,tn,[])}enqueue(o,tt){tt={priority:0,...tt};const rt={priority:tt.priority,run:o};if(this.size&&Lt(this,tn)[this.size-1].priority>=tt.priority){Lt(this,tn).push(rt);return}const nt=lowerBound(Lt(this,tn),rt,(ot,it)=>it.priority-ot.priority);Lt(this,tn).splice(nt,0,rt)}dequeue(){const o=Lt(this,tn).shift();return o==null?void 0:o.run}filter(o){return Lt(this,tn).filter(tt=>tt.priority===o.priority).map(tt=>tt.run)}get size(){return Lt(this,tn).length}},tn=new WeakMap,Bl);var Xn,Jn,En,ho,eo,fo,Hr,to,Ur,po,Wr,ro,an,mo,$r,nu,ou,iu,su,au,_i,Ls,Ms,es,cu,ts;class PQueue extends EventEmitter$1{constructor(tt){var rt,nt;super();hr(this,$r);hr(this,Xn);hr(this,Jn);hr(this,En,0);hr(this,ho);hr(this,eo);hr(this,fo,0);hr(this,Hr);hr(this,to);hr(this,Ur);hr(this,po);hr(this,Wr,0);hr(this,ro);hr(this,an);hr(this,mo);wt(this,"timeout");if(tt={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:PriorityQueue$1,...tt},!(typeof tt.intervalCap=="number"&&tt.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${((rt=tt.intervalCap)==null?void 0:rt.toString())??""}\` (${typeof tt.intervalCap})`);if(tt.interval===void 0||!(Number.isFinite(tt.interval)&&tt.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${((nt=tt.interval)==null?void 0:nt.toString())??""}\` (${typeof tt.interval})`);ur(this,Xn,tt.carryoverConcurrencyCount),ur(this,Jn,tt.intervalCap===Number.POSITIVE_INFINITY||tt.interval===0),ur(this,ho,tt.intervalCap),ur(this,eo,tt.interval),ur(this,Ur,new tt.queueClass),ur(this,po,tt.queueClass),this.concurrency=tt.concurrency,this.timeout=tt.timeout,ur(this,mo,tt.throwOnTimeout===!0),ur(this,an,tt.autoStart===!1)}get concurrency(){return Lt(this,ro)}set concurrency(tt){if(!(typeof tt=="number"&&tt>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${tt}\` (${typeof tt})`);ur(this,ro,tt),fr(this,$r,es).call(this)}async add(tt,rt={}){return rt={timeout:this.timeout,throwOnTimeout:Lt(this,mo),...rt},new Promise((nt,ot)=>{Lt(this,Ur).enqueue(async()=>{var it;Cn(this,Wr)._++,Cn(this,En)._++;try{(it=rt.signal)==null||it.throwIfAborted();let st=tt({signal:rt.signal});rt.timeout&&(st=pTimeout(Promise.resolve(st),{milliseconds:rt.timeout})),rt.signal&&(st=Promise.race([st,fr(this,$r,cu).call(this,rt.signal)]));const at=await st;nt(at),this.emit("completed",at)}catch(st){if(st instanceof TimeoutError$1&&!rt.throwOnTimeout){nt();return}ot(st),this.emit("error",st)}finally{fr(this,$r,iu).call(this)}},rt),this.emit("add"),fr(this,$r,_i).call(this)})}async addAll(tt,rt){return Promise.all(tt.map(async nt=>this.add(nt,rt)))}start(){return Lt(this,an)?(ur(this,an,!1),fr(this,$r,es).call(this),this):this}pause(){ur(this,an,!0)}clear(){ur(this,Ur,new(Lt(this,po)))}async onEmpty(){Lt(this,Ur).size!==0&&await fr(this,$r,ts).call(this,"empty")}async onSizeLessThan(tt){Lt(this,Ur).sizeLt(this,Ur).size{fr(this,$r,su).call(this)},rt)),!0}return!1},_i=function(){if(Lt(this,Ur).size===0)return Lt(this,Hr)&&clearInterval(Lt(this,Hr)),ur(this,Hr,void 0),this.emit("empty"),Lt(this,Wr)===0&&this.emit("idle"),!1;if(!Lt(this,an)){const tt=!Lt(this,$r,au);if(Lt(this,$r,nu)&&Lt(this,$r,ou)){const rt=Lt(this,Ur).dequeue();return rt?(this.emit("active"),rt(),tt&&fr(this,$r,Ls).call(this),!0):!1}}return!1},Ls=function(){Lt(this,Jn)||Lt(this,Hr)!==void 0||(ur(this,Hr,setInterval(()=>{fr(this,$r,Ms).call(this)},Lt(this,eo))),ur(this,fo,Date.now()+Lt(this,eo)))},Ms=function(){Lt(this,En)===0&&Lt(this,Wr)===0&&Lt(this,Hr)&&(clearInterval(Lt(this,Hr)),ur(this,Hr,void 0)),ur(this,En,Lt(this,Xn)?Lt(this,Wr):0),fr(this,$r,es).call(this)},es=function(){for(;fr(this,$r,_i).call(this););},cu=async function(tt){return new Promise((rt,nt)=>{tt.addEventListener("abort",()=>{nt(tt.reason)},{once:!0})})},ts=async function(tt,rt){return new Promise(nt=>{const ot=()=>{rt&&!rt()||(this.off(tt,ot),nt())};this.on(tt,ot)})};function getTypes(et){const o=[RecordType.A];return et==null?o:Array.isArray(et)?et.length===0?o:et:[et]}function coerce$a(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$c(et){return new TextEncoder().encode(et)}function toString$g(et){return new TextDecoder().decode(et)}function base$9(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$a=base$9,_brrp__multiformats_scope_baseX$9=src$a;let Encoder$9=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$9=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$9(this,o)}},ComposedDecoder$9=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$9(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$9(et,o){return new ComposedDecoder$9({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$9=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$9(o,tt,rt),this.decoder=new Decoder$9(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$a({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$9(et,o,tt,rt)}function baseX$9({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$9(tt,et);return from$a({prefix:o,name:et,encode:rt,decode:ot=>coerce$a(nt(ot))})}function decode$q(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$l(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$6=alphabet$6.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$k(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$6[tt],o),"")}function decode$p(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$6[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$c=from$a({prefix:"🚀",name:"base256emoji",encode:encode$k,decode:decode$p}),base256emoji$d=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$c},Symbol.toStringTag,{value:"Module"})),base32$g=rfc4648$8({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$6=rfc4648$8({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$6=rfc4648$8({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$6=rfc4648$8({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$6=rfc4648$8({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$6=rfc4648$8({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$6=rfc4648$8({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$6=rfc4648$8({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$6=rfc4648$8({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$h=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$g,base32hex:base32hex$6,base32hexpad:base32hexpad$6,base32hexpadupper:base32hexpadupper$6,base32hexupper:base32hexupper$6,base32pad:base32pad$6,base32padupper:base32padupper$6,base32upper:base32upper$6,base32z:base32z$6},Symbol.toStringTag,{value:"Module"})),base36$d=baseX$9({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$6=baseX$9({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$e=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$d,base36upper:base36upper$6},Symbol.toStringTag,{value:"Module"})),base58btc$9=baseX$9({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$6=baseX$9({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$6=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$9,base58flickr:base58flickr$6},Symbol.toStringTag,{value:"Module"})),base64$f=rfc4648$8({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$6=rfc4648$8({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$6=rfc4648$8({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$6=rfc4648$8({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$g=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$f,base64pad:base64pad$6,base64url:base64url$6,base64urlpad:base64urlpad$6},Symbol.toStringTag,{value:"Module"})),base8$c=rfc4648$8({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$d=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$c},Symbol.toStringTag,{value:"Module"})),identity$6=from$a({prefix:"\0",name:"identity",encode:et=>toString$g(et),decode:et=>fromString$c(et)}),identityBase$6=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$6},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$6={...identityBase$6,...base2$d,...base8$d,...base10$d,...base16$d,...base32$h,...base36$e,...base58$6,...base64$g,...base256emoji$d};function allocUnsafe$5(et=0){return new Uint8Array(et)}function createCodec$6(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$9=createCodec$6("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$6=createCodec$6("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$5(et.length);for(let tt=0;tt({name:o.name,type:RecordType[o.type]})),Answer:(et.Answer??et.answers??[]).map(o=>({name:o.name,type:RecordType[o.type],TTL:o.TTL??o.ttl??DEFAULT_TTL,data:o.data instanceof Uint8Array?toString$f(o.data):o.data}))}}const DEFAULT_QUERY_CONCURRENCY=4;function dnsJsonOverHttps(et,o={}){const tt=new PQueue({concurrency:o.queryConcurrency??DEFAULT_QUERY_CONCURRENCY});return async(rt,nt={})=>{var st;const ot=new URLSearchParams;ot.set("name",rt),getTypes(nt.types).forEach(at=>{ot.append("type",RecordType[at])}),(st=nt.onProgress)==null||st.call(nt,new CustomProgressEvent("dns:query",{detail:rt}));const it=await tt.add(async()=>{var lt;const at=await fetch(`${et}?${ot}`,{headers:{accept:"application/dns-json"},signal:nt==null?void 0:nt.signal});if(at.status!==200)throw new Error(`Unexpected HTTP status: ${at.status} - ${at.statusText}`);const ct=toDNSResponse(await at.json());return(lt=nt.onProgress)==null||lt.call(nt,new CustomProgressEvent("dns:response",{detail:ct})),ct},{signal:nt.signal});if(it==null)throw new Error("No DNS response received");return it}}function defaultResolver(){return[dnsJsonOverHttps("https://cloudflare-dns.com/dns-query"),dnsJsonOverHttps("https://dns.google/resolve")]}var hashlru=function(et){if(!et)throw Error("hashlru must have a max value, of type number, greater than 0");var o=0,tt=Object.create(null),rt=Object.create(null);function nt(ot,it){tt[ot]=it,o++,o>=et&&(o=0,rt=tt,tt=Object.create(null))}return{has:function(ot){return tt[ot]!==void 0||rt[ot]!==void 0},remove:function(ot){tt[ot]!==void 0&&(tt[ot]=void 0),rt[ot]!==void 0&&(rt[ot]=void 0)},get:function(ot){var it=tt[ot];if(it!==void 0)return it;if((it=rt[ot])!==void 0)return nt(ot,it),it},set:function(ot,it){tt[ot]!==void 0?tt[ot]=it:nt(ot,it)},clear:function(){tt=Object.create(null),rt=Object.create(null)}}};const hashlru$1=getDefaultExportFromCjs(hashlru);class CachedAnswers{constructor(o){wt(this,"lru");this.lru=hashlru$1(o)}get(o,tt){let rt=!0;const nt=[];for(const ot of tt){const it=this.getAnswers(o,ot);if(it.length===0){rt=!1;break}nt.push(...it)}if(rt)return toDNSResponse({answers:nt})}getAnswers(o,tt){const rt=`${o.toLowerCase()}-${tt}`,nt=this.lru.get(rt);if(nt!=null){const ot=nt.filter(it=>it.expires>Date.now()).map(({expires:it,value:st})=>({...st,TTL:Math.round((it-Date.now())/1e3),type:RecordType[st.type]}));return ot.length===0&&this.lru.remove(rt),ot}return[]}add(o,tt){const rt=`${o.toLowerCase()}-${tt.type}`,nt=this.lru.get(rt)??[];nt.push({expires:Date.now()+(tt.TTL??DEFAULT_TTL)*1e3,value:tt}),this.lru.set(rt,nt)}remove(o,tt){const rt=`${o.toLowerCase()}-${tt}`;this.lru.remove(rt)}clear(){this.lru.clear()}}function cache$1(et){return new CachedAnswers(et)}const DEFAULT_ANSWER_CACHE_SIZE=1e3;class DNS{constructor(o){wt(this,"resolvers");wt(this,"cache");this.resolvers={},this.cache=cache$1(o.cacheSize??DEFAULT_ANSWER_CACHE_SIZE),Object.entries(o.resolvers??{}).forEach(([tt,rt])=>{Array.isArray(rt)||(rt=[rt]),tt.endsWith(".")||(tt=`${tt}.`),this.resolvers[tt]=rt}),this.resolvers["."]==null&&(this.resolvers["."]=defaultResolver())}async query(o,tt={}){var at,ct,lt;const rt=getTypes(tt.types),nt=tt.cached!==!1?this.cache.get(o,rt):void 0;if(nt!=null)return(at=tt.onProgress)==null||at.call(tt,new CustomProgressEvent("dns:cache",{detail:nt})),nt;const ot=`${o.split(".").pop()}.`,it=(this.resolvers[ot]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),st=[];for(const dt of it){if(((ct=tt.signal)==null?void 0:ct.aborted)===!0)break;try{const ht=await dt(o,{...tt,types:rt});for(const mt of ht.Answer)this.cache.add(o,mt);return ht}catch(ht){st.push(ht),(lt=tt.onProgress)==null||lt.call(tt,new CustomProgressEvent("dns:error",{detail:ht}))}}throw st.length===1?st[0]:new AggregateError(st,`DNS lookup of ${o} ${rt} failed`)}}var RecordType;(function(et){et[et.A=1]="A",et[et.CNAME=5]="CNAME",et[et.TXT=16]="TXT",et[et.AAAA=28]="AAAA"})(RecordType||(RecordType={}));function dns(et={}){return new DNS(et)}const MAX_RECURSIVE_DEPTH=32,{code:dnsaddrCode}=getProtocol("dnsaddr");class RecursionLimitError extends Error{constructor(o="Max recursive depth reached"){super(o),this.name="RecursionLimitError"}}const dnsaddrResolver=async function(o,tt={}){const rt=tt.maxRecursiveDepth??MAX_RECURSIVE_DEPTH;if(rt===0)throw new RecursionLimitError("Max recursive depth reached");const[,nt]=o.stringTuples().find(([ct])=>ct===dnsaddrCode)??[],it=await((tt==null?void 0:tt.dns)??dns()).query(`_dnsaddr.${nt}`,{signal:tt==null?void 0:tt.signal,types:[RecordType.TXT]}),st=o.getPeerId(),at=[];for(const ct of it.Answer){const lt=ct.data.replace(/["']/g,"").trim().split("=")[1];if(lt==null||st!=null&&!lt.includes(st))continue;const dt=multiaddr(lt);if(lt.startsWith("/dnsaddr")){const ht=await dt.resolve({...tt,maxRecursiveDepth:rt-1});at.push(...ht.map(mt=>mt.toString()))}else at.push(dt.toString())}return at};var isPlainObj=et=>{if(Object.prototype.toString.call(et)!=="[object Object]")return!1;const o=Object.getPrototypeOf(et);return o===null||o===Object.prototype};const isOptionObject=isPlainObj,{hasOwnProperty:hasOwnProperty$1}=Object.prototype,{propertyIsEnumerable}=Object,defineProperty$1=(et,o,tt)=>Object.defineProperty(et,o,{value:tt,writable:!0,enumerable:!0,configurable:!0}),globalThis$1=commonjsGlobal,defaultMergeOptions={concatArrays:!1,ignoreUndefined:!1},getEnumerableOwnPropertyKeys=et=>{const o=[];for(const tt in et)hasOwnProperty$1.call(et,tt)&&o.push(tt);if(Object.getOwnPropertySymbols){const tt=Object.getOwnPropertySymbols(et);for(const rt of tt)propertyIsEnumerable.call(et,rt)&&o.push(rt)}return o};function clone(et){return Array.isArray(et)?cloneArray(et):isOptionObject(et)?cloneOptionObject(et):et}function cloneArray(et){const o=et.slice(0,0);return getEnumerableOwnPropertyKeys(et).forEach(tt=>{defineProperty$1(o,tt,clone(et[tt]))}),o}function cloneOptionObject(et){const o=Object.getPrototypeOf(et)===null?Object.create(null):{};return getEnumerableOwnPropertyKeys(et).forEach(tt=>{defineProperty$1(o,tt,clone(et[tt]))}),o}const mergeKeys=(et,o,tt,rt)=>(tt.forEach(nt=>{typeof o[nt]>"u"&&rt.ignoreUndefined||(nt in et&&et[nt]!==Object.getPrototypeOf(et)?defineProperty$1(et,nt,merge$1(et[nt],o[nt],rt)):defineProperty$1(et,nt,clone(o[nt])))}),et),concatArrays=(et,o,tt)=>{let rt=et.slice(0,0),nt=0;return[et,o].forEach(ot=>{const it=[];for(let st=0;st!it.includes(st)),tt)}),rt};function merge$1(et,o,tt){return tt.concatArrays&&Array.isArray(et)&&Array.isArray(o)?concatArrays(et,o,tt):!isOptionObject(o)||!isOptionObject(et)?clone(o):mergeKeys(et,o,getEnumerableOwnPropertyKeys(o),tt)}var mergeOptions=function(...et){const o=merge$1(clone(defaultMergeOptions),this!==globalThis$1&&this||{},defaultMergeOptions);let tt={_:{}};for(const rt of et)if(rt!==void 0){if(!isOptionObject(rt))throw new TypeError("`"+rt+"` is not an Option Object");tt=merge$1(tt,{_:rt},o)}return tt._};const mergeOptions$1=getDefaultExportFromCjs(mergeOptions),DefaultConfig={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:et=>et},connectionManager:{resolvers:{dnsaddr:dnsaddrResolver}},transportManager:{faultTolerance:FaultTolerance.FATAL_ALL}};async function validateConfig(et){var tt,rt;const o=mergeOptions$1(DefaultConfig,et);if(o.connectionProtector===null&&((rt=(tt=globalThis.process)==null?void 0:tt.env)==null?void 0:rt.LIBP2P_FORCE_PNET)!=null)throw new InvalidParametersError$1("Private network is enforced, but no protector was provided");return o}function coerce$9(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function base$8(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$9=base$8,_brrp__multiformats_scope_baseX$8=src$9;let Encoder$8=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$8=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$8(this,o)}},ComposedDecoder$8=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$8(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$8(et,o){return new ComposedDecoder$8({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$8=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$8(o,tt,rt),this.decoder=new Decoder$8(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$9({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$8(et,o,tt,rt)}function baseX$8({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$8(tt,et);return from$9({prefix:o,name:et,encode:rt,decode:ot=>coerce$9(nt(ot))})}function decode$o(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$j(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<0)return parse$3(et);if(typeof et=="number"&&isFinite(et))return o!=null&&o.long?fmtLong(et):fmtShort(et);throw new Error("Value is not a string or number.")}catch(tt){const rt=isError$1(tt)?`${tt.message}. value=${JSON.stringify(et)}`:"An unknown error has occured.";throw new Error(rt)}}function parse$3(et){if(et=String(et),et.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");const o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(et);if(!o)return NaN;const tt=parseFloat(o[1]),rt=(o[2]||"ms").toLowerCase();switch(rt){case"years":case"year":case"yrs":case"yr":case"y":return tt*y;case"weeks":case"week":case"w":return tt*w;case"days":case"day":case"d":return tt*d;case"hours":case"hour":case"hrs":case"hr":case"h":return tt*h;case"minutes":case"minute":case"mins":case"min":case"m":return tt*m;case"seconds":case"second":case"secs":case"sec":case"s":return tt*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return tt;default:throw new Error(`The unit ${rt} was matched, but no matching case exists.`)}}function fmtShort(et){const o=Math.abs(et);return o>=d?`${Math.round(et/d)}d`:o>=h?`${Math.round(et/h)}h`:o>=m?`${Math.round(et/m)}m`:o>=s?`${Math.round(et/s)}s`:`${et}ms`}function fmtLong(et){const o=Math.abs(et);return o>=d?plural(et,o,d,"day"):o>=h?plural(et,o,h,"hour"):o>=m?plural(et,o,m,"minute"):o>=s?plural(et,o,s,"second"):`${et} ms`}function plural(et,o,tt,rt){const nt=o>=tt*1.5;return`${Math.round(et/tt)} ${rt}${nt?"s":""}`}function isError$1(et){return typeof et=="object"&&et!==null&&"message"in et}function setup(et){tt.debug=tt,tt.default=tt,tt.coerce=at,tt.disable=ot,tt.enable=nt,tt.enabled=it,tt.humanize=ms,tt.destroy=ct,Object.keys(et).forEach(lt=>{tt[lt]=et[lt]}),tt.names=[],tt.skips=[],tt.formatters={};function o(lt){let dt=0;for(let ht=0;ht{if(Ct==="%%")return"%";vt++;const At=tt.formatters[St];if(typeof At=="function"){const kt=gt[vt];Ct=At.call(yt,kt),gt.splice(vt,1),vt--}return Ct}),tt.formatArgs.call(yt,gt),(yt.log||tt.log).apply(yt,gt)}return pt.namespace=lt,pt.useColors=tt.useColors(),pt.color=tt.selectColor(lt),pt.extend=rt,pt.destroy=tt.destroy,Object.defineProperty(pt,"enabled",{enumerable:!0,configurable:!1,get:()=>ht!==null?ht:(mt!==tt.namespaces&&(mt=tt.namespaces,ft=tt.enabled(lt)),ft),set:gt=>{ht=gt}}),typeof tt.init=="function"&&tt.init(pt),pt}function rt(lt,dt){const ht=tt(this.namespace+(typeof dt>"u"?":":dt)+lt);return ht.log=this.log,ht}function nt(lt){tt.save(lt),tt.namespaces=lt,tt.names=[],tt.skips=[];let dt;const ht=(typeof lt=="string"?lt:"").split(/[\s,]+/),mt=ht.length;for(dt=0;dt"-"+dt)].join(",");return tt.enable(""),lt}function it(lt){if(lt[lt.length-1]==="*")return!0;let dt,ht;for(dt=0,ht=tt.skips.length;dt=31||typeof navigator<"u"&&((nt=navigator.userAgent)==null?void 0:nt.toLowerCase().match(/applewebkit\/(\d+)/))}function formatArgs(et){if(et[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+et[0]+(this.useColors?"%c ":" ")+"+"+ms(this.diff),!this.useColors)return;const o="color: "+this.color;et.splice(1,0,o,"color: inherit");let tt=0,rt=0;et[0].replace(/%[a-zA-Z%]/g,nt=>{nt!=="%%"&&(tt++,nt==="%c"&&(rt=tt))}),et.splice(rt,0,o)}const log$a=console.debug??console.log??(()=>{});function save(et){try{et?storage==null||storage.setItem("debug",et):storage==null||storage.removeItem("debug")}catch{}}function load$1(){let et;try{et=storage==null?void 0:storage.getItem("debug")}catch{}return!et&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(et=define_globalThis_process_env_default.DEBUG),et}function localstorage(){try{return localStorage}catch{}}function setupFormatters(et){et.j=function(o){try{return JSON.stringify(o)}catch(tt){return"[UnexpectedJSONParseError]: "+tt.message}}}const weald=setup({formatArgs,save,load:load$1,useColors,setupFormatters,colors,storage,log:log$a});weald.formatters.b=et=>et==null?"undefined":base58btc$8.baseEncode(et);weald.formatters.t=et=>et==null?"undefined":base32$f.baseEncode(et);weald.formatters.m=et=>et==null?"undefined":base64$e.baseEncode(et);weald.formatters.p=et=>et==null?"undefined":et.toString();weald.formatters.c=et=>et==null?"undefined":et.toString();weald.formatters.k=et=>et==null?"undefined":et.toString();weald.formatters.a=et=>et==null?"undefined":et.toString();weald.formatters.e=et=>et==null?"undefined":notEmpty(et.stack)??notEmpty(et.message)??et.toString();function createDisabledLogger(et){const o=()=>{};return o.enabled=!1,o.color="",o.diff=0,o.log=()=>{},o.namespace=et,o.destroy=()=>!0,o.extend=()=>o,o}function defaultLogger(){return{forComponent(et){return logger$2(et)}}}function logger$2(et){let o=createDisabledLogger(`${et}:trace`);return weald.enabled(`${et}:trace`)&&weald.names.map(tt=>tt.toString()).find(tt=>tt.includes(":trace"))!=null&&(o=weald(`${et}:trace`)),Object.assign(weald(et),{error:weald(`${et}:error`),trace:o})}function notEmpty(et){if(et!=null&&(et=et.trim(),et.length!==0))return et}function coerce$8(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function base$7(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$8=base$7,_brrp__multiformats_scope_baseX$7=src$8;let Encoder$7=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$7=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$7(this,o)}},ComposedDecoder$7=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$7(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$7(et,o){return new ComposedDecoder$7({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$7=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$7(o,tt,rt),this.decoder=new Decoder$7(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$8({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$7(et,o,tt,rt)}function baseX$7({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$7(tt,et);return from$8({prefix:o,name:et,encode:rt,decode:ot=>coerce$8(nt(ot))})}const base58btc$7=baseX$7({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});baseX$7({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var encode_1$1=encode$i,MSB$2=128,REST$2=127,MSBALL$1=~REST$2,INT$1=Math.pow(2,31);function encode$i(et,o,tt){o=o||[],tt=tt||0;for(var rt=tt;et>=INT$1;)o[tt++]=et&255|MSB$2,et/=128;for(;et&MSBALL$1;)o[tt++]=et&255|MSB$2,et>>>=7;return o[tt]=et|0,encode$i.bytes=tt-rt+1,o}var decode$n=read$2,MSB$1$1=128,REST$1$1=127;function read$2(et,rt){var tt=0,rt=rt||0,nt=0,ot=rt,it,st=et.length;do{if(ot>=st)throw read$2.bytes=0,new RangeError("Could not decode varint");it=et[ot++],tt+=nt<28?(it&REST$1$1)<=MSB$1$1);return read$2.bytes=ot-rt,tt}var N1$1=Math.pow(2,7),N2$1=Math.pow(2,14),N3$1=Math.pow(2,21),N4$1=Math.pow(2,28),N5$1=Math.pow(2,35),N6$1=Math.pow(2,42),N7$1=Math.pow(2,49),N8$1=Math.pow(2,56),N9$1=Math.pow(2,63),length$1=function(et){return ettt,next:()=>{const rt=et.next(),nt=rt.value;return rt.done===!0||nt==null?{done:!0,value:void 0}:{done:!1,value:o(nt)}}};return tt}function peerIdFromString(et){const o=decode$l(base58btc$7.decode(`z${et}`));return peerIdFromMultihash(o)}class PeerMap{constructor(o){wt(this,"map");if(this.map=new Map,o!=null)for(const[tt,rt]of o.entries())this.map.set(tt.toString(),{key:tt,value:rt})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(o){return this.map.delete(o.toString())}entries(){return mapIterable(this.map.entries(),o=>[o[1].key,o[1].value])}forEach(o){this.map.forEach((tt,rt)=>{o(tt.value,tt.key,this)})}get(o){var tt;return(tt=this.map.get(o.toString()))==null?void 0:tt.value}has(o){return this.map.has(o.toString())}set(o,tt){this.map.set(o.toString(),{key:o,value:tt})}keys(){return mapIterable(this.map.values(),o=>o.key)}values(){return mapIterable(this.map.values(),o=>o.value)}get size(){return this.map.size}}class PeerSet{constructor(o){wt(this,"set");if(this.set=new Set,o!=null)for(const tt of o)this.set.add(tt.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(o){this.set.add(o.toString())}clear(){this.set.clear()}delete(o){this.set.delete(o.toString())}entries(){return mapIterable(this.set.entries(),o=>{const tt=peerIdFromString(o[0]);return[tt,tt]})}forEach(o){this.set.forEach(tt=>{const rt=peerIdFromString(tt);o(rt,rt,this)})}has(o){return this.set.has(o.toString())}values(){return mapIterable(this.set.values(),o=>peerIdFromString(o))}intersection(o){const tt=new PeerSet;for(const rt of o)this.has(rt)&&tt.add(rt);return tt}difference(o){const tt=new PeerSet;for(const rt of this)o.has(rt)||tt.add(rt);return tt}union(o){const tt=new PeerSet;for(const rt of o)tt.add(rt);for(const rt of this)tt.add(rt);return tt}}var murmurHash3js={exports:{}};(function(et,o){(function(tt,rt){var nt={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function ot(pt){if(!Array.isArray(pt)&&!ArrayBuffer.isView(pt))return!1;for(var gt=0;gt255)return!1;return!0}function it(pt,gt){return(pt&65535)*gt+(((pt>>>16)*gt&65535)<<16)}function st(pt,gt){return pt<>>32-gt}function at(pt){return pt^=pt>>>16,pt=it(pt,2246822507),pt^=pt>>>13,pt=it(pt,3266489909),pt^=pt>>>16,pt}function ct(pt,gt){pt=[pt[0]>>>16,pt[0]&65535,pt[1]>>>16,pt[1]&65535],gt=[gt[0]>>>16,gt[0]&65535,gt[1]>>>16,gt[1]&65535];var yt=[0,0,0,0];return yt[3]+=pt[3]+gt[3],yt[2]+=yt[3]>>>16,yt[3]&=65535,yt[2]+=pt[2]+gt[2],yt[1]+=yt[2]>>>16,yt[2]&=65535,yt[1]+=pt[1]+gt[1],yt[0]+=yt[1]>>>16,yt[1]&=65535,yt[0]+=pt[0]+gt[0],yt[0]&=65535,[yt[0]<<16|yt[1],yt[2]<<16|yt[3]]}function lt(pt,gt){pt=[pt[0]>>>16,pt[0]&65535,pt[1]>>>16,pt[1]&65535],gt=[gt[0]>>>16,gt[0]&65535,gt[1]>>>16,gt[1]&65535];var yt=[0,0,0,0];return yt[3]+=pt[3]*gt[3],yt[2]+=yt[3]>>>16,yt[3]&=65535,yt[2]+=pt[2]*gt[3],yt[1]+=yt[2]>>>16,yt[2]&=65535,yt[2]+=pt[3]*gt[2],yt[1]+=yt[2]>>>16,yt[2]&=65535,yt[1]+=pt[1]*gt[3],yt[0]+=yt[1]>>>16,yt[1]&=65535,yt[1]+=pt[2]*gt[2],yt[0]+=yt[1]>>>16,yt[1]&=65535,yt[1]+=pt[3]*gt[1],yt[0]+=yt[1]>>>16,yt[1]&=65535,yt[0]+=pt[0]*gt[3]+pt[1]*gt[2]+pt[2]*gt[1]+pt[3]*gt[0],yt[0]&=65535,[yt[0]<<16|yt[1],yt[2]<<16|yt[3]]}function dt(pt,gt){return gt%=64,gt===32?[pt[1],pt[0]]:gt<32?[pt[0]<>>32-gt,pt[1]<>>32-gt]:(gt-=32,[pt[1]<>>32-gt,pt[0]<>>32-gt])}function ht(pt,gt){return gt%=64,gt===0?pt:gt<32?[pt[0]<>>32-gt,pt[1]<>>1]),pt=lt(pt,[4283543511,3981806797]),pt=mt(pt,[0,pt[0]>>>1]),pt=lt(pt,[3301882366,444984403]),pt=mt(pt,[0,pt[0]>>>1]),pt}nt.x86.hash32=function(pt,gt){if(nt.inputValidation&&!ot(pt))return rt;gt=gt||0;for(var yt=pt.length%4,bt=pt.length-yt,xt=gt,vt=0,Et=3432918353,Ct=461845907,St=0;St>>0},nt.x86.hash128=function(pt,gt){if(nt.inputValidation&&!ot(pt))return rt;gt=gt||0;for(var yt=pt.length%16,bt=pt.length-yt,xt=gt,vt=gt,Et=gt,Ct=gt,St=0,At=0,kt=0,It=0,Ot=597399067,Nt=2869860233,Yt=951274213,Ft=2716044179,Ht=0;Ht>>0).toString(16)).slice(-8)+("00000000"+(vt>>>0).toString(16)).slice(-8)+("00000000"+(Et>>>0).toString(16)).slice(-8)+("00000000"+(Ct>>>0).toString(16)).slice(-8)},nt.x64.hash128=function(pt,gt){if(nt.inputValidation&&!ot(pt))return rt;gt=gt||0;for(var yt=pt.length%16,bt=pt.length-yt,xt=[0,gt],vt=[0,gt],Et=[0,0],Ct=[0,0],St=[2277735313,289559509],At=[1291169091,658871167],kt=0;kt>>0).toString(16)).slice(-8)+("00000000"+(xt[1]>>>0).toString(16)).slice(-8)+("00000000"+(vt[0]>>>0).toString(16)).slice(-8)+("00000000"+(vt[1]>>>0).toString(16)).slice(-8)},et.exports&&(o=et.exports=nt),o.murmurHash3=nt})()})(murmurHash3js,murmurHash3js.exports);function alloc$2(et=0){return new Uint8Array(et)}function allocUnsafe$4(et=0){return new Uint8Array(et)}function coerce$7(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$b(et){return new TextEncoder().encode(et)}function toString$e(et){return new TextDecoder().decode(et)}function base$6(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$7=base$6,_brrp__multiformats_scope_baseX$6=src$7;let Encoder$6=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$6=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$6(this,o)}},ComposedDecoder$6=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$6(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$6(et,o){return new ComposedDecoder$6({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$6=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$6(o,tt,rt),this.decoder=new Decoder$6(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$7({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$6(et,o,tt,rt)}function baseX$6({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$6(tt,et);return from$7({prefix:o,name:et,encode:rt,decode:ot=>coerce$7(nt(ot))})}function decode$k(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$h(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$5=alphabet$5.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$g(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$5[tt],o),"")}function decode$j(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$5[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$a=from$7({prefix:"🚀",name:"base256emoji",encode:encode$g,decode:decode$j}),base256emoji$b=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$a},Symbol.toStringTag,{value:"Module"})),base32$d=rfc4648$6({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$5=rfc4648$6({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$5=rfc4648$6({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$5=rfc4648$6({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$5=rfc4648$6({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$5=rfc4648$6({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$5=rfc4648$6({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$5=rfc4648$6({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$5=rfc4648$6({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$e=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$d,base32hex:base32hex$5,base32hexpad:base32hexpad$5,base32hexpadupper:base32hexpadupper$5,base32hexupper:base32hexupper$5,base32pad:base32pad$5,base32padupper:base32padupper$5,base32upper:base32upper$5,base32z:base32z$5},Symbol.toStringTag,{value:"Module"})),base36$b=baseX$6({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$5=baseX$6({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$c=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$b,base36upper:base36upper$5},Symbol.toStringTag,{value:"Module"})),base58btc$6=baseX$6({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$5=baseX$6({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$5=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$6,base58flickr:base58flickr$5},Symbol.toStringTag,{value:"Module"})),base64$c=rfc4648$6({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$5=rfc4648$6({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$5=rfc4648$6({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$5=rfc4648$6({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$d=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$c,base64pad:base64pad$5,base64url:base64url$5,base64urlpad:base64urlpad$5},Symbol.toStringTag,{value:"Module"})),base8$a=rfc4648$6({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$b=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$a},Symbol.toStringTag,{value:"Module"})),identity$5=from$7({prefix:"\0",name:"identity",encode:et=>toString$e(et),decode:et=>fromString$b(et)}),identityBase$5=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$5},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$5={...identityBase$5,...base2$b,...base8$b,...base10$b,...base16$b,...base32$e,...base36$c,...base58$5,...base64$d,...base256emoji$b};function createCodec$5(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$8=createCodec$5("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$5=createCodec$5("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$4(et.length);for(let tt=0;ttMAX_FINGERPRINT_SIZE)throw new TypeError("Invalid Fingerprint Size");const ot=tt.hashV(o,rt),it=alloc$2(nt);for(let st=0;sto.equals(tt))}add(o){if(!(o instanceof Fingerprint))throw new TypeError("Invalid Fingerprint");for(let tt=0;tto.equals(rt));return tt>-1?(this.contents[tt]=null,!0):!1}}const FNV_PRIMES={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},FNV_OFFSETS={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},cachedEncoder=new globalThis.TextEncoder;function fnv1aUint8Array(et,o){const tt=FNV_PRIMES[o];let rt=FNV_OFFSETS[o];for(let nt=0;nt0;){const it=cachedEncoder.encodeInto(ot,tt);ot=ot.slice(it.read);for(let st=0;stNumber(fnv1a$1(et,{size:32})),hashV:(et,o)=>numberToBuffer(fnv1a.hash(et,o))};function numberToBuffer(et){let o=et.toString(16);return o.length%2===1&&(o=`0${o}`),fromString$a(o,"base16")}const maxCuckooCount=500;class CuckooFilter{constructor(o){wt(this,"bucketSize");wt(this,"filterSize");wt(this,"fingerprintSize");wt(this,"buckets");wt(this,"count");wt(this,"hash");wt(this,"seed");this.filterSize=o.filterSize,this.bucketSize=o.bucketSize??4,this.fingerprintSize=o.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=o.hash??fnv1a,this.seed=o.seed??getRandomInt(0,Math.pow(2,10))}add(o){typeof o=="string"&&(o=fromString$a(o));const tt=new Fingerprint(o,this.hash,this.seed,this.fingerprintSize),rt=this.hash.hash(o,this.seed)%this.filterSize,nt=(rt^tt.hash())%this.filterSize;if(this.buckets[rt]==null&&(this.buckets[rt]=new Bucket(this.bucketSize)),this.buckets[nt]==null&&(this.buckets[nt]=new Bucket(this.bucketSize)),this.buckets[rt].add(tt)||this.buckets[nt].add(tt))return this.count++,!0;const ot=[rt,nt];let it=ot[getRandomInt(0,ot.length-1)];this.buckets[it]==null&&(this.buckets[it]=new Bucket(this.bucketSize));for(let st=0;st.002?2:et>1e-5?4:8}function optimize(et,o=.001){const tt=calculateBucketSize(o),rt=MAX_LOAD[tt],nt=Math.round(et/rt),ot=Math.min(Math.ceil(Math.log2(1/o)+Math.log2(2*tt)),MAX_FINGERPRINT_SIZE);return{filterSize:nt,bucketSize:tt,fingerprintSize:ot}}class ScalableCuckooFilter{constructor(o){wt(this,"filterSize");wt(this,"bucketSize");wt(this,"fingerprintSize");wt(this,"scale");wt(this,"filterSeries");wt(this,"hash");wt(this,"seed");this.bucketSize=o.bucketSize??4,this.filterSize=o.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=o.fingerprintSize??2,this.scale=o.scale??2,this.hash=o.hash??fnv1a,this.seed=o.seed??getRandomInt(0,Math.pow(2,10)),this.filterSeries=[new CuckooFilter({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(o){if(typeof o=="string"&&(o=fromString$a(o)),this.has(o))return!0;let tt=this.filterSeries.find(rt=>rt.reliable);if(tt==null){const rt=this.filterSize*Math.pow(this.scale,this.filterSeries.length);tt=new CuckooFilter({filterSize:rt,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(tt)}return tt.add(o)}has(o){typeof o=="string"&&(o=fromString$a(o));for(let tt=0;tto+tt.count,0)}}function createScalableCuckooFilter(et,o=.001,tt){return new ScalableCuckooFilter({...optimize(et,o)})}const peerIdSymbol=Symbol.for("@libp2p/peer-id");function isPeerId(et){return!!(et!=null&&et[peerIdSymbol])}class InvalidParametersError extends Error{constructor(o="Invalid parameters"){super(o),this.name="InvalidParametersError"}}wt(InvalidParametersError,"name","InvalidParametersError");const events={},observable=et=>{et.addEventListener("message",o=>{observable.dispatchEvent("message",et,o)}),et.port!=null&&et.port.addEventListener("message",o=>{observable.dispatchEvent("message",et,o)})};observable.addEventListener=(et,o)=>{events[et]==null&&(events[et]=[]),events[et].push(o)};observable.removeEventListener=(et,o)=>{events[et]!=null&&(events[et]=events[et].filter(tt=>tt===o))};observable.dispatchEvent=function(et,o,tt){events[et]!=null&&events[et].forEach(rt=>rt(o,tt))};const WORKER_REQUEST_READ_LOCK="lock:worker:request-read",WORKER_RELEASE_READ_LOCK="lock:worker:release-read",MASTER_GRANT_READ_LOCK="lock:master:grant-read",WORKER_REQUEST_WRITE_LOCK="lock:worker:request-write",WORKER_RELEASE_WRITE_LOCK="lock:worker:release-write",MASTER_GRANT_WRITE_LOCK="lock:master:grant-write",nanoid=(et=21)=>Math.random().toString().substring(2),handleWorkerLockRequest=(et,o,tt,rt,nt)=>(ot,it)=>{if(it.data.type!==tt)return;const st={type:it.data.type,name:it.data.name,identifier:it.data.identifier};et.dispatchEvent(new MessageEvent(o,{data:{name:st.name,handler:async()=>{ot.postMessage({type:nt,name:st.name,identifier:st.identifier}),await new Promise(at=>{const ct=lt=>{if((lt==null?void 0:lt.data)==null)return;const dt={type:lt.data.type,name:lt.data.name,identifier:lt.data.identifier};dt.type===rt&&dt.identifier===st.identifier&&(ot.removeEventListener("message",ct),at())};ot.addEventListener("message",ct)})}}}))},makeWorkerLockRequest=(et,o,tt,rt)=>async()=>{const nt=nanoid();return globalThis.postMessage({type:o,identifier:nt,name:et}),new Promise(ot=>{const it=st=>{if((st==null?void 0:st.data)==null)return;const at={type:st.data.type,identifier:st.data.identifier};at.type===tt&&at.identifier===nt&&(globalThis.removeEventListener("message",it),ot(()=>{globalThis.postMessage({type:rt,identifier:nt,name:et})}))};globalThis.addEventListener("message",it)})},defaultOptions$4={singleProcess:!1},impl=et=>{if(et=Object.assign({},defaultOptions$4,et),!!globalThis.document||et.singleProcess){const tt=new EventTarget;return observable.addEventListener("message",handleWorkerLockRequest(tt,"requestReadLock",WORKER_REQUEST_READ_LOCK,WORKER_RELEASE_READ_LOCK,MASTER_GRANT_READ_LOCK)),observable.addEventListener("message",handleWorkerLockRequest(tt,"requestWriteLock",WORKER_REQUEST_WRITE_LOCK,WORKER_RELEASE_WRITE_LOCK,MASTER_GRANT_WRITE_LOCK)),tt}return{isWorker:!0,readLock:tt=>makeWorkerLockRequest(tt,WORKER_REQUEST_READ_LOCK,MASTER_GRANT_READ_LOCK,WORKER_RELEASE_READ_LOCK),writeLock:tt=>makeWorkerLockRequest(tt,WORKER_REQUEST_WRITE_LOCK,MASTER_GRANT_WRITE_LOCK,WORKER_RELEASE_WRITE_LOCK)}},mutexes={};let implementation;async function createReleaseable(et,o){let tt;const rt=new Promise(nt=>{tt=nt});return et.add(async()=>pTimeout((async()=>{await new Promise(nt=>{tt(()=>{nt()})})})(),{milliseconds:o.timeout})),rt}const createMutex=(et,o)=>{if(implementation.isWorker===!0)return{readLock:implementation.readLock(et,o),writeLock:implementation.writeLock(et,o)};const tt=new PQueue({concurrency:1});let rt;return{async readLock(){if(rt!=null)return createReleaseable(rt,o);rt=new PQueue({concurrency:o.concurrency,autoStart:!1});const nt=rt,ot=createReleaseable(rt,o);return tt.add(async()=>{nt.start(),await nt.onIdle().then(()=>{rt===nt&&(rt=null)})}),ot},async writeLock(){return rt=null,createReleaseable(tt,o)}}},defaultOptions$3={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function createMortice(et){const o=Object.assign({},defaultOptions$3,et);return implementation==null&&(implementation=impl(o),implementation.isWorker!==!0&&(implementation.addEventListener("requestReadLock",tt=>{mutexes[tt.data.name]!=null&&mutexes[tt.data.name].readLock().then(async rt=>tt.data.handler().finally(()=>{rt()}))}),implementation.addEventListener("requestWriteLock",async tt=>{mutexes[tt.data.name]!=null&&mutexes[tt.data.name].writeLock().then(async rt=>tt.data.handler().finally(()=>{rt()}))}))),mutexes[o.name]==null&&(mutexes[o.name]=createMutex(o.name,o)),mutexes[o.name]}function equals$2(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;tt=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$6=base$5,_brrp__multiformats_scope_baseX$5=src$6;let Encoder$5=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$5=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$5(this,o)}},ComposedDecoder$5=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$5(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$5(et,o){return new ComposedDecoder$5({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$5=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$5(o,tt,rt),this.decoder=new Decoder$5(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$6({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$5(et,o,tt,rt)}function baseX$5({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$5(tt,et);return from$6({prefix:o,name:et,encode:rt,decode:ot=>coerce$6(nt(ot))})}function decode$i(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$f(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<=INT;)o[tt++]=et&255|MSB,et/=128;for(;et&MSBALL;)o[tt++]=et&255|MSB,et>>>=7;return o[tt]=et|0,encode$e.bytes=tt-rt+1,o}var decode$h=read$1,MSB$1=128,REST$1=127;function read$1(et,rt){var tt=0,rt=rt||0,nt=0,ot=rt,it,st=et.length;do{if(ot>=st)throw read$1.bytes=0,new RangeError("Could not decode varint");it=et[ot++],tt+=nt<28?(it&REST$1)<=MSB$1);return read$1.bytes=ot-rt,tt}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function(et){return et{const[dt,ht]=decode$g(o.subarray(tt));return tt+=ht,dt};let nt=rt(),ot=DAG_PB_CODE;if(nt===18?(nt=0,tt=0):ot=rt(),nt!==0&&nt!==1)throw new RangeError(`Invalid CID version ${nt}`);const it=tt,st=rt(),at=rt(),ct=tt+at,lt=ct-it;return{version:nt,codec:ot,multihashCode:st,digestSize:at,multihashSize:lt,size:ct}}static parse(o,tt){const[rt,nt]=parseCIDtoBytes(o,tt),ot=CID.decode(nt);if(ot.version===0&&o[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache(ot).set(rt,o),ot}}function parseCIDtoBytes(et,o){switch(et[0]){case"Q":{const tt=o??base58btc$5;return[base58btc$5.prefix,tt.decode(`${base58btc$5.prefix}${et}`)]}case base58btc$5.prefix:{const tt=o??base58btc$5;return[base58btc$5.prefix,tt.decode(et)]}case base32$c.prefix:{const tt=o??base32$c;return[base32$c.prefix,tt.decode(et)]}case base36$a.prefix:{const tt=o??base36$a;return[base36$a.prefix,tt.decode(et)]}default:{if(o==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[et[0],o.decode(et)]}}}function toStringV0(et,o,tt){const{prefix:rt}=tt;if(rt!==base58btc$5.prefix)throw Error(`Cannot string encode V0 in ${tt.name} encoding`);const nt=o.get(rt);if(nt==null){const ot=tt.encode(et).slice(1);return o.set(rt,ot),ot}else return nt}function toStringV1(et,o,tt){const{prefix:rt}=tt,nt=o.get(rt);if(nt==null){const ot=tt.encode(et);return o.set(rt,ot),ot}else return nt}const DAG_PB_CODE=112,SHA_256_CODE=18;function encodeCID(et,o,tt){const rt=encodingLength$2(et),nt=rt+encodingLength$2(o),ot=new Uint8Array(nt+tt.byteLength);return encodeTo(et,ot,0),encodeTo(o,ot,rt),ot.set(tt,nt),ot}const cidSymbol=Symbol.for("@ipld/js-cid/CID");function equals(et,o){if(et===o)return!0;if(et.byteLength!==o.byteLength)return!1;for(let tt=0;tt(rt==null&&(rt=message$1((nt,ot,it={})=>{it.lengthDelimited!==!1&&ot.fork(),nt.key!=null&&nt.key!==""&&(ot.uint32(10),ot.string(nt.key)),nt.value!=null&&nt.value.byteLength>0&&(ot.uint32(18),ot.bytes(nt.value)),it.lengthDelimited!==!1&&ot.ldelim()},(nt,ot,it={})=>{const st={key:"",value:alloc$1(0)},at=ot==null?nt.len:nt.pos+ot;for(;nt.pos>>3){case 1:{st.key=nt.string();break}case 2:{st.value=nt.bytes();break}default:{nt.skipType(ct&7);break}}}return st})),rt),tt.encode=nt=>encodeMessage(nt,tt.codec()),tt.decode=(nt,ot)=>decodeMessage(nt,tt.codec(),ot)})(et.Peer$metadataEntry||(et.Peer$metadataEntry={})),function(tt){let rt;tt.codec=()=>(rt==null&&(rt=message$1((nt,ot,it={})=>{it.lengthDelimited!==!1&&ot.fork(),nt.key!=null&&nt.key!==""&&(ot.uint32(10),ot.string(nt.key)),nt.value!=null&&(ot.uint32(18),Tag.codec().encode(nt.value,ot)),it.lengthDelimited!==!1&&ot.ldelim()},(nt,ot,it={})=>{var ct;const st={key:""},at=ot==null?nt.len:nt.pos+ot;for(;nt.pos>>3){case 1:{st.key=nt.string();break}case 2:{st.value=Tag.codec().decode(nt,nt.uint32(),{limits:(ct=it.limits)==null?void 0:ct.value});break}default:{nt.skipType(lt&7);break}}}return st})),rt),tt.encode=nt=>encodeMessage(nt,tt.codec()),tt.decode=(nt,ot)=>decodeMessage(nt,tt.codec(),ot)}(et.Peer$tagsEntry||(et.Peer$tagsEntry={}));let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{if(nt.lengthDelimited!==!1&&rt.fork(),tt.addresses!=null)for(const ot of tt.addresses)rt.uint32(10),Address.codec().encode(ot,rt);if(tt.protocols!=null)for(const ot of tt.protocols)rt.uint32(18),rt.string(ot);if(tt.publicKey!=null&&(rt.uint32(34),rt.bytes(tt.publicKey)),tt.peerRecordEnvelope!=null&&(rt.uint32(42),rt.bytes(tt.peerRecordEnvelope)),tt.metadata!=null&&tt.metadata.size!==0)for(const[ot,it]of tt.metadata.entries())rt.uint32(50),et.Peer$metadataEntry.codec().encode({key:ot,value:it},rt);if(tt.tags!=null&&tt.tags.size!==0)for(const[ot,it]of tt.tags.entries())rt.uint32(58),et.Peer$tagsEntry.codec().encode({key:ot,value:it},rt);nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{var st,at,ct,lt,dt,ht;const ot={addresses:[],protocols:[],metadata:new Map,tags:new Map},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{if(((st=nt.limits)==null?void 0:st.addresses)!=null&&ot.addresses.length===nt.limits.addresses)throw new MaxLengthError('Decode error - map field "addresses" had too many elements');ot.addresses.push(Address.codec().decode(tt,tt.uint32(),{limits:(at=nt.limits)==null?void 0:at.addresses$}));break}case 2:{if(((ct=nt.limits)==null?void 0:ct.protocols)!=null&&ot.protocols.length===nt.limits.protocols)throw new MaxLengthError('Decode error - map field "protocols" had too many elements');ot.protocols.push(tt.string());break}case 4:{ot.publicKey=tt.bytes();break}case 5:{ot.peerRecordEnvelope=tt.bytes();break}case 6:{if(((lt=nt.limits)==null?void 0:lt.metadata)!=null&&ot.metadata.size===nt.limits.metadata)throw new MaxSizeError('Decode error - map field "metadata" had too many elements');const ft=et.Peer$metadataEntry.codec().decode(tt,tt.uint32());ot.metadata.set(ft.key,ft.value);break}case 7:{if(((dt=nt.limits)==null?void 0:dt.tags)!=null&&ot.tags.size===nt.limits.tags)throw new MaxSizeError('Decode error - map field "tags" had too many elements');const ft=et.Peer$tagsEntry.codec().decode(tt,tt.uint32(),{limits:{value:(ht=nt.limits)==null?void 0:ht.tags$value}});ot.tags.set(ft.key,ft.value);break}default:{tt.skipType(mt&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(Peer||(Peer={}));var Address;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.multiaddr!=null&&tt.multiaddr.byteLength>0&&(rt.uint32(10),rt.bytes(tt.multiaddr)),tt.isCertified!=null&&(rt.uint32(16),rt.bool(tt.isCertified)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={multiaddr:alloc$1(0)},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.multiaddr=tt.bytes();break}case 2:{ot.isCertified=tt.bool();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(Address||(Address={}));var Tag;(function(et){let o;et.codec=()=>(o==null&&(o=message$1((tt,rt,nt={})=>{nt.lengthDelimited!==!1&&rt.fork(),tt.value!=null&&tt.value!==0&&(rt.uint32(8),rt.uint32(tt.value)),tt.expiry!=null&&(rt.uint32(16),rt.uint64(tt.expiry)),nt.lengthDelimited!==!1&&rt.ldelim()},(tt,rt,nt={})=>{const ot={value:0},it=rt==null?tt.len:tt.pos+rt;for(;tt.pos>>3){case 1:{ot.value=tt.uint32();break}case 2:{ot.expiry=tt.uint64();break}default:{tt.skipType(st&7);break}}}return ot})),o),et.encode=tt=>encodeMessage(tt,et.codec()),et.decode=(tt,rt)=>decodeMessage(tt,et.codec(),rt)})(Tag||(Tag={}));function bytesToPeer(et,o){const tt=Peer.decode(o);if(tt.publicKey!=null&&et.publicKey==null){const ot=publicKeyFromProtobuf(tt.publicKey);et=peerIdFromPublicKey(ot)}const rt=new Map,nt=BigInt(Date.now());for(const[ot,it]of tt.tags.entries())it.expiry!=null&&it.expiry({multiaddr:multiaddr(ot),isCertified:it??!1})),metadata:tt.metadata,peerRecordEnvelope:tt.peerRecordEnvelope??void 0,tags:rt}}function coerce$5(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$9(et){return new TextEncoder().encode(et)}function toString$d(et){return new TextDecoder().decode(et)}function base$4(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$5=base$4,_brrp__multiformats_scope_baseX$4=src$5;let Encoder$4=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$4=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$4(this,o)}},ComposedDecoder$4=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$4(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$4(et,o){return new ComposedDecoder$4({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$4=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$4(o,tt,rt),this.decoder=new Decoder$4(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$5({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$4(et,o,tt,rt)}function baseX$4({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$4(tt,et);return from$5({prefix:o,name:et,encode:rt,decode:ot=>coerce$5(nt(ot))})}function decode$e(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$d(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$4=alphabet$4.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$c(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$4[tt],o),"")}function decode$d(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$4[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$8=from$5({prefix:"🚀",name:"base256emoji",encode:encode$c,decode:decode$d}),base256emoji$9=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$8},Symbol.toStringTag,{value:"Module"})),base32$a=rfc4648$4({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$4=rfc4648$4({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$4=rfc4648$4({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$4=rfc4648$4({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$4=rfc4648$4({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$4=rfc4648$4({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$4=rfc4648$4({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$4=rfc4648$4({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$4=rfc4648$4({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$b=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$a,base32hex:base32hex$4,base32hexpad:base32hexpad$4,base32hexpadupper:base32hexpadupper$4,base32hexupper:base32hexupper$4,base32pad:base32pad$4,base32padupper:base32padupper$4,base32upper:base32upper$4,base32z:base32z$4},Symbol.toStringTag,{value:"Module"})),base36$8=baseX$4({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$4=baseX$4({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$9=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$8,base36upper:base36upper$4},Symbol.toStringTag,{value:"Module"})),base58btc$4=baseX$4({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$4=baseX$4({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$4=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$4,base58flickr:base58flickr$4},Symbol.toStringTag,{value:"Module"})),base64$a=rfc4648$4({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$4=rfc4648$4({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$4=rfc4648$4({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$4=rfc4648$4({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$b=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$a,base64pad:base64pad$4,base64url:base64url$4,base64urlpad:base64urlpad$4},Symbol.toStringTag,{value:"Module"})),base8$8=rfc4648$4({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$9=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$8},Symbol.toStringTag,{value:"Module"})),identity$4=from$5({prefix:"\0",name:"identity",encode:et=>toString$d(et),decode:et=>fromString$9(et)}),identityBase$4=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$4},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$4={...identityBase$4,...base2$9,...base8$9,...base10$9,...base16$9,...base32$b,...base36$9,...base58$4,...base64$b,...base256emoji$9};function allocUnsafe$3(et=0){return new Uint8Array(et)}function createCodec$4(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$7=createCodec$4("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$4=createCodec$4("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$3(et.length);for(let tt=0;tt1&&this._buf[this._buf.byteLength-1]===pathSep;)this._buf=this._buf.subarray(0,-1)}less(o){const tt=this.list(),rt=o.list();for(let nt=0;ntit)return!1}return tt.lengthtt.namespaces()))])}}function namespaceType(et){const o=et.split(":");return o.length<2?"":o.slice(0,-1).join(":")}function namespaceValue(et){const o=et.split(":");return o[o.length-1]}function flatten(et){return[].concat(...et)}const NAMESPACE_COMMON="/peers/";function peerIdToDatastoreKey(et){if(!isPeerId(et)||et.type==null)throw new InvalidParametersError("Invalid PeerId");const o=et.toCID().toString();return new Key(`${NAMESPACE_COMMON}${o}`)}async function dedupeFilterAndSortAddresses(et,o,tt){const rt=new Map;for(const nt of tt){if(nt==null)continue;if(nt.multiaddr instanceof Uint8Array&&(nt.multiaddr=multiaddr(nt.multiaddr)),!isMultiaddr(nt.multiaddr))throw new InvalidParametersError("Multiaddr was invalid");if(!await o(et,nt.multiaddr))continue;const ot=nt.isCertified??!1,it=nt.multiaddr.toString(),st=rt.get(it);st!=null?nt.isCertified=st.isCertified||ot:rt.set(it,{multiaddr:nt.multiaddr,isCertified:ot})}return[...rt.values()].sort((nt,ot)=>nt.multiaddr.toString().localeCompare(ot.multiaddr.toString())).map(({isCertified:nt,multiaddr:ot})=>({isCertified:nt,multiaddr:ot.bytes}))}async function toPeerPB(et,o,tt,rt){if(o==null)throw new InvalidParametersError("Invalid PeerData");if(o.publicKey!=null&&et.publicKey!=null&&!o.publicKey.equals(et.publicKey))throw new InvalidParametersError("publicKey bytes do not match peer id publicKey bytes");const nt=rt.existingPeer;if(nt!=null&&!et.equals(nt.id))throw new InvalidParametersError("peer id did not match existing peer id");let ot=(nt==null?void 0:nt.addresses)??[],it=new Set((nt==null?void 0:nt.protocols)??[]),st=(nt==null?void 0:nt.metadata)??new Map,at=(nt==null?void 0:nt.tags)??new Map,ct=nt==null?void 0:nt.peerRecordEnvelope;if(tt==="patch"){if((o.multiaddrs!=null||o.addresses!=null)&&(ot=[],o.multiaddrs!=null&&ot.push(...o.multiaddrs.map(ht=>({isCertified:!1,multiaddr:ht}))),o.addresses!=null&&ot.push(...o.addresses)),o.protocols!=null&&(it=new Set(o.protocols)),o.metadata!=null){const ht=o.metadata instanceof Map?[...o.metadata.entries()]:Object.entries(o.metadata);st=createSortedMap(ht,{validate:validateMetadata})}if(o.tags!=null){const ht=o.tags instanceof Map?[...o.tags.entries()]:Object.entries(o.tags);at=createSortedMap(ht,{validate:validateTag,map:mapTag})}o.peerRecordEnvelope!=null&&(ct=o.peerRecordEnvelope)}if(tt==="merge"){if(o.multiaddrs!=null&&ot.push(...o.multiaddrs.map(ht=>({isCertified:!1,multiaddr:ht}))),o.addresses!=null&&ot.push(...o.addresses),o.protocols!=null&&(it=new Set([...it,...o.protocols])),o.metadata!=null){const ht=o.metadata instanceof Map?[...o.metadata.entries()]:Object.entries(o.metadata);for(const[mt,ft]of ht)ft==null?st.delete(mt):st.set(mt,ft);st=createSortedMap([...st.entries()],{validate:validateMetadata})}if(o.tags!=null){const ht=o.tags instanceof Map?[...o.tags.entries()]:Object.entries(o.tags),mt=new Map(at);for(const[ft,pt]of ht)pt==null?mt.delete(ft):mt.set(ft,pt);at=createSortedMap([...mt.entries()],{validate:validateTag,map:mapTag})}o.peerRecordEnvelope!=null&&(ct=o.peerRecordEnvelope)}let lt;(nt==null?void 0:nt.id.publicKey)!=null?lt=publicKeyToProtobuf(nt.id.publicKey):o.publicKey!=null?lt=publicKeyToProtobuf(o.publicKey):et.publicKey!=null&&(lt=publicKeyToProtobuf(et.publicKey));const dt={addresses:await dedupeFilterAndSortAddresses(et,rt.addressFilter??(async()=>!0),ot),protocols:[...it.values()].sort((ht,mt)=>ht.localeCompare(mt)),metadata:st,tags:at,publicKey:lt,peerRecordEnvelope:ct};return et.type!=="RSA"&&delete dt.publicKey,dt}function createSortedMap(et,o){var rt;const tt=new Map;for(const[nt,ot]of et)ot!=null&&o.validate(nt,ot);for(const[nt,ot]of et.sort(([it],[st])=>it.localeCompare(st)))ot!=null&&tt.set(nt,((rt=o.map)==null?void 0:rt.call(o,nt,ot))??ot);return tt}function validateMetadata(et,o){if(typeof et!="string")throw new InvalidParametersError("Metadata key must be a string");if(!(o instanceof Uint8Array))throw new InvalidParametersError("Metadata value must be a Uint8Array")}function validateTag(et,o){if(typeof et!="string")throw new InvalidParametersError("Tag name must be a string");if(o.value!=null){if(parseInt(`${o.value}`,10)!==o.value)throw new InvalidParametersError("Tag value must be an integer");if(o.value<0||o.value>100)throw new InvalidParametersError("Tag value must be between 0-100")}if(o.ttl!=null){if(parseInt(`${o.ttl}`,10)!==o.ttl)throw new InvalidParametersError("Tag ttl must be an integer");if(o.ttl<0)throw new InvalidParametersError("Tag ttl must be between greater than 0")}}function mapTag(et,o){let tt;return o.expiry!=null&&(tt=o.expiry),o.ttl!=null&&(tt=BigInt(Date.now()+Number(o.ttl))),{value:o.value??0,expiry:tt}}function decodePeer(et,o,tt){const rt=et.toString().split("/")[2],nt=CID.parse(rt,base32$c),ot=peerIdFromCID(nt),it=tt.get(ot);if(it!=null)return it;const st=bytesToPeer(ot,o);return tt.set(ot,st),st}function mapQuery(et,o){return et==null?{}:{prefix:NAMESPACE_COMMON,filters:(et.filters??[]).map(tt=>({key:rt,value:nt})=>tt(decodePeer(rt,nt,o))),orders:(et.orders??[]).map(tt=>(rt,nt)=>tt(decodePeer(rt.key,rt.value,o),decodePeer(nt.key,nt.value,o)))}}var rn,rs,ns;class PersistentStore{constructor(o,tt={}){hr(this,rn);wt(this,"peerId");wt(this,"datastore");wt(this,"lock");wt(this,"addressFilter");this.peerId=o.peerId,this.datastore=o.datastore,this.addressFilter=tt.addressFilter,this.lock=createMortice({name:"peer-store",singleProcess:!0})}async has(o){return this.datastore.has(peerIdToDatastoreKey(o))}async delete(o){if(this.peerId.equals(o))throw new InvalidParametersError("Cannot delete self peer");await this.datastore.delete(peerIdToDatastoreKey(o))}async load(o){const tt=await this.datastore.get(peerIdToDatastoreKey(o));return bytesToPeer(o,tt)}async save(o,tt){const{existingBuf:rt,existingPeer:nt}=await fr(this,rn,rs).call(this,o),ot=await toPeerPB(o,tt,"patch",{addressFilter:this.addressFilter});return fr(this,rn,ns).call(this,o,ot,rt,nt)}async patch(o,tt){const{existingBuf:rt,existingPeer:nt}=await fr(this,rn,rs).call(this,o),ot=await toPeerPB(o,tt,"patch",{addressFilter:this.addressFilter,existingPeer:nt});return fr(this,rn,ns).call(this,o,ot,rt,nt)}async merge(o,tt){const{existingBuf:rt,existingPeer:nt}=await fr(this,rn,rs).call(this,o),ot=await toPeerPB(o,tt,"merge",{addressFilter:this.addressFilter,existingPeer:nt});return fr(this,rn,ns).call(this,o,ot,rt,nt)}async*all(o){const tt=new PeerMap;for await(const{key:rt,value:nt}of this.datastore.query(mapQuery(o??{},tt))){const ot=decodePeer(rt,nt,tt);ot.id.equals(this.peerId)||(yield ot)}}}rn=new WeakSet,rs=async function(o){try{const tt=await this.datastore.get(peerIdToDatastoreKey(o)),rt=bytesToPeer(o,tt);return{existingBuf:tt,existingPeer:rt}}catch(tt){if(tt.name!=="NotFoundError")throw tt}return{}},ns=async function(o,tt,rt,nt){const ot=Peer.encode(tt);return rt!=null&&equals(ot,rt)?{peer:bytesToPeer(o,ot),previous:nt,updated:!1}:(await this.datastore.put(peerIdToDatastoreKey(o),ot),{peer:bytesToPeer(o,ot),previous:nt,updated:!0})};var Ul,no,os;Ul=Symbol.toStringTag;class PersistentPeerStore{constructor(o,tt={}){hr(this,no);wt(this,"store");wt(this,"events");wt(this,"peerId");wt(this,"log");wt(this,Ul,"@libp2p/peer-store");this.log=o.logger.forComponent("libp2p:peer-store"),this.events=o.events,this.peerId=o.peerId,this.store=new PersistentStore(o,tt)}async forEach(o,tt){this.log.trace("forEach await read lock");const rt=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(const nt of this.store.all(tt))o(nt)}finally{this.log.trace("forEach release read lock"),rt()}}async all(o){this.log.trace("all await read lock");const tt=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await all$2(this.store.all(o))}finally{this.log.trace("all release read lock"),tt()}}async delete(o){this.log.trace("delete await write lock");const tt=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(o)}finally{this.log.trace("delete release write lock"),tt()}}async has(o){this.log.trace("has await read lock");const tt=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(o)}finally{this.log.trace("has release read lock"),tt()}}async get(o){this.log.trace("get await read lock");const tt=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(o)}finally{this.log.trace("get release read lock"),tt()}}async save(o,tt){this.log.trace("save await write lock");const rt=await this.store.lock.writeLock();this.log.trace("save got write lock");try{const nt=await this.store.save(o,tt);return fr(this,no,os).call(this,o,nt),nt.peer}finally{this.log.trace("save release write lock"),rt()}}async patch(o,tt){this.log.trace("patch await write lock");const rt=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{const nt=await this.store.patch(o,tt);return fr(this,no,os).call(this,o,nt),nt.peer}finally{this.log.trace("patch release write lock"),rt()}}async merge(o,tt){this.log.trace("merge await write lock");const rt=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{const nt=await this.store.merge(o,tt);return fr(this,no,os).call(this,o,nt),nt.peer}finally{this.log.trace("merge release write lock"),rt()}}async consumePeerRecord(o,tt){const rt=await RecordEnvelope.openAndCertify(o,PeerRecord.DOMAIN),nt=peerIdFromCID(rt.publicKey.toCID());if((tt==null?void 0:tt.equals(nt))===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",tt,nt),!1;const ot=PeerRecord.createFromProtobuf(rt.payload);let it;try{it=await this.get(nt)}catch(st){if(st.name!=="NotFoundError")throw st}if((it==null?void 0:it.peerRecordEnvelope)!=null){const st=await RecordEnvelope.createFromProtobuf(it.peerRecordEnvelope),at=PeerRecord.createFromProtobuf(st.payload);if(at.seqNumber>=ot.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",at.seqNumber,ot.seqNumber),!1}return await this.patch(ot.peerId,{peerRecordEnvelope:o,addresses:ot.multiaddrs.map(st=>({isCertified:!0,multiaddr:st}))}),!0}}no=new WeakSet,os=function(o,tt){tt.updated&&(this.peerId.equals(o)?this.events.safeDispatchEvent("self:peer:update",{detail:tt}):this.events.safeDispatchEvent("peer:update",{detail:tt}))};function persistentPeerStore(et,o={}){return new PersistentPeerStore(et,o)}const Ln=class Ln extends Error{constructor(tt="Not Found"){super(tt);wt(this,"name",Ln.name);wt(this,"code",Ln.code)}};wt(Ln,"name","NotFoundError"),wt(Ln,"code","ERR_NOT_FOUND");let NotFoundError=Ln;function peekable(et){const[o,tt]=et[Symbol.asyncIterator]!=null?[et[Symbol.asyncIterator](),Symbol.asyncIterator]:[et[Symbol.iterator](),Symbol.iterator],rt=[];return{peek:()=>o.next(),push:nt=>{rt.push(nt)},next:()=>rt.length>0?{done:!1,value:rt.shift()}:o.next(),[tt](){return this}}}function isAsyncIterable$2(et){return et[Symbol.asyncIterator]!=null}function filter(et,o){let tt=0;if(isAsyncIterable$2(et))return async function*(){for await(const at of et)await o(at,tt++)&&(yield at)}();const rt=peekable(et),{value:nt,done:ot}=rt.next();if(ot===!0)return function*(){}();const it=o(nt,tt++);if(typeof it.then=="function")return async function*(){await it&&(yield nt);for await(const at of rt)await o(at,tt++)&&(yield at)}();const st=o;return function*(){it===!0&&(yield nt);for(const at of rt)st(at,tt++)&&(yield at)}()}function isAsyncIterable$1(et){return et[Symbol.asyncIterator]!=null}function sort(et,o){return isAsyncIterable$1(et)?async function*(){yield*(await all$2(et)).sort(o)}():function*(){yield*all$2(et).sort(o)}()}function isAsyncIterable(et){return et[Symbol.asyncIterator]!=null}function take(et,o){return isAsyncIterable(et)?async function*(){let tt=0;if(!(o<1)){for await(const rt of et)if(yield rt,tt++,tt===o)return}}():function*(){let tt=0;if(!(o<1)){for(const rt of et)if(yield rt,tt++,tt===o)return}}()}class BaseDatastore{put(o,tt,rt){return Promise.reject(new Error(".put is not implemented"))}get(o,tt){return Promise.reject(new Error(".get is not implemented"))}has(o,tt){return Promise.reject(new Error(".has is not implemented"))}delete(o,tt){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(o,tt={}){for await(const{key:rt,value:nt}of o)await this.put(rt,nt,tt),yield rt}async*getMany(o,tt={}){for await(const rt of o)yield{key:rt,value:await this.get(rt,tt)}}async*deleteMany(o,tt={}){for await(const rt of o)await this.delete(rt,tt),yield rt}batch(){let o=[],tt=[];return{put(rt,nt){o.push({key:rt,value:nt})},delete(rt){tt.push(rt)},commit:async rt=>{await drain(this.putMany(o,rt)),o=[],await drain(this.deleteMany(tt,rt)),tt=[]}}}async*_all(o,tt){throw new Error("._all is not implemented")}async*_allKeys(o,tt){throw new Error("._allKeys is not implemented")}query(o,tt){let rt=this._all(o,tt);if(o.prefix!=null){const nt=o.prefix;rt=filter(rt,ot=>ot.key.toString().startsWith(nt))}if(Array.isArray(o.filters)&&(rt=o.filters.reduce((nt,ot)=>filter(nt,ot),rt)),Array.isArray(o.orders)&&(rt=o.orders.reduce((nt,ot)=>sort(nt,ot),rt)),o.offset!=null){let nt=0;const ot=o.offset;rt=filter(rt,()=>nt++>=ot)}return o.limit!=null&&(rt=take(rt,o.limit)),rt}queryKeys(o,tt){let rt=this._allKeys(o,tt);if(o.prefix!=null){const nt=o.prefix;rt=filter(rt,ot=>ot.toString().startsWith(nt))}if(Array.isArray(o.filters)&&(rt=o.filters.reduce((nt,ot)=>filter(nt,ot),rt)),Array.isArray(o.orders)&&(rt=o.orders.reduce((nt,ot)=>sort(nt,ot),rt)),o.offset!=null){const nt=o.offset;let ot=0;rt=filter(rt,()=>ot++>=nt)}return o.limit!=null&&(rt=take(rt,o.limit)),rt}}class MemoryDatastore extends BaseDatastore{constructor(){super();wt(this,"data");this.data=new Map}put(tt,rt){return this.data.set(tt.toString(),rt),tt}get(tt){const rt=this.data.get(tt.toString());if(rt==null)throw new NotFoundError;return rt}has(tt){return this.data.has(tt.toString())}delete(tt){this.data.delete(tt.toString())}*_all(){for(const[tt,rt]of this.data.entries())yield{key:new Key(tt),value:rt}}*_allKeys(){for(const tt of this.data.keys())yield new Key(tt)}}function allocUnsafe$2(et=0){return new Uint8Array(et)}function asUint8Array(et){return et}function concat(et,o){o==null&&(o=et.reduce((nt,ot)=>nt+ot.length,0));const tt=allocUnsafe$2(o);let rt=0;for(const nt of et)tt.set(nt,rt),rt+=nt.length;return tt}function coerce$4(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$7(et){return new TextEncoder().encode(et)}function toString$b(et){return new TextDecoder().decode(et)}function base$3(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$4=base$3,_brrp__multiformats_scope_baseX$3=src$4;let Encoder$3=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$3=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$3(this,o)}},ComposedDecoder$3=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$3(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$3(et,o){return new ComposedDecoder$3({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$3=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$3(o,tt,rt),this.decoder=new Decoder$3(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$4({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$3(et,o,tt,rt)}function baseX$3({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$3(tt,et);return from$4({prefix:o,name:et,encode:rt,decode:ot=>coerce$4(nt(ot))})}function decode$c(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$b(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$3=alphabet$3.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$a(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$3[tt],o),"")}function decode$b(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$3[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$6=from$4({prefix:"🚀",name:"base256emoji",encode:encode$a,decode:decode$b}),base256emoji$7=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$6},Symbol.toStringTag,{value:"Module"})),base32$8=rfc4648$3({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$3=rfc4648$3({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$3=rfc4648$3({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$3=rfc4648$3({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$3=rfc4648$3({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$3=rfc4648$3({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$3=rfc4648$3({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$3=rfc4648$3({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$3=rfc4648$3({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$9=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$8,base32hex:base32hex$3,base32hexpad:base32hexpad$3,base32hexpadupper:base32hexpadupper$3,base32hexupper:base32hexupper$3,base32pad:base32pad$3,base32padupper:base32padupper$3,base32upper:base32upper$3,base32z:base32z$3},Symbol.toStringTag,{value:"Module"})),base36$6=baseX$3({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$3=baseX$3({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$7=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$6,base36upper:base36upper$3},Symbol.toStringTag,{value:"Module"})),base58btc$3=baseX$3({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$3=baseX$3({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$3=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$3,base58flickr:base58flickr$3},Symbol.toStringTag,{value:"Module"})),base64$8=rfc4648$3({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$3=rfc4648$3({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$3=rfc4648$3({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$3=rfc4648$3({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$9=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$8,base64pad:base64pad$3,base64url:base64url$3,base64urlpad:base64urlpad$3},Symbol.toStringTag,{value:"Module"})),base8$6=rfc4648$3({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$7=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$6},Symbol.toStringTag,{value:"Module"})),identity$3=from$4({prefix:"\0",name:"identity",encode:et=>toString$b(et),decode:et=>fromString$7(et)}),identityBase$3=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$3},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$3={...identityBase$3,...base2$7,...base8$7,...base10$7,...base16$7,...base32$9,...base36$7,...base58$3,...base64$9,...base256emoji$7};function createCodec$3(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$6=createCodec$3("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$3=createCodec$3("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$2(et.length);for(let tt=0;ttet;function stripPeerId(et,o){const tt=et.getPeerId();return tt!=null&&peerIdFromString$1(tt).equals(o)&&(et=et.decapsulate(multiaddr(`/p2p/${o.toString()}`))),et}var zl;zl=Symbol.toStringTag;class DefaultAddressManager{constructor(o,tt={}){wt(this,"log");wt(this,"components");wt(this,"listen");wt(this,"announce");wt(this,"observed");wt(this,"announceFilter");wt(this,zl,"@libp2p/address-manager");const{listen:rt=[],announce:nt=[]}=tt;this.components=o,this.log=o.logger.forComponent("libp2p:address-manager"),this.listen=rt.map(ot=>ot.toString()),this.announce=new Set(nt.map(ot=>ot.toString())),this.observed=new Map,this.announceFilter=tt.announceFilter??defaultAddressFilter,this._updatePeerStoreAddresses=debounce(this._updatePeerStoreAddresses.bind(this),1e3),o.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),o.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){const o=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([tt,rt])=>rt.confident).map(([tt])=>multiaddr(tt))).map(tt=>tt.getPeerId()===this.components.peerId.toString()?tt.decapsulate(`/p2p/${this.components.peerId.toString()}`):tt);this.components.peerStore.patch(this.components.peerId,{multiaddrs:o}).catch(tt=>{this.log.error("error updating addresses",tt)})}getListenAddrs(){return Array.from(this.listen).map(o=>multiaddr(o))}getAnnounceAddrs(){return Array.from(this.announce).map(o=>multiaddr(o))}getObservedAddrs(){return Array.from(this.observed).map(([o])=>multiaddr(o))}addObservedAddr(o){o=stripPeerId(o,this.components.peerId);const tt=o.toString();this.observed.has(tt)||this.observed.set(tt,{confident:!1})}confirmObservedAddr(o){o=stripPeerId(o,this.components.peerId);const tt=o.toString(),nt=(this.observed.get(tt)??{confident:!1}).confident;this.observed.set(tt,{confident:!0}),nt||this._updatePeerStoreAddresses()}removeObservedAddr(o){o=stripPeerId(o,this.components.peerId);const tt=o.toString();this.observed.delete(tt)}getAddresses(){let o=this.getAnnounceAddrs().map(rt=>rt.toString());o.length===0&&(o=this.components.transportManager.getAddrs().map(rt=>rt.toString())),o=o.concat(Array.from(this.observed).filter(([rt,nt])=>nt.confident).map(([rt])=>rt));const tt=new Set(o);return this.announceFilter(Array.from(tt).map(rt=>multiaddr(rt))).map(rt=>{var nt;return((nt=rt.protos().pop())==null?void 0:nt.path)===!0||rt.getPeerId()===this.components.peerId.toString()?rt:rt.encapsulate(`/p2p/${this.components.peerId.toString()}`)})}}var messages;(function(et){et.NOT_STARTED_YET="The libp2p node is not started yet",et.NOT_FOUND="Not found"})(messages||(messages={}));class MissingServiceError extends Error{constructor(o="Missing service"){super(o),this.name="MissingServiceError"}}class UnmetServiceDependenciesError extends Error{constructor(o="Unmet service dependencies"){super(o),this.name="UnmetServiceDependenciesError"}}class NoContentRoutersError extends Error{constructor(o="No content routers available"){super(o),this.name="NoContentRoutersError"}}class NoPeerRoutersError extends Error{constructor(o="No peer routers available"){super(o),this.name="NoPeerRoutersError"}}class QueriedForSelfError extends Error{constructor(o="Should not try to find self"){super(o),this.name="QueriedForSelfError"}}class UnhandledProtocolError extends Error{constructor(o="Unhandled protocol error"){super(o),this.name="UnhandledProtocolError"}}class DuplicateProtocolHandlerError extends Error{constructor(o="Duplicate protocol handler error"){super(o),this.name="DuplicateProtocolHandlerError"}}class DialDeniedError extends Error{constructor(o="Dial denied error"){super(o),this.name="DialDeniedError"}}class NoValidAddressesError extends Error{constructor(o="No valid addresses"){super(o),this.name="NoValidAddressesError"}}class ConnectionInterceptedError extends Error{constructor(o="Connection intercepted"){super(o),this.name="ConnectionInterceptedError"}}class ConnectionDeniedError extends Error{constructor(o="Connection denied"){super(o),this.name="ConnectionDeniedError"}}class MuxerUnavailableError extends Error{constructor(o="Stream is not multiplexed"){super(o),this.name="MuxerUnavailableError"}}class EncryptionFailedError extends Error{constructor(o="Encryption failed"){super(o),this.name="EncryptionFailedError"}}class TransportUnavailableError extends Error{constructor(o="Transport unavailable"){super(o),this.name="TransportUnavailableError"}}class DefaultComponents{constructor(o={}){wt(this,"components",{});wt(this,"_started",!1);this.components={};for(const[tt,rt]of Object.entries(o))this.components[tt]=rt;this.components.logger==null&&(this.components.logger=defaultLogger())}isStarted(){return this._started}async _invokeStartableMethod(o){await Promise.all(Object.values(this.components).filter(tt=>isStartable(tt)).map(async tt=>{var rt;await((rt=tt[o])==null?void 0:rt.call(tt))}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const OPTIONAL_SERVICES=["metrics","connectionProtector","dns"],NON_SERVICE_PROPERTIES=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function defaultComponents(et={}){const o=new DefaultComponents(et);return new Proxy(o,{get(rt,nt,ot){if(typeof nt=="string"&&!NON_SERVICE_PROPERTIES.includes(nt)){const it=o.components[nt];if(it==null&&!OPTIONAL_SERVICES.includes(nt))throw new MissingServiceError(`${nt} not set`);return it}return Reflect.get(rt,nt,ot)},set(rt,nt,ot){return typeof nt=="string"?o.components[nt]=ot:Reflect.set(rt,nt,ot),!0}})}function checkServiceDependencies(et){const o={};for(const tt of Object.values(et.components))for(const rt of getServiceCapabilities(tt))o[rt]=!0;for(const tt of Object.values(et.components))for(const rt of getServiceDependencies(tt))if(o[rt]!==!0)throw new UnmetServiceDependenciesError(`Service "${getServiceName(tt)}" required capability "${rt}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function getServiceCapabilities(et){return Array.isArray(et==null?void 0:et[serviceCapabilities])?et[serviceCapabilities]:[]}function getServiceDependencies(et){return Array.isArray(et==null?void 0:et[serviceDependencies])?et[serviceDependencies]:[]}function getServiceName(et){return(et==null?void 0:et[Symbol.toStringTag])??(et==null?void 0:et.toString())??"unknown"}function connectionGater(et={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async o=>{const tt=o.stringTuples();return tt[0][0]===4||tt[0][0]===41?!!isPrivateIp(`${tt[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...et}}function getPeerAddress(et){if(isPeerId$1(et))return{peerId:et,multiaddrs:[]};Array.isArray(et)||(et=[et]);let o;if(et.length>0){const tt=et[0].getPeerId();o=tt==null?void 0:peerIdFromString$1(tt),et.forEach(rt=>{if(!isMultiaddr(rt))throw new InvalidMultiaddrError("Invalid multiaddr");const nt=rt.getPeerId();if(nt==null){if(o!=null)throw new InvalidParametersError$1("Multiaddrs must all have the same peer id or have no peer id")}else{const ot=peerIdFromString$1(nt);if((o==null?void 0:o.equals(ot))!==!0)throw new InvalidParametersError$1("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:o,multiaddrs:et}}const DEFAULT_CLOSABLE_PROTOCOLS=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function safelyCloseConnectionIfUnused(et,o){var nt;const tt=((nt=et==null?void 0:et.streams)==null?void 0:nt.map(ot=>ot.protocol))??[],rt=(o==null?void 0:o.closableProtocols)??DEFAULT_CLOSABLE_PROTOCOLS;if(!(tt.filter(ot=>ot!=null&&!rt.includes(ot)).length>0))try{await(et==null?void 0:et.close(o))}catch(ot){et==null||et.abort(ot)}}const DIAL_TIMEOUT=5e3,UPGRADE_TIMEOUT=3e3,PROTOCOL_NEGOTIATION_TIMEOUT=2e3,MAX_PEER_ADDRS_TO_DIAL=25,INBOUND_CONNECTION_THRESHOLD=5,MAX_INCOMING_PENDING_CONNECTIONS=10,MAX_PARALLEL_RECONNECTS=5,LAST_DIAL_FAILURE_KEY="last-dial-failure",LAST_DIAL_SUCCESS_KEY="last-dial-success",MAX_DIAL_QUEUE_LENGTH=500,MAX_CONNECTIONS=100,MAX_PARALLEL_DIALS=50,defaultOptions$2={maxConnections:MAX_CONNECTIONS,allow:[]};class ConnectionPruner{constructor(o,tt={}){wt(this,"maxConnections");wt(this,"connectionManager");wt(this,"peerStore");wt(this,"allow");wt(this,"events");wt(this,"log");this.maxConnections=tt.maxConnections??defaultOptions$2.maxConnections,this.allow=tt.allow??defaultOptions$2.allow,this.connectionManager=o.connectionManager,this.peerStore=o.peerStore,this.events=o.events,this.log=o.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(o=>{this.log.error("error while pruning connections %e",o)})}async _maybePruneConnections(){const o=this.connectionManager.getConnections(),tt=o.length;if(this.log("checking max connections limit %d/%d",tt,this.maxConnections),tt<=this.maxConnections)return;const rt=new PeerMap;for(const st of o){const at=st.remotePeer;if(!rt.has(at)){rt.set(at,0);try{const ct=await this.peerStore.get(at);rt.set(at,[...ct.tags.values()].reduce((lt,dt)=>lt+dt.value,0))}catch(ct){ct.name!=="NotFoundError"&&this.log.error("error loading peer tags",ct)}}}const nt=this.sortConnections(o,rt),ot=Math.max(tt-this.maxConnections,0),it=[];for(const st of nt)if(this.log("too many connections open - closing a connection to %p",st.remotePeer),this.allow.some(ct=>st.remoteAddr.toString().startsWith(ct.toString()))||it.push(st),it.length===ot)break;await Promise.all(it.map(async st=>{await safelyCloseConnectionIfUnused(st,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:it})}sortConnections(o,tt){return o.sort((rt,nt)=>{const ot=rt.timeline.open,it=nt.timeline.open;return otit?-1:0}).sort((rt,nt)=>rt.direction==="outbound"&&nt.direction==="inbound"?1:rt.direction==="inbound"&&nt.direction==="outbound"?-1:0).sort((rt,nt)=>rt.streams.length>nt.streams.length?1:rt.streams.length{const ot=tt.get(rt.remotePeer)??0,it=tt.get(nt.remotePeer)??0;return ot>it?1:ot{function st(){tt==null||tt.removeEventListener("abort",lt),et.removeEventListener(o,at),(rt==null?void 0:rt.errorEvent)!=null&&et.removeEventListener(rt.errorEvent,ct)}const at=dt=>{var ht;try{if(((ht=rt==null?void 0:rt.filter)==null?void 0:ht.call(rt,dt))===!1)return}catch(mt){st(),it(mt);return}st(),ot(dt)},ct=dt=>{st(),it(dt.detail)},lt=()=>{st(),it(nt)};tt==null||tt.addEventListener("abort",lt),et.addEventListener(o,at),(rt==null?void 0:rt.errorEvent)!=null&&et.addEventListener(rt.errorEvent,ct)})}class JobRecipient{constructor(o){wt(this,"deferred");wt(this,"signal");var tt;this.signal=o,this.deferred=pDefer(),this.onAbort=this.onAbort.bind(this),(tt=this.signal)==null||tt.addEventListener("abort",this.onAbort)}onAbort(){var o;this.deferred.reject(((o=this.signal)==null?void 0:o.reason)??new AbortError$6)}cleanup(){var o;(o=this.signal)==null||o.removeEventListener("abort",this.onAbort)}}function randomId(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}class Job{constructor(o,tt){wt(this,"id");wt(this,"fn");wt(this,"options");wt(this,"recipients");wt(this,"status");wt(this,"timeline");wt(this,"controller");this.id=randomId(),this.status="queued",this.fn=o,this.options=tt,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,setMaxListeners$2(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(o){this.controller.abort(o)}onAbort(){this.recipients.reduce((tt,rt)=>{var nt;return tt&&((nt=rt.signal)==null?void 0:nt.aborted)===!0},!0)&&(this.controller.abort(new AbortError$6),this.cleanup())}async join(o={}){var rt;const tt=new JobRecipient(o.signal);return this.recipients.push(tt),(rt=o.signal)==null||rt.addEventListener("abort",this.onAbort),tt.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const o=await raceSignal(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(tt=>{tt.deferred.resolve(o)}),this.status="complete"}catch(o){this.recipients.forEach(tt=>{tt.deferred.reject(o)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(o=>{var tt;o.cleanup(),(tt=o.signal)==null||tt.removeEventListener("abort",this.onAbort)})}}class Queue extends TypedEventEmitter$1{constructor(tt={}){var rt;super();wt(this,"concurrency");wt(this,"maxSize");wt(this,"queue");wt(this,"pending");wt(this,"sort");this.concurrency=tt.concurrency??Number.POSITIVE_INFINITY,this.maxSize=tt.maxSize??Number.POSITIVE_INFINITY,this.pending=0,tt.metricName!=null&&((rt=tt.metrics)==null||rt.registerMetricGroup(tt.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})})),this.sort=tt.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending{for(let rt=0;rt(this.safeDispatchEvent("completed",{detail:it}),this.safeDispatchEvent("success",{detail:{job:nt,result:it}}),it)).catch(it=>{if(nt.status==="queued"){for(let st=0;st{tt.abort(new AbortError$6)}),this.clear()}async onEmpty(tt){this.size!==0&&await raceEvent(this,"empty",tt==null?void 0:tt.signal)}async onSizeLessThan(tt,rt){this.sizethis.size{ht!=null?this.abort():this.clear(),rt.end(ht)},ot=ht=>{ht.detail!=null&&rt.push(ht.detail)},it=ht=>{nt(ht.detail)},st=()=>{nt()},at=()=>{nt(new AbortError$6("Queue aborted"))};this.addEventListener("completed",ot),this.addEventListener("error",it),this.addEventListener("idle",st),(lt=tt==null?void 0:tt.signal)==null||lt.addEventListener("abort",at);try{yield*rt}finally{this.removeEventListener("completed",ot),this.removeEventListener("error",it),this.removeEventListener("idle",st),(dt=tt==null?void 0:tt.signal)==null||dt.removeEventListener("abort",at),nt()}}}class PriorityQueue extends Queue{constructor(o={}){super({...o,sort:(tt,rt)=>tt.options.priority>rt.options.priority?-1:tt.options.prioritynt.toString())),rt}const defaultOptions$1={maxParallelDials:MAX_PARALLEL_DIALS,maxDialQueueLength:MAX_DIAL_QUEUE_LENGTH,maxPeerAddrsToDial:MAX_PEER_ADDRS_TO_DIAL,dialTimeout:DIAL_TIMEOUT,resolvers:{dnsaddr:dnsaddrResolver}};class DialQueue{constructor(o,tt={}){wt(this,"queue");wt(this,"components");wt(this,"addressSorter");wt(this,"maxPeerAddrsToDial");wt(this,"maxDialQueueLength");wt(this,"dialTimeout");wt(this,"shutDownController");wt(this,"connections");wt(this,"log");this.addressSorter=tt.addressSorter,this.maxPeerAddrsToDial=tt.maxPeerAddrsToDial??defaultOptions$1.maxPeerAddrsToDial,this.maxDialQueueLength=tt.maxDialQueueLength??defaultOptions$1.maxDialQueueLength,this.dialTimeout=tt.dialTimeout??defaultOptions$1.dialTimeout,this.connections=tt.connections??new PeerMap,this.log=o.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=o,this.shutDownController=new AbortController,setMaxListeners(1/0,this.shutDownController.signal);for(const[rt,nt]of Object.entries(tt.resolvers??{}))resolvers$1.set(rt,nt);this.queue=new PriorityQueue({concurrency:tt.maxParallelDials??defaultOptions$1.maxParallelDials,metricName:"libp2p_dial_queue",metrics:o.metrics}),this.queue.addEventListener("error",rt=>{rt.detail.name!==AbortError$4.name&&this.log.error("error in dial queue - %e",rt.detail)})}start(){this.shutDownController=new AbortController,setMaxListeners(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(o,tt={}){var st,at,ct;const{peerId:rt,multiaddrs:nt}=getPeerAddress(o),ot=Array.from(this.connections.values()).flat().find(lt=>tt.force===!0?!1:lt.remotePeer.equals(rt)?!0:nt.find(dt=>dt.equals(lt.remoteAddr)));if((ot==null?void 0:ot.status)==="open")return this.log("already connected to %a",ot.remoteAddr),(st=tt.onProgress)==null||st.call(tt,new CustomProgressEvent("dial-queue:already-connected")),ot;const it=this.queue.queue.find(lt=>{if((rt==null?void 0:rt.equals(lt.options.peerId))===!0)return!0;const dt=lt.options.multiaddrs;if(dt==null)return!1;for(const ht of nt)if(dt.has(ht.toString()))return!0;return!1});if(it!=null){this.log("joining existing dial target for %p",rt);for(const lt of nt)it.options.multiaddrs.add(lt.toString());return(at=tt.onProgress)==null||at.call(tt,new CustomProgressEvent("dial-queue:already-in-dial-queue")),it.join(tt)}if(this.queue.size>=this.maxDialQueueLength)throw new DialError("Dial queue is full");return this.log("creating dial target for %p",rt,nt.map(lt=>lt.toString())),(ct=tt.onProgress)==null||ct.call(tt,new CustomProgressEvent("dial-queue:add-to-dial-queue")),this.queue.add(async lt=>{var mt,ft;(mt=lt==null?void 0:lt.onProgress)==null||mt.call(lt,new CustomProgressEvent("dial-queue:start-dial"));const dt=this.createDialAbortController(lt==null?void 0:lt.signal);let ht;try{ht=await this.calculateMultiaddrs(rt,lt==null?void 0:lt.multiaddrs,{...lt,signal:dt}),(ft=lt==null?void 0:lt.onProgress)==null||ft.call(lt,new CustomProgressEvent("dial-queue:calculated-addresses",ht)),ht.map(({multiaddr:pt})=>pt.toString()).forEach(pt=>{lt==null||lt.multiaddrs.add(pt)})}catch(pt){throw dt.clear(),pt}try{let pt=0;const gt=[];for(const yt of ht){if(pt===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",pt,rt),new DialError("Peer had more than maxPeerAddrsToDial");pt++;try{const bt=await this.components.transportManager.dial(yt.multiaddr,{...lt,signal:dt});this.log("dial to %a succeeded",yt.multiaddr);try{await this.components.peerStore.merge(bt.remotePeer,{multiaddrs:[bt.remoteAddr],metadata:{[LAST_DIAL_SUCCESS_KEY]:fromString$6(Date.now().toString())}})}catch(xt){this.log.error("could not update last dial failure key for %p",rt,xt)}return bt}catch(bt){if(this.log.error("dial failed to %a",yt.multiaddr,bt),rt!=null)try{await this.components.peerStore.merge(rt,{metadata:{[LAST_DIAL_FAILURE_KEY]:fromString$6(Date.now().toString())}})}catch(xt){this.log.error("could not update last dial failure key for %p",rt,xt)}if(dt.aborted)throw new TimeoutError$2(bt.message);gt.push(bt)}}throw gt.length===1?gt[0]:new AggregateError(gt,"All multiaddr dials failed")}finally{dt.clear()}},{peerId:rt,priority:tt.priority??DEFAULT_DIAL_PRIORITY,multiaddrs:new Set(nt.map(lt=>lt.toString())),signal:tt.signal,onProgress:tt.onProgress})}createDialAbortController(o){const tt=anySignal([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,o]);return setMaxListeners(1/0,tt),tt}async calculateMultiaddrs(o,tt=new Set,rt={}){var dt,ht;const nt=[...tt].map(mt=>({multiaddr:multiaddr(mt),isCertified:!1}));if(o!=null){if(this.components.peerId.equals(o))throw new DialError("Tried to dial self");if(await((ht=(dt=this.components.connectionGater).denyDialPeer)==null?void 0:ht.call(dt,o))===!0)throw new DialDeniedError("The dial request is blocked by gater.allowDialPeer");if(nt.length===0){this.log("loading multiaddrs for %p",o);try{const mt=await this.components.peerStore.get(o);nt.push(...mt.addresses),this.log("loaded multiaddrs for %p",o,nt.map(({multiaddr:ft})=>ft.toString()))}catch(mt){if(mt.name!=="NotFoundError")throw mt}}if(nt.length===0){this.log("looking up multiaddrs for %p in the peer routing",o);try{const mt=await this.components.peerRouting.findPeer(o);this.log("found multiaddrs for %p in the peer routing",o,nt.map(({multiaddr:ft})=>ft.toString())),nt.push(...mt.multiaddrs.map(ft=>({multiaddr:ft,isCertified:!1})))}catch(mt){mt.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",o,mt)}}}let ot=(await Promise.all(nt.map(async mt=>{const ft=await resolveMultiaddrs(mt.multiaddr,{dns:this.components.dns,...rt,log:this.log});return ft.length===1&&ft[0].equals(mt.multiaddr)?mt:ft.map(pt=>({multiaddr:pt,isCertified:!1}))}))).flat();if(o!=null){const mt=`/p2p/${o.toString()}`;ot=ot.map(ft=>{const pt=ft.multiaddr.protos().pop();return(pt==null?void 0:pt.path)===!0?ft:ft.multiaddr.getPeerId()==null?{multiaddr:ft.multiaddr.encapsulate(mt),isCertified:ft.isCertified}:ft})}const it=ot.filter(mt=>{if(this.components.transportManager.dialTransportForMultiaddr(mt.multiaddr)==null)return!1;const ft=mt.multiaddr.getPeerId();return o!=null&&ft!=null?o.equals(ft):!0}),st=new Map;for(const mt of it){const ft=mt.multiaddr.toString(),pt=st.get(ft);if(pt!=null){pt.isCertified=pt.isCertified||mt.isCertified||!1;continue}st.set(ft,mt)}const at=[...st.values()];if(at.length===0)throw new NoValidAddressesError("The dial request has no valid addresses");const ct=[];for(const mt of at)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(mt.multiaddr)||ct.push(mt);const lt=this.addressSorter==null?defaultAddressSorter(ct):ct.sort(this.addressSorter);if(lt.length===0)throw new DialDeniedError("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",o??"unknown peer",ot.map(({multiaddr:mt})=>mt.toString())),this.log.trace("addresses for %p after filtering",o??"unknown peer",lt.map(({multiaddr:mt})=>mt.toString())),lt}async isDialable(o,tt={}){Array.isArray(o)||(o=[o]);try{const rt=await this.calculateMultiaddrs(void 0,new Set(o.map(nt=>nt.toString())),tt);return tt.runOnLimitedConnection===!1?rt.find(nt=>!Circuit.matches(nt.multiaddr))!=null:!0}catch(rt){this.log.trace("error calculating if multiaddr(s) were dialable",rt)}return!1}}class PeerQueue extends Queue{has(o){return this.find(o)!=null}find(o){return this.queue.find(tt=>o.equals(tt.options.peerId))}}var retry$2={};function RetryOperation(et,o){typeof o=="boolean"&&(o={forever:o}),this._originalTimeouts=JSON.parse(JSON.stringify(et)),this._timeouts=et,this._options=o||{},this._maxRetryTime=o&&o.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var retry_operation=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(et){if(this._timeout&&clearTimeout(this._timeout),!et)return!1;var o=new Date().getTime();if(et&&o-this._operationStart>=this._maxRetryTime)return this._errors.push(et),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(et);var tt=this._timeouts.shift();if(tt===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),tt=this._cachedTimeouts.slice(-1);else return!1;var rt=this;return this._timer=setTimeout(function(){rt._attempts++,rt._operationTimeoutCb&&(rt._timeout=setTimeout(function(){rt._operationTimeoutCb(rt._attempts)},rt._operationTimeout),rt._options.unref&&rt._timeout.unref()),rt._fn(rt._attempts)},tt),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(et,o){this._fn=et,o&&(o.timeout&&(this._operationTimeout=o.timeout),o.cb&&(this._operationTimeoutCb=o.cb));var tt=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){tt._operationTimeoutCb()},tt._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(et){console.log("Using RetryOperation.try() is deprecated"),this.attempt(et)};RetryOperation.prototype.start=function(et){console.log("Using RetryOperation.start() is deprecated"),this.attempt(et)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var et={},o=null,tt=0,rt=0;rt=tt&&(o=nt,tt=it)}return o};(function(et){var o=retry_operation;et.operation=function(tt){var rt=et.timeouts(tt);return new o(rt,{forever:tt&&(tt.forever||tt.retries===1/0),unref:tt&&tt.unref,maxRetryTime:tt&&tt.maxRetryTime})},et.timeouts=function(tt){if(tt instanceof Array)return[].concat(tt);var rt={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var nt in tt)rt[nt]=tt[nt];if(rt.minTimeout>rt.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var ot=[],it=0;itobjectToString.call(et)==="[object Error]",errorMessages=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function isNetworkError(et){return et&&isError(et)&&et.name==="TypeError"&&typeof et.message=="string"?et.message==="Load failed"?et.stack===void 0:errorMessages.has(et.message):!1}let AbortError$1=class extends Error{constructor(o){super(),o instanceof Error?(this.originalError=o,{message:o}=o):(this.originalError=new Error(o),this.originalError.stack=this.stack),this.name="AbortError",this.message=o}};const decorateErrorWithCounts=(et,o,tt)=>{const rt=tt.retries-(o-1);return et.attemptNumber=o,et.retriesLeft=rt,et};async function pRetry(et,o){return new Promise((tt,rt)=>{o={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...o};const nt=retry$1.operation(o),ot=()=>{var st;nt.stop(),rt((st=o.signal)==null?void 0:st.reason)};o.signal&&!o.signal.aborted&&o.signal.addEventListener("abort",ot,{once:!0});const it=()=>{var st;(st=o.signal)==null||st.removeEventListener("abort",ot),nt.stop()};nt.attempt(async st=>{try{const at=await et(st);it(),tt(at)}catch(at){try{if(!(at instanceof Error))throw new TypeError(`Non-error was thrown: "${at}". You should only throw errors.`);if(at instanceof AbortError$1)throw at.originalError;if(at instanceof TypeError&&!isNetworkError(at))throw at;if(decorateErrorWithCounts(at,st,o),await o.shouldRetry(at)||(nt.stop(),rt(at)),await o.onFailedAttempt(at),!nt.retry(at))throw nt.mainError()}catch(ct){decorateErrorWithCounts(ct,st,o),it(),rt(ct)}}})})}class ReconnectQueue{constructor(o,tt={}){wt(this,"log");wt(this,"queue");wt(this,"started");wt(this,"peerStore");wt(this,"retries");wt(this,"retryInterval");wt(this,"backoffFactor");wt(this,"connectionManager");wt(this,"events");this.log=o.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=o.peerStore,this.connectionManager=o.connectionManager,this.queue=new PeerQueue({concurrency:tt.maxParallelReconnects??MAX_PARALLEL_RECONNECTS,metricName:"libp2p_reconnect_queue",metrics:o.metrics}),this.started=!1,this.retries=tt.retries??5,this.backoffFactor=tt.backoffFactor,this.retryInterval=tt.retryInterval,this.events=o.events,o.events.addEventListener("peer:disconnect",rt=>{this.maybeReconnect(rt.detail).catch(nt=>{this.log.error("failed to maybe reconnect to %p - %e",rt.detail,nt)})})}async maybeReconnect(o){if(!this.started)return;const tt=await this.peerStore.get(o);hasKeepAliveTag(tt)&&(this.queue.has(o)||this.queue.add(async rt=>{await pRetry(async nt=>{if(this.started)try{await this.connectionManager.openConnection(o,{signal:rt==null?void 0:rt.signal})}catch(ot){throw this.log("reconnecting to %p attempt %d of %d failed - %e",o,nt,this.retries,ot),ot}},{signal:rt==null?void 0:rt.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:o}).catch(async rt=>{this.log.error("failed to reconnect to %p - %e",o,rt);const nt={};[...tt.tags.keys()].forEach(ot=>{ot.startsWith(KEEP_ALIVE)&&(nt[ot]=void 0)}),await this.peerStore.merge(o,{tags:nt}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:o})}).catch(async rt=>{this.log.error("failed to remove keep-alive tag from %p - %e",o,rt)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{const o=await this.peerStore.all({filters:[tt=>hasKeepAliveTag(tt)]});await Promise.all(o.map(async tt=>{await this.connectionManager.openConnection(tt.id).catch(rt=>{this.log.error(rt)})}))}).catch(o=>{this.log.error(o)})}stop(){this.started=!1,this.queue.abort()}}function hasKeepAliveTag(et){for(const o of et.tags.keys())if(o.startsWith(KEEP_ALIVE))return!0;return!1}const DEFAULT_DIAL_PRIORITY=50,defaultOptions={maxConnections:MAX_CONNECTIONS,inboundConnectionThreshold:INBOUND_CONNECTION_THRESHOLD,maxIncomingPendingConnections:MAX_INCOMING_PENDING_CONNECTIONS};var Vl;Vl=Symbol.toStringTag;class DefaultConnectionManager{constructor(o,tt={}){wt(this,"started");wt(this,"connections");wt(this,"allow");wt(this,"deny");wt(this,"maxIncomingPendingConnections");wt(this,"incomingPendingConnections");wt(this,"outboundPendingConnections");wt(this,"maxConnections");wt(this,"dialQueue");wt(this,"reconnectQueue");wt(this,"connectionPruner");wt(this,"inboundConnectionRateLimiter");wt(this,"peerStore");wt(this,"metrics");wt(this,"events");wt(this,"log");wt(this,"peerId");wt(this,Vl,"@libp2p/connection-manager");if(this.maxConnections=tt.maxConnections??defaultOptions.maxConnections,this.maxConnections<1)throw new InvalidParametersError$1("Connection Manager maxConnections must be greater than 0");this.connections=new PeerMap,this.started=!1,this.peerId=o.peerId,this.peerStore=o.peerStore,this.metrics=o.metrics,this.events=o.events,this.log=o.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(tt.allow??[]).map(rt=>multiaddr(rt)),this.deny=(tt.deny??[]).map(rt=>multiaddr(rt)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=tt.maxIncomingPendingConnections??defaultOptions.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new RateLimiter({points:tt.inboundConnectionThreshold??defaultOptions.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ConnectionPruner({connectionManager:this,peerStore:o.peerStore,events:o.events,logger:o.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new DialQueue(o,{addressSorter:tt.addressSorter,maxParallelDials:tt.maxParallelDials??MAX_PARALLEL_DIALS,maxDialQueueLength:tt.maxDialQueueLength??MAX_DIAL_QUEUE_LENGTH,maxPeerAddrsToDial:tt.maxPeerAddrsToDial??MAX_PEER_ADDRS_TO_DIAL,dialTimeout:tt.dialTimeout??DIAL_TIMEOUT,resolvers:tt.resolvers??{dnsaddr:dnsaddrResolver},connections:this.connections}),this.reconnectQueue=new ReconnectQueue({events:o.events,peerStore:o.peerStore,logger:o.logger,connectionManager:this},{retries:tt.reconnectRetries,retryInterval:tt.reconnectRetryInterval,backoffFactor:tt.reconnectBackoffFactor,maxParallelReconnects:tt.maxParallelReconnects})}async start(){var o,tt,rt;(o=this.metrics)==null||o.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const nt={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const ot of this.connections.values())for(const it of ot)nt[it.direction]++;return nt}}),(tt=this.metrics)==null||tt.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const nt={};for(const ot of this.connections.values())for(const it of ot)for(const st of it.streams){const at=`${st.direction} ${st.protocol??"unnegotiated"}`;nt[at]=(nt[at]??0)+1}return nt}}),(rt=this.metrics)==null||rt.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const nt={};for(const it of this.connections.values())for(const st of it){const at={};for(const ct of st.streams){const lt=`${ct.direction} ${ct.protocol??"unnegotiated"}`;at[lt]=(at[lt]??0)+1}for(const[ct,lt]of Object.entries(at))nt[ct]=nt[ct]??[],nt[ct].push(lt)}const ot={};for(let[it,st]of Object.entries(nt)){st=st.sort((ct,lt)=>ct-lt);const at=Math.floor(st.length*.9);ot[it]=st[at]}return ot}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await start(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await stop(this.reconnectQueue,this.dialQueue,this.connectionPruner);const o=[];for(const tt of this.connections.values())for(const rt of tt)o.push((async()=>{try{await rt.close()}catch(nt){this.log.error(nt)}})());this.log("closing %d connections",o.length),await Promise.all(o),this.connections.clear(),this.log("stopped")}onConnect(o){this._onConnect(o).catch(tt=>{this.log.error(tt)})}async _onConnect(o){const{detail:tt}=o;if(!this.started){await tt.close();return}if(tt.status!=="open")return;const rt=tt.remotePeer,nt=!this.connections.has(rt),ot=this.connections.get(rt)??[];ot.push(tt),this.connections.set(rt,ot),rt.publicKey!=null&&rt.type==="RSA"&&await this.peerStore.patch(rt,{publicKey:rt.publicKey}),nt&&this.events.safeDispatchEvent("peer:connect",{detail:tt.remotePeer})}onDisconnect(o){const{detail:tt}=o,rt=tt.remotePeer,ot=(this.connections.get(rt)??[]).filter(it=>it.id!==tt.id);this.connections.set(rt,ot),ot.length===0&&(this.log("onDisconnect remove all connections for peer %p",rt),this.connections.delete(rt),this.events.safeDispatchEvent("peer:disconnect",{detail:tt.remotePeer}))}getConnections(o){if(o!=null)return this.connections.get(o)??[];let tt=[];for(const rt of this.connections.values())tt=tt.concat(rt);return tt}getConnectionsMap(){return this.connections}async openConnection(o,tt={}){var rt,nt;if(!this.started)throw new NotStartedError("Not started");this.outboundPendingConnections++;try{(rt=tt.signal)==null||rt.throwIfAborted();const{peerId:ot}=getPeerAddress(o);if(this.peerId.equals(ot))throw new InvalidPeerIdError("Can not dial self");if(ot!=null&&tt.force!==!0){this.log("dial %p",ot);const ct=this.getConnections(ot).find(lt=>lt.limits==null);if(ct!=null)return this.log("had an existing non-limited connection to %p",ot),(nt=tt.onProgress)==null||nt.call(tt,new CustomProgressEvent("dial-queue:already-connected")),ct}const it=await this.dialQueue.dial(o,{...tt,priority:tt.priority??DEFAULT_DIAL_PRIORITY});if(it.status!=="open")throw new ConnectionClosedError("Remote closed connection during opening");let st=this.connections.get(it.remotePeer);st==null&&(st=[],this.connections.set(it.remotePeer,st));let at=!1;for(const ct of st)if(ct.id===it.id&&(at=!0),tt.force!==!0&&ct.id!==it.id&&ct.remoteAddr.equals(it.remoteAddr))return it.abort(new InvalidMultiaddrError("Duplicate multiaddr connection")),ct;return at||st.push(it),it}finally{this.outboundPendingConnections--}}async closeConnections(o,tt={}){const rt=this.connections.get(o)??[];await Promise.all(rt.map(async nt=>{try{await nt.close(tt)}catch(ot){nt.abort(ot)}}))}async acceptIncomingConnection(o){if(this.deny.some(nt=>o.remoteAddr.toString().startsWith(nt.toString())))return this.log("connection from %a refused - connection remote address was in deny list",o.remoteAddr),!1;if(this.allow.some(nt=>o.remoteAddr.toString().startsWith(nt.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",o.remoteAddr),!1;if(o.remoteAddr.isThinWaistAddress()){const nt=o.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(nt,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",o.remoteAddr,nt),!1}}return this.getConnections().length({id:tt.id,status:o[tt.status],peerId:tt.options.peerId,multiaddrs:[...tt.options.multiaddrs].map(rt=>multiaddr(rt))}))}async isDialable(o,tt={}){return this.dialQueue.isDialable(o,tt)}}class MovingAverage{constructor(o){wt(this,"movingAverage");wt(this,"variance");wt(this,"deviation");wt(this,"forecast");wt(this,"timespan");wt(this,"previousTime");this.timespan=o,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(o,tt){return 1-Math.exp(-(o-tt)/this.timespan)}push(o,tt=Date.now()){if(this.previousTime!=null){const rt=this.alpha(tt,this.previousTime),nt=o-this.movingAverage,ot=rt*nt;this.movingAverage=rt*o+(1-rt)*this.movingAverage,this.variance=(1-rt)*(this.variance+nt*ot),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+rt*nt}else this.movingAverage=o;this.previousTime=tt}}const DEFAULT_TIMEOUT_MULTIPLIER=1.2,DEFAULT_FAILURE_MULTIPLIER=2,DEFAULT_MIN_TIMEOUT=2e3;class AdaptiveTimeout{constructor(o={}){wt(this,"success");wt(this,"failure");wt(this,"next");wt(this,"metric");wt(this,"timeoutMultiplier");wt(this,"failureMultiplier");wt(this,"minTimeout");var tt;this.success=new MovingAverage(o.interval??5e3),this.failure=new MovingAverage(o.interval??5e3),this.next=new MovingAverage(o.interval??5e3),this.failureMultiplier=o.failureMultiplier??DEFAULT_FAILURE_MULTIPLIER,this.timeoutMultiplier=o.timeoutMultiplier??DEFAULT_TIMEOUT_MULTIPLIER,this.minTimeout=o.minTimeout??DEFAULT_MIN_TIMEOUT,o.metricName!=null&&(this.metric=(tt=o.metrics)==null?void 0:tt.registerMetricGroup(o.metricName))}getTimeoutSignal(o={}){const tt=Math.max(Math.round(this.next.movingAverage*(o.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),rt=AbortSignal.timeout(tt),nt=anySignal([o.signal,rt]);return setMaxListeners$2(1/0,nt,rt),nt.start=Date.now(),nt.timeout=tt,nt}cleanUp(o){var rt,nt;const tt=Date.now()-o.start;o.aborted?(this.failure.push(tt),this.next.push(tt*this.failureMultiplier),(rt=this.metric)==null||rt.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:tt})):(this.success.push(tt),this.next.push(tt),(nt=this.metric)==null||nt.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:tt}))}}const DEFAULT_PING_INTERVAL_MS=1e4,PROTOCOL_VERSION="1.0.0",PROTOCOL_NAME="ping",PROTOCOL_PREFIX="ipfs",PING_LENGTH=32,DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE=!0;var Hl,Wl;Wl=Symbol.toStringTag,Hl=serviceCapabilities;class ConnectionMonitor{constructor(o,tt={}){wt(this,"protocol");wt(this,"components");wt(this,"log");wt(this,"heartbeatInterval");wt(this,"pingIntervalMs");wt(this,"abortController");wt(this,"timeout");wt(this,"abortConnectionOnPingFailure");wt(this,Wl,"@libp2p/connection-monitor");wt(this,Hl,["@libp2p/connection-monitor"]);this.components=o,this.protocol=`/${tt.protocolPrefix??PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`,this.log=o.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=tt.pingInterval??DEFAULT_PING_INTERVAL_MS,this.abortConnectionOnPingFailure=tt.abortConnectionOnPingFailure??DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE,this.timeout=new AdaptiveTimeout({...tt.pingTimeout??{},metrics:o.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}start(){this.abortController=new AbortController,setMaxListeners(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(o=>{Promise.resolve().then(async()=>{var rt;let tt=Date.now();try{const nt=this.timeout.getTimeoutSignal({signal:(rt=this.abortController)==null?void 0:rt.signal}),ot=await o.newStream(this.protocol,{signal:nt,runOnLimitedConnection:!0}),it=byteStream(ot);tt=Date.now(),await Promise.all([it.write(randomBytes(PING_LENGTH),{signal:nt}),it.read(PING_LENGTH,{signal:nt})]),o.rtt=Date.now()-tt,await it.unwrap().close({signal:nt})}catch(nt){if(nt.name!=="UnsupportedProtocolError")throw nt;o.rtt=(Date.now()-tt)/2}}).catch(tt=>{this.log.error("error during heartbeat",tt),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),o.abort(tt)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){var o;(o=this.abortController)==null||o.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}}var Gl;Gl=Symbol.toStringTag;class CompoundContentRouting{constructor(o,tt){wt(this,"routers");wt(this,"started");wt(this,"components");wt(this,Gl,"@libp2p/content-routing");this.routers=tt.routers??[],this.started=!1,this.components=o}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(o,tt={}){if(this.routers.length===0)throw new NoContentRoutersError("No content routers available");const rt=this,nt=new PeerSet;for await(const ot of merge$2(...rt.routers.map(it=>it.findProviders(o,tt))))ot!=null&&(ot.multiaddrs.length>0&&await this.components.peerStore.merge(ot.id,{multiaddrs:ot.multiaddrs}),!nt.has(ot.id)&&(nt.add(ot.id),yield ot))}async provide(o,tt={}){if(this.routers.length===0)throw new NoContentRoutersError("No content routers available");await Promise.all(this.routers.map(async rt=>{await rt.provide(o,tt)}))}async put(o,tt,rt){if(!this.isStarted())throw new NotStartedError;await Promise.all(this.routers.map(async nt=>{await nt.put(o,tt,rt)}))}async get(o,tt){if(!this.isStarted())throw new NotStartedError;return Promise.any(this.routers.map(async rt=>rt.get(o,tt)))}}var Zl;Zl=Symbol.toStringTag;class DefaultPeerRouting{constructor(o,tt={}){wt(this,"log");wt(this,"peerId");wt(this,"peerStore");wt(this,"routers");wt(this,Zl,"@libp2p/peer-routing");this.log=o.logger.forComponent("libp2p:peer-routing"),this.peerId=o.peerId,this.peerStore=o.peerStore,this.routers=tt.routers??[]}async findPeer(o,tt){if(this.routers.length===0)throw new NoPeerRoutersError("No peer routers available");if(o.toString()===this.peerId.toString())throw new QueriedForSelfError("Should not try to find self");const rt=this,nt=merge$2(...this.routers.map(ot=>async function*(){try{yield await ot.findPeer(o,tt)}catch(it){rt.log.error(it)}}()));for await(const ot of nt)if(ot!=null)return ot.multiaddrs.length>0&&await this.peerStore.merge(ot.id,{multiaddrs:ot.multiaddrs}),ot;throw new NotFoundError$1}async*getClosestPeers(o,tt={}){if(this.routers.length===0)throw new NoPeerRoutersError("No peer routers available");const rt=this,nt=createScalableCuckooFilter(1024);for await(const ot of parallel(async function*(){const it=merge$2(...rt.routers.map(st=>st.getClosestPeers(o,tt)));for await(let st of it)yield async()=>{if(st.multiaddrs.length===0)try{st=await rt.findPeer(st.id,{...tt,useCache:!1})}catch(at){rt.log.error("could not find peer multiaddrs",at);return}return st}}()))ot!=null&&(ot.multiaddrs.length>0&&await this.peerStore.merge(ot.id,{multiaddrs:ot.multiaddrs}),!nt.has(ot.id.toMultihash().bytes)&&(nt.add(ot.id.toMultihash().bytes),yield ot))}}var Kl,Ql;class RandomWalk extends(Ql=TypedEventEmitter,Kl=Symbol.toStringTag,Ql){constructor(tt){super();wt(this,"peerRouting");wt(this,"log");wt(this,"walking");wt(this,"walkers");wt(this,"shutdownController");wt(this,"walkController");wt(this,"needNext");wt(this,Kl,"@libp2p/random-walk");this.log=tt.logger.forComponent("libp2p:random-walk"),this.peerRouting=tt.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,setMaxListeners(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,setMaxListeners(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(tt){var nt,ot;this.walking||this.startWalk(),this.walkers++;const rt=anySignal([this.shutdownController.signal,tt==null?void 0:tt.signal]);setMaxListeners(1/0,rt);try{for(;;)(nt=this.needNext)==null||nt.resolve(),this.needNext=pDefer(),yield(await raceEvent(this,"walk:peer",rt,{errorEvent:"walk:error"})).detail}finally{rt.clear(),this.walkers--,this.walkers===0&&((ot=this.walkController)==null||ot.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,setMaxListeners(1/0,this.walkController.signal);const tt=anySignal([this.walkController.signal,this.shutdownController.signal]);setMaxListeners(1/0,tt);const rt=Date.now();let nt=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{const ot=randomBytes(32);let it=Date.now();for await(const st of this.peerRouting.getClosestPeers(ot,{signal:tt}))tt.aborted&&this.log("aborting walk"),tt.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",st.id,Date.now()-it,this.walkers),nt++,this.safeDispatchEvent("walk:peer",{detail:st}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await raceSignal(this.needNext.promise,tt)),it=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",ot,this.walkers,nt)}catch(ot){this.log.error("randomwalk errored",ot),this.safeDispatchEvent("walk:error",{detail:ot})}this.log("no walkers left, ended walk")}).catch(ot=>{this.log.error("randomwalk errored",ot)}).finally(()=>{this.log("finished walk, found %d peers after %dms",nt,Date.now()-rt),this.walking=!1})}}const DEFAULT_MAX_INBOUND_STREAMS=32,DEFAULT_MAX_OUTBOUND_STREAMS=64;var Yl;Yl=Symbol.toStringTag;class DefaultRegistrar{constructor(o){wt(this,"log");wt(this,"topologies");wt(this,"handlers");wt(this,"components");wt(this,Yl,"@libp2p/registrar");this.log=o.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=o,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(o){const tt=this.handlers.get(o);if(tt==null)throw new UnhandledProtocolError(`No handler registered for protocol ${o}`);return tt}getTopologies(o){const tt=this.topologies.get(o);return tt==null?[]:[...tt.values()]}async handle(o,tt,rt){if(this.handlers.has(o))throw new DuplicateProtocolHandlerError(`Handler already registered for protocol ${o}`);const nt=mergeOptions$1.bind({ignoreUndefined:!0})({maxInboundStreams:DEFAULT_MAX_INBOUND_STREAMS,maxOutboundStreams:DEFAULT_MAX_OUTBOUND_STREAMS},rt);this.handlers.set(o,{handler:tt,options:nt}),await this.components.peerStore.merge(this.components.peerId,{protocols:[o]})}async unhandle(o){(Array.isArray(o)?o:[o]).forEach(rt=>{this.handlers.delete(rt)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(o,tt){if(tt==null)throw new InvalidParametersError$1("invalid topology");const rt=`${(Math.random()*1e9).toString(36)}${Date.now()}`;let nt=this.topologies.get(o);return nt==null&&(nt=new Map,this.topologies.set(o,nt)),nt.set(rt,tt),rt}unregister(o){for(const[tt,rt]of this.topologies.entries())rt.has(o)&&(rt.delete(o),rt.size===0&&this.topologies.delete(tt))}_onDisconnect(o){const tt=o.detail;this.components.peerStore.get(tt).then(rt=>{var nt,ot,it;for(const st of rt.protocols){const at=this.topologies.get(st);if(at!=null)for(const ct of at.values())((nt=ct.filter)==null?void 0:nt.has(tt))!==!1&&((ot=ct.filter)==null||ot.remove(tt),(it=ct.onDisconnect)==null||it.call(ct,tt))}}).catch(rt=>{rt.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",tt,rt)})}_onPeerUpdate(o){var ot,it,st;const{peer:tt,previous:rt}=o.detail,nt=((rt==null?void 0:rt.protocols)??[]).filter(at=>!tt.protocols.includes(at));for(const at of nt){const ct=this.topologies.get(at);if(ct!=null)for(const lt of ct.values())((ot=lt.filter)==null?void 0:ot.has(tt.id))!==!1&&((it=lt.filter)==null||it.remove(tt.id),(st=lt.onDisconnect)==null||st.call(lt,tt.id))}}_onPeerIdentify(o){var ot,it,st;const tt=o.detail.protocols,rt=o.detail.connection,nt=o.detail.peerId;for(const at of tt){const ct=this.topologies.get(at);if(ct!=null)for(const lt of ct.values())rt.limits!=null&<.notifyOnLimitedConnection!==!0||((ot=lt.filter)==null?void 0:ot.has(nt))!==!0&&((it=lt.filter)==null||it.add(nt),(st=lt.onConnect)==null||st.call(lt,nt,rt))}}}class TrackedMap extends Map{constructor(tt){super();wt(this,"metric");const{name:rt,metrics:nt}=tt;this.metric=nt.registerMetric(rt),this.updateComponentMetric()}set(tt,rt){return super.set(tt,rt),this.updateComponentMetric(),this}delete(tt){const rt=super.delete(tt);return this.updateComponentMetric(),rt}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function trackedMap(et){const{name:o,metrics:tt}=et;let rt;return tt!=null?rt=new TrackedMap({name:o,metrics:tt}):rt=new Map,rt}var Xl;Xl=Symbol.toStringTag;class DefaultTransportManager{constructor(o,tt={}){wt(this,"log");wt(this,"components");wt(this,"transports");wt(this,"listeners");wt(this,"faultTolerance");wt(this,"started");wt(this,Xl,"@libp2p/transport-manager");this.log=o.logger.forComponent("libp2p:transports"),this.components=o,this.started=!1,this.transports=new Map,this.listeners=trackedMap({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=tt.faultTolerance??FaultTolerance.FATAL_ALL}add(o){const tt=o[Symbol.toStringTag];if(tt==null)throw new InvalidParametersError$1("Transport must have a valid tag");if(this.transports.has(tt))throw new InvalidParametersError$1(`There is already a transport with the tag ${tt}`);this.log("adding transport %s",tt),this.transports.set(tt,o),this.listeners.has(tt)||this.listeners.set(tt,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const o=this.components.addressManager.getListenAddrs();await this.listen(o)}async stop(){const o=[];for(const[tt,rt]of this.listeners)for(this.log("closing listeners for %s",tt);rt.length>0;){const nt=rt.pop();nt!=null&&o.push(nt.close())}await Promise.all(o),this.log("all listeners closed");for(const tt of this.listeners.keys())this.listeners.set(tt,[]);this.started=!1}async dial(o,tt){var nt;const rt=this.dialTransportForMultiaddr(o);if(rt==null)throw new TransportUnavailableError(`No transport available for address ${String(o)}`);return(nt=tt==null?void 0:tt.onProgress)==null||nt.call(tt,new CustomProgressEvent("transport-manager:selected-transport",rt[Symbol.toStringTag])),rt.dial(o,{...tt,upgrader:this.components.upgrader})}getAddrs(){let o=[];for(const tt of this.listeners.values())for(const rt of tt)o=[...o,...rt.getAddrs()];return o}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(o){for(const tt of this.transports.values())if(tt.dialFilter([o]).length>0)return tt}listenTransportForMultiaddr(o){for(const tt of this.transports.values())if(tt.listenFilter([o]).length>0)return tt}async listen(o){if(!this.isStarted())throw new NotStartedError("Not started");if(o==null||o.length===0){this.log("no addresses were provided for listening, this node is dial only");return}const tt=[];for(const[rt,nt]of this.transports.entries()){const ot=nt.listenFilter(o),it=[];for(const ct of ot){this.log("creating listener for %s on %a",rt,ct);const lt=nt.createListener({upgrader:this.components.upgrader});let dt=this.listeners.get(rt)??[];dt==null&&(dt=[],this.listeners.set(rt,dt)),dt.push(lt),lt.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:lt})}),lt.addEventListener("close",()=>{const ht=dt.findIndex(mt=>mt===lt);dt.splice(ht,1),this.components.events.safeDispatchEvent("transport:close",{detail:lt})}),it.push(lt.listen(ct))}if(it.length===0){tt.push(rt);continue}if((await Promise.allSettled(it)).find(ct=>ct.status==="fulfilled")==null&&this.faultTolerance!==FaultTolerance.NO_FATAL)throw new NoValidAddressesError(`Transport (${rt}) could not listen on any available address`)}if(tt.length===this.transports.size){const rt=`no valid addresses were provided for transports [${tt.join(", ")}]`;if(this.faultTolerance===FaultTolerance.FATAL_ALL)throw new NoValidAddressesError(rt);this.log(`libp2p in dial mode only: ${rt}`)}}async remove(o){const tt=this.listeners.get(o)??[];this.log.trace("removing transport %s",o);const rt=[];for(this.log.trace("closing listeners for %s",o);tt.length>0;){const nt=tt.pop();nt!=null&&rt.push(nt.close())}await Promise.all(rt),this.transports.delete(o),this.listeners.delete(o)}async removeAll(){const o=[];for(const tt of this.transports.keys())o.push(this.remove(tt));await Promise.all(o)}}const PROTOCOL_ID="/multistream/1.0.0",MAX_PROTOCOL_LENGTH=1024;class UnsupportedProtocolError extends Error{constructor(o="Unsupported protocol error"){super(o),this.name="UnsupportedProtocolError"}}wt(UnsupportedProtocolError,"name","UnsupportedProtocolError");class InvalidMessageError extends Error{constructor(o="Invalid message"){super(o),this.name="InvalidMessageError"}}wt(InvalidMessageError,"name","InvalidMessageError");function coerce$3(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$5(et){return new TextEncoder().encode(et)}function toString$a(et){return new TextDecoder().decode(et)}function base$2(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$3=base$2,_brrp__multiformats_scope_baseX$2=src$3;let Encoder$2=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$2=class{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$2(this,o)}},ComposedDecoder$2=class{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or$2(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$2(et,o){return new ComposedDecoder$2({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}let Codec$2=class{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$2(o,tt,rt),this.decoder=new Decoder$2(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};function from$3({name:et,prefix:o,encode:tt,decode:rt}){return new Codec$2(et,o,tt,rt)}function baseX$2({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$2(tt,et);return from$3({prefix:o,name:et,encode:rt,decode:ot=>coerce$3(nt(ot))})}function decode$a(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$9(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes$2=alphabet$2.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode$8(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$2[tt],o),"")}function decode$9(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes$2[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji$4=from$3({prefix:"🚀",name:"base256emoji",encode:encode$8,decode:decode$9}),base256emoji$5=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$4},Symbol.toStringTag,{value:"Module"})),base32$6=rfc4648$2({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$2=rfc4648$2({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$2=rfc4648$2({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$2=rfc4648$2({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$2=rfc4648$2({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$2=rfc4648$2({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$2=rfc4648$2({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$2=rfc4648$2({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$2=rfc4648$2({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$7=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$6,base32hex:base32hex$2,base32hexpad:base32hexpad$2,base32hexpadupper:base32hexpadupper$2,base32hexupper:base32hexupper$2,base32pad:base32pad$2,base32padupper:base32padupper$2,base32upper:base32upper$2,base32z:base32z$2},Symbol.toStringTag,{value:"Module"})),base36$4=baseX$2({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$2=baseX$2({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$5=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$4,base36upper:base36upper$2},Symbol.toStringTag,{value:"Module"})),base58btc$2=baseX$2({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$2=baseX$2({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$2=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$2,base58flickr:base58flickr$2},Symbol.toStringTag,{value:"Module"})),base64$6=rfc4648$2({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$2=rfc4648$2({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$2=rfc4648$2({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$2=rfc4648$2({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$7=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$6,base64pad:base64pad$2,base64url:base64url$2,base64urlpad:base64urlpad$2},Symbol.toStringTag,{value:"Module"})),base8$4=rfc4648$2({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$5=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$4},Symbol.toStringTag,{value:"Module"})),identity$2=from$3({prefix:"\0",name:"identity",encode:et=>toString$a(et),decode:et=>fromString$5(et)}),identityBase$2=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$2},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$2={...identityBase$2,...base2$5,...base8$5,...base10$5,...base16$5,...base32$7,...base36$5,...base58$2,...base64$7,...base256emoji$5};function allocUnsafe$1(et=0){return new Uint8Array(et)}function createCodec$2(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$5=createCodec$2("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$2=createCodec$2("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$1(et.length);for(let tt=0;tt{const{sink:xt}=ft.unwrap();await xt(async function*(){let vt=!1;for await(const Et of bt){if(ct&&await lt.promise,at)yield Et;else{ct=!0,tt.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',PROTOCOL_ID,o,Et.byteLength);const Ct=`${o} +`;yield new Uint8ArrayList(Uint8Array.from([19]),fromString$4(`${PROTOCOL_ID} +`),encode$P(Ct.length),fromString$4(Ct),Et).subarray(),tt.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',PROTOCOL_ID,o,Et.byteLength),at=!0,ct=!1,lt.resolve(),pt().catch(St=>{tt.log.error("could not finish optimistic protocol negotiation of %s",o,St)})}vt=!0}vt||await pt()}())};async function pt(){if(it){tt.log.trace("optimistic: already negotiating %s stream",o),await st.promise;return}it=!0;try{at||(tt.log.trace("optimistic: doing send protocol for %s stream",o),await gt()),dt||(tt.log.trace("optimistic: doing read protocol for %s stream",o),await yt())}finally{it=!1,ot=!0,st.resolve()}}async function gt(){if(ct){await lt.promise;return}ct=!0;try{tt.log.trace('optimistic: write ["%s", "%s", data] in source',PROTOCOL_ID,o),await ft.writeV([fromString$4(`${PROTOCOL_ID} +`),fromString$4(`${o} +`)]),tt.log.trace('optimistic: wrote ["%s", "%s", data] in source',PROTOCOL_ID,o)}finally{at=!0,ct=!1,lt.resolve()}}async function yt(){if(ht){await mt.promise;return}ht=!0;try{tt.log.trace("optimistic: reading multistream select header");let bt=await readString(ft,tt);if(tt.log.trace('optimistic: read multistream select header "%s"',bt),bt===PROTOCOL_ID&&(bt=await readString(ft,tt)),tt.log.trace('optimistic: read protocol "%s", expecting "%s"',bt,o),bt!==o)throw new UnsupportedProtocolError("protocol selection failed")}finally{dt=!0,ht=!1,mt.resolve()}}if(et.source=async function*(){await pt(),tt.log.trace('optimistic: reading data from "%s" stream',o),yield*ft.unwrap().source}(),et.closeRead!=null){const bt=et.closeRead.bind(et);et.closeRead=async xt=>{ot||await pt().catch(vt=>{tt.log.error("could not negotiate protocol before close read",vt)}),await bt(xt)}}if(et.closeWrite!=null){const bt=et.closeWrite.bind(et);et.closeWrite=async xt=>{ot||await pt().catch(vt=>{tt.log.error("could not negotiate protocol before close write",vt)}),await bt(xt)}}if(et.close!=null){const bt=et.close.bind(et);et.close=async xt=>{const vt=[];ct&&vt.push(lt.promise),ht&&vt.push(mt.promise),vt.length>0?await raceSignal(Promise.all(vt),xt==null?void 0:xt.signal):(ot=!0,it=!1,st.resolve()),await bt(xt)}}return{stream:et,protocol:o}}async function handle(et,o,tt){o=Array.isArray(o)?o:[o],tt.log.trace("handle: available protocols %s",o);const rt=lpStream(et,{...tt,maxDataLength:MAX_PROTOCOL_LENGTH,maxLengthLength:2});for(;;){tt.log.trace("handle: reading incoming string");const nt=await readString(rt,tt);if(tt.log.trace('handle: read "%s"',nt),nt===PROTOCOL_ID){tt.log.trace('handle: respond with "%s" for "%s"',PROTOCOL_ID,nt),await write$1(rt,fromString$4(`${PROTOCOL_ID} +`),tt),tt.log.trace('handle: responded with "%s" for "%s"',PROTOCOL_ID,nt);continue}if(o.includes(nt))return tt.log.trace('handle: respond with "%s" for "%s"',nt,nt),await write$1(rt,fromString$4(`${nt} +`),tt),tt.log.trace('handle: responded with "%s" for "%s"',nt,nt),{stream:rt.unwrap(),protocol:nt};if(nt==="ls"){const ot=new Uint8ArrayList(...o.map(it=>encode$K.single(fromString$4(`${it} +`))),fromString$4(` +`));tt.log.trace('handle: respond with "%s" for %s',o,nt),await write$1(rt,ot,tt),tt.log.trace('handle: responded with "%s" for %s',o,nt);continue}tt.log.trace('handle: respond with "na" for "%s"',nt),await write$1(rt,fromString$4(`na +`),tt),tt.log('handle: responded with "na" for "%s"',nt)}}const CLOSE_TIMEOUT=500;var Jl,eu;eu=Symbol.toStringTag,Jl=connectionSymbol;class ConnectionImpl{constructor(o){wt(this,"id");wt(this,"remoteAddr");wt(this,"remotePeer");wt(this,"direction");wt(this,"timeline");wt(this,"multiplexer");wt(this,"encryption");wt(this,"status");wt(this,"limits");wt(this,"log");wt(this,"tags");wt(this,"_newStream");wt(this,"_close");wt(this,"_abort");wt(this,"_getStreams");wt(this,eu,"Connection");wt(this,Jl,!0);const{remoteAddr:tt,remotePeer:rt,newStream:nt,close:ot,abort:it,getStreams:st}=o;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=tt,this.remotePeer=rt,this.direction=o.direction,this.status="open",this.timeline=o.timeline,this.multiplexer=o.multiplexer,this.encryption=o.encryption,this.limits=o.limits,this.log=o.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=nt,this._close=ot,this._abort=it,this._getStreams=st,this.tags=[]}get streams(){return this._getStreams()}async newStream(o,tt){if(this.status==="closing")throw new ConnectionClosingError("the connection is being closed");if(this.status==="closed")throw new ConnectionClosedError("the connection is closed");if(Array.isArray(o)||(o=[o]),this.limits!=null&&(tt==null?void 0:tt.runOnLimitedConnection)!==!0)throw new LimitedConnectionError("Cannot open protocol stream on limited connection");const rt=await this._newStream(o,tt);return rt.direction="outbound",rt}async close(o={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",o.signal==null){const tt=AbortSignal.timeout(CLOSE_TIMEOUT);setMaxListeners(1/0,tt),o={...o,signal:tt}}try{this.log.trace("closing underlying transport"),await this._close(o),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(tt){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,tt),this.abort(tt)}}}abort(o){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,o),this.status="closing",this._abort(o),this.status="closed",this.timeline.close=Date.now())}}function createConnection(et){return new ConnectionImpl(et)}function findIncomingStreamLimit(et,o){try{const{options:tt}=o.getHandler(et);return tt.maxInboundStreams}catch(tt){if(tt.name!=="UnhandledProtocolError")throw tt}return DEFAULT_MAX_INBOUND_STREAMS}function findOutgoingStreamLimit(et,o,tt={}){try{const{options:rt}=o.getHandler(et);if(rt.maxOutboundStreams!=null)return rt.maxOutboundStreams}catch(rt){if(rt.name!=="UnhandledProtocolError")throw rt}return tt.maxOutboundStreams??DEFAULT_MAX_OUTBOUND_STREAMS}function countStreams(et,o,tt){let rt=0;return tt.streams.forEach(nt=>{nt.direction===o&&nt.protocol===et&&rt++}),rt}var tu;tu=Symbol.toStringTag;class DefaultUpgrader{constructor(o,tt){wt(this,"components");wt(this,"connectionEncrypters");wt(this,"streamMuxers");wt(this,"inboundUpgradeTimeout");wt(this,"outboundUpgradeTimeout");wt(this,"inboundStreamProtocolNegotiationTimeout");wt(this,"outboundStreamProtocolNegotiationTimeout");wt(this,"events");wt(this,"metrics");wt(this,tu,"@libp2p/upgrader");var rt,nt;this.components=o,this.connectionEncrypters=new Map,tt.connectionEncrypters.forEach(ot=>{this.connectionEncrypters.set(ot.protocol,ot)}),this.streamMuxers=new Map,tt.streamMuxers.forEach(ot=>{this.streamMuxers.set(ot.protocol,ot)}),this.inboundUpgradeTimeout=tt.inboundUpgradeTimeout??UPGRADE_TIMEOUT,this.outboundUpgradeTimeout=tt.outboundUpgradeTimeout??UPGRADE_TIMEOUT,this.inboundStreamProtocolNegotiationTimeout=tt.inboundStreamProtocolNegotiationTimeout??PROTOCOL_NEGOTIATION_TIMEOUT,this.outboundStreamProtocolNegotiationTimeout=tt.outboundStreamProtocolNegotiationTimeout??PROTOCOL_NEGOTIATION_TIMEOUT,this.events=o.events,this.metrics={dials:(rt=o.metrics)==null?void 0:rt.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:(nt=o.metrics)==null?void 0:nt.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}async shouldBlockConnection(o,...tt){const rt=this.components.connectionGater[o];if(rt==null)return;if(await rt.apply(this.components.connectionGater,tt)===!0)throw new ConnectionInterceptedError(`The multiaddr connection is blocked by gater.${o}`)}async upgradeInbound(o,tt={}){var rt,nt;try{if((rt=this.metrics.dials)==null||rt.increment({inbound:!0}),!await this.components.connectionManager.acceptIncomingConnection(o))throw new ConnectionDeniedError("connection denied");return await this.shouldBlockConnection("denyInboundConnection",o),await this._performUpgrade(o,"inbound",tt)}catch(ot){throw(nt=this.metrics.errors)==null||nt.increment({inbound:!0}),ot}finally{this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(o,tt={}){var rt,nt;try{(rt=this.metrics.dials)==null||rt.increment({outbound:!0});const ot=o.remoteAddr.getPeerId();let it;return ot!=null&&(it=peerIdFromString$1(ot),await this.shouldBlockConnection("denyOutboundConnection",it,o)),await this._performUpgrade(o,"outbound",tt)}catch(ot){throw(nt=this.metrics.errors)==null||nt.increment({outbound:!0}),ot}}async _performUpgrade(o,tt,rt){var ht,mt,ft;let nt,ot,it,st,at;const ct=AbortSignal.timeout(tt==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),lt=anySignal([ct,rt.signal]);setMaxListeners(1/0,ct,lt),rt.signal=lt,(ht=this.components.metrics)==null||ht.trackMultiaddrConnection(o),o.log.trace("starting the %s connection upgrade",tt);let dt=o;if((rt==null?void 0:rt.skipProtection)!==!0){const pt=this.components.connectionProtector;pt!=null&&(o.log("protecting the %s connection",tt),dt=await pt.protect(o,rt))}try{if(nt=dt,(rt==null?void 0:rt.skipEncryption)!==!0){(mt=rt==null?void 0:rt.onProgress)==null||mt.call(rt,new CustomProgressEvent(`upgrader:encrypt-${tt}-connection`)),{conn:nt,remotePeer:ot,protocol:at}=await(tt==="inbound"?this._encryptInbound(dt,{...rt,signal:lt}):this._encryptOutbound(dt,{...rt,signal:lt}));const pt={...dt,...nt};await this.shouldBlockConnection(tt==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",ot,pt)}else{const pt=o.remoteAddr.getPeerId();if(pt==null)throw new InvalidMultiaddrError(`${tt} connection that skipped encryption must have a peer id`);const gt=peerIdFromString$1(pt);at="native",ot=gt}if(ot.equals(this.components.peerId)){const pt=new InvalidPeerIdError("Can not dial self");throw o.abort(pt),pt}if(it=nt,(rt==null?void 0:rt.muxerFactory)!=null)st=rt.muxerFactory;else if(this.streamMuxers.size>0){(ft=rt==null?void 0:rt.onProgress)==null||ft.call(rt,new CustomProgressEvent(`upgrader:multiplex-${tt}-connection`));const pt=await(tt==="inbound"?this._multiplexInbound({...dt,...nt},this.streamMuxers,rt):this._multiplexOutbound({...dt,...nt},this.streamMuxers,rt));st=pt.muxerFactory,it=pt.stream}}catch(pt){throw o.log.error("failed to upgrade inbound connection %s %a - %e",tt==="inbound"?"from":"to",o.remoteAddr,pt),pt}finally{lt.clear()}return await this.shouldBlockConnection(tt==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",ot,o),o.log("successfully upgraded %s connection",tt),this._createConnection({cryptoProtocol:at,direction:tt,maConn:o,upgradedConn:it,muxerFactory:st,remotePeer:ot,limits:rt==null?void 0:rt.limits})}_createConnection(o){const{cryptoProtocol:tt,direction:rt,maConn:nt,upgradedConn:ot,remotePeer:it,muxerFactory:st,limits:at}=o;let ct,lt,dt;st!=null&&(ct=st.createStreamMuxer({direction:rt,onIncomingStream:ft=>{dt!=null&&Promise.resolve().then(async()=>{var Et;const pt=this.components.registrar.getProtocols(),gt=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);setMaxListeners(1/0,gt);const{stream:yt,protocol:bt}=await handle(ft,pt,{signal:gt,log:ft.log,yieldBytes:!1});if(dt==null)return;dt.log("incoming stream opened on %s",bt);const xt=findIncomingStreamLimit(bt,this.components.registrar);if(countStreams(bt,"inbound",dt)===xt){const Ct=new TooManyInboundProtocolStreamsError(`Too many inbound protocol streams for protocol "${bt}" - limit ${xt}`);throw ft.abort(Ct),Ct}ft.source=yt.source,ft.sink=yt.sink,ft.protocol=bt,yt.closeWrite!=null&&(ft.closeWrite=yt.closeWrite),yt.closeRead!=null&&(ft.closeRead=yt.closeRead),yt.close!=null&&(ft.close=yt.close),await this.components.peerStore.merge(it,{protocols:[bt]}),(Et=this.components.metrics)==null||Et.trackProtocolStream(ft,dt),this._onStream({connection:dt,stream:ft,protocol:bt})}).catch(async pt=>{dt.log.error("error handling incoming stream id %s - %e",ft.id,pt),ft.timeline.close==null&&await ft.close()})}}),lt=async(ft,pt={})=>{var yt;if(ct==null)throw new MuxerUnavailableError("Connection is not multiplexed");dt.log.trace("starting new stream for protocols %s",ft);const gt=await ct.newStream();dt.log.trace("started new stream %s for protocols %s",gt.id,ft);try{if(pt.signal==null){gt.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",ft);const Ct=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);setMaxListeners(1/0,Ct),pt={...pt,signal:Ct}}gt.log.trace("selecting protocol from protocols %s",ft);const{stream:bt,protocol:xt}=await select(gt,ft,{...pt,log:gt.log,yieldBytes:!0});gt.log.trace("selected protocol %s",xt);const vt=findOutgoingStreamLimit(xt,this.components.registrar,pt),Et=countStreams(xt,"outbound",dt);if(Et>=vt){const Ct=new TooManyOutboundProtocolStreamsError(`Too many outbound protocol streams for protocol "${xt}" - ${Et}/${vt}`);throw gt.abort(Ct),Ct}return await this.components.peerStore.merge(it,{protocols:[xt]}),gt.source=bt.source,gt.sink=bt.sink,gt.protocol=xt,bt.closeWrite!=null&&(gt.closeWrite=bt.closeWrite),bt.closeRead!=null&&(gt.closeRead=bt.closeRead),bt.close!=null&&(gt.close=bt.close),(yt=this.components.metrics)==null||yt.trackProtocolStream(gt,dt),gt}catch(bt){throw dt.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",rt==="inbound"?"from":"to",o.maConn.remoteAddr,ft,bt),gt.timeline.close==null&>.abort(bt),bt}},Promise.all([ct.sink(ot.source),ot.sink(ct.source)]).catch(ft=>{dt.log.error("error piping data through muxer - %e",ft)}));const ht=nt.timeline;nt.timeline=new Proxy(ht,{set:(...ft)=>(ft[1]==="close"&&ft[2]!=null&&ht.close==null&&(async()=>{try{dt.status==="open"&&await dt.close()}catch(pt){dt.log.error("error closing connection after timeline close %e",pt)}finally{this.events.safeDispatchEvent("connection:close",{detail:dt})}})().catch(pt=>{dt.log.error("error thrown while dispatching connection:close event %e",pt)}),Reflect.set(...ft))}),nt.timeline.upgraded=Date.now();const mt=()=>{throw new MuxerUnavailableError("Connection is not multiplexed")};return dt=createConnection({remoteAddr:nt.remoteAddr,remotePeer:it,status:"open",direction:rt,timeline:nt.timeline,multiplexer:ct==null?void 0:ct.protocol,encryption:tt,limits:at,logger:this.components.logger,newStream:lt??mt,getStreams:()=>(ct==null?void 0:ct.streams)??[],close:async ft=>{await(ct==null?void 0:ct.close(ft)),await nt.close(ft)},abort:ft=>{nt.abort(ft),ct==null||ct.abort(ft)}}),this.events.safeDispatchEvent("connection:open",{detail:dt}),dt.__maConnTimeline=ht,dt}_onStream(o){const{connection:tt,stream:rt,protocol:nt}=o,{handler:ot,options:it}=this.components.registrar.getHandler(nt);if(tt.limits!=null&&it.runOnLimitedConnection!==!0)throw new LimitedConnectionError("Cannot open protocol stream on limited connection");ot({connection:tt,stream:rt})}async _encryptInbound(o,tt){const rt=Array.from(this.connectionEncrypters.keys());try{const{stream:nt,protocol:ot}=await handle(o,rt,{...tt,log:o.log}),it=this.connectionEncrypters.get(ot);if(it==null)throw new EncryptionFailedError(`no crypto module found for ${ot}`);return o.log("encrypting inbound connection to %a using %s",o.remoteAddr,ot),{...await it.secureInbound(nt,tt),protocol:ot}}catch(nt){throw o.log.error("encrypting inbound connection from %a failed",o.remoteAddr,nt),new EncryptionFailedError(nt.message)}}async _encryptOutbound(o,tt){const rt=Array.from(this.connectionEncrypters.keys());try{o.log.trace("selecting encrypter from %s",rt);const{stream:nt,protocol:ot}=await select(o,rt,{...tt,log:o.log,yieldBytes:!0}),it=this.connectionEncrypters.get(ot);if(it==null)throw new EncryptionFailedError(`no crypto module found for ${ot}`);return o.log("encrypting outbound connection to %a using %s",o.remoteAddr,ot),{...await it.secureOutbound(nt,tt),protocol:ot}}catch(nt){throw o.log.error("encrypting outbound connection to %a failed",o.remoteAddr,nt),new EncryptionFailedError(nt.message)}}async _multiplexOutbound(o,tt,rt){const nt=Array.from(tt.keys());o.log("outbound selecting muxer %s",nt);try{o.log.trace("selecting stream muxer from %s",nt);const{stream:ot,protocol:it}=await select(o,nt,{...rt,log:o.log,yieldBytes:!0});o.log("selected %s as muxer protocol",it);const st=tt.get(it);return{stream:ot,muxerFactory:st}}catch(ot){throw o.log.error("error multiplexing outbound connection",ot),new MuxerUnavailableError(String(ot))}}async _multiplexInbound(o,tt,rt){const nt=Array.from(tt.keys());o.log("inbound handling muxers %s",nt);try{const{stream:ot,protocol:it}=await handle(o,nt,{...rt,log:o.log}),st=tt.get(it);return{stream:ot,muxerFactory:st}}catch(ot){throw o.log.error("error multiplexing inbound connection",ot),new MuxerUnavailableError(String(ot))}}}const version$3="2.1.8",name$2="libp2p";var go,Bs;class Libp2p extends TypedEventEmitter{constructor(tt){var at,ct,lt,dt,ht,mt;super();hr(this,go);wt(this,"peerId");wt(this,"peerStore");wt(this,"contentRouting");wt(this,"peerRouting");wt(this,"metrics");wt(this,"services");wt(this,"logger");wt(this,"status");wt(this,"components");wt(this,"log");this.status="stopped";const rt=new TypedEventEmitter,nt=rt.dispatchEvent.bind(rt);rt.dispatchEvent=ft=>{const pt=nt(ft),gt=this.dispatchEvent(new CustomEvent(ft.type,{detail:ft.detail}));return pt||gt},setMaxListeners(1/0,rt),this.peerId=tt.peerId,this.logger=tt.logger??defaultLogger(),this.log=this.logger.forComponent("libp2p"),this.services={};const ot=this.components=defaultComponents({peerId:tt.peerId,privateKey:tt.privateKey,nodeInfo:tt.nodeInfo??{name:name$2,version:version$3},logger:this.logger,events:rt,datastore:tt.datastore??new MemoryDatastore,connectionGater:connectionGater(tt.connectionGater),dns:tt.dns});this.peerStore=this.configureComponent("peerStore",persistentPeerStore(ot,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...tt.peerStore})),tt.metrics!=null&&(this.metrics=this.configureComponent("metrics",tt.metrics(this.components))),ot.events.addEventListener("peer:update",ft=>{if(ft.detail.previous==null){const pt={id:ft.detail.peer.id,multiaddrs:ft.detail.peer.addresses.map(gt=>gt.multiaddr)};ot.events.safeDispatchEvent("peer:discovery",{detail:pt})}}),tt.connectionProtector!=null&&this.configureComponent("connectionProtector",tt.connectionProtector(ot)),this.components.upgrader=new DefaultUpgrader(this.components,{connectionEncrypters:(tt.connectionEncrypters??[]).map((ft,pt)=>this.configureComponent(`connection-encryption-${pt}`,ft(this.components))),streamMuxers:(tt.streamMuxers??[]).map((ft,pt)=>this.configureComponent(`stream-muxers-${pt}`,ft(this.components))),inboundUpgradeTimeout:(at=tt.connectionManager)==null?void 0:at.inboundUpgradeTimeout,outboundUpgradeTimeout:(ct=tt.connectionManager)==null?void 0:ct.outboundUpgradeTimeout}),this.configureComponent("transportManager",new DefaultTransportManager(this.components,tt.transportManager)),this.configureComponent("connectionManager",new DefaultConnectionManager(this.components,tt.connectionManager)),((lt=tt.connectionMonitor)==null?void 0:lt.enabled)!==!1&&this.configureComponent("connectionMonitor",new ConnectionMonitor(this.components,tt.connectionMonitor)),this.configureComponent("registrar",new DefaultRegistrar(this.components)),this.configureComponent("addressManager",new DefaultAddressManager(this.components,tt.addresses));const it=(tt.peerRouters??[]).map((ft,pt)=>this.configureComponent(`peer-router-${pt}`,ft(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new DefaultPeerRouting(this.components,{routers:it}));const st=(tt.contentRouters??[]).map((ft,pt)=>this.configureComponent(`content-router-${pt}`,ft(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new CompoundContentRouting(this.components,{routers:st})),this.configureComponent("randomWalk",new RandomWalk(this.components)),(tt.peerDiscovery??[]).forEach((ft,pt)=>{this.configureComponent(`peer-discovery-${pt}`,ft(this.components)).addEventListener("peer",yt=>{fr(this,go,Bs).call(this,yt)})}),(dt=tt.transports)==null||dt.forEach((ft,pt)=>{this.components.transportManager.add(this.configureComponent(`transport-${pt}`,ft(this.components)))}),tt.services!=null)for(const ft of Object.keys(tt.services)){const pt=tt.services[ft],gt=pt(this.components);if(gt==null){this.log.error("service factory %s returned null or undefined instance",ft);continue}this.services[ft]=gt,this.configureComponent(ft,gt),gt[contentRoutingSymbol]!=null&&(this.log("registering service %s for content routing",ft),st.push(gt[contentRoutingSymbol])),gt[peerRoutingSymbol]!=null&&(this.log("registering service %s for peer routing",ft),it.push(gt[peerRoutingSymbol])),gt[peerDiscoverySymbol]!=null&&(this.log("registering service %s for peer discovery",ft),(mt=(ht=gt[peerDiscoverySymbol]).addEventListener)==null||mt.call(ht,"peer",yt=>{fr(this,go,Bs).call(this,yt)}))}checkServiceDependencies(ot)}configureComponent(tt,rt){return rt==null&&this.log.error("component %s was null or undefined",tt),this.components[tt]=rt,rt}async start(){var tt,rt,nt,ot;if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await((rt=(tt=this.components).beforeStart)==null?void 0:rt.call(tt)),await this.components.start(),await((ot=(nt=this.components).afterStart)==null?void 0:ot.call(nt)),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(it){throw this.log.error("An error occurred starting libp2p",it),this.status="started",await this.stop(),it}}}async stop(){var tt,rt,nt,ot;this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await((rt=(tt=this.components).beforeStop)==null?void 0:rt.call(tt)),await this.components.stop(),await((ot=(nt=this.components).afterStop)==null?void 0:ot.call(nt)),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(tt){return this.components.connectionManager.getConnections(tt)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const tt=new PeerSet;for(const rt of this.components.connectionManager.getConnections())tt.add(rt.remotePeer);return Array.from(tt)}async dial(tt,rt={}){return this.components.connectionManager.openConnection(tt,{priority:75,...rt})}async dialProtocol(tt,rt,nt={}){if(rt==null)throw new InvalidParametersError$1("no protocols were provided to open a stream");if(rt=Array.isArray(rt)?rt:[rt],rt.length===0)throw new InvalidParametersError$1("no protocols were provided to open a stream");return(await this.dial(tt,nt)).newStream(rt,nt)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(tt,rt={}){isMultiaddr(tt)&&(tt=peerIdFromString$1(tt.getPeerId()??"")),await this.components.connectionManager.closeConnections(tt,rt)}async getPublicKey(tt,rt={}){if(this.log("getPublicKey %p",tt),tt.publicKey!=null)return tt.publicKey;try{const st=await this.peerStore.get(tt);if(st.id.publicKey!=null)return st.id.publicKey}catch(st){if(st.name!=="NotFoundError")throw st}const nt=concat([fromString$6("/pk/"),tt.toMultihash().bytes]),ot=await this.contentRouting.get(nt,rt),it=publicKeyFromProtobuf(ot);return await this.peerStore.patch(tt,{publicKey:it}),it}async handle(tt,rt,nt){Array.isArray(tt)||(tt=[tt]),await Promise.all(tt.map(async ot=>{await this.components.registrar.handle(ot,rt,nt)}))}async unhandle(tt){Array.isArray(tt)||(tt=[tt]),await Promise.all(tt.map(async rt=>{await this.components.registrar.unhandle(rt)}))}async register(tt,rt){return this.components.registrar.register(tt,rt)}unregister(tt){this.components.registrar.unregister(tt)}async isDialable(tt,rt={}){return this.components.connectionManager.isDialable(tt,rt)}}go=new WeakSet,Bs=function(tt){const{detail:rt}=tt;if(rt.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(rt.id,{multiaddrs:rt.multiaddrs}).catch(nt=>{this.log.error(nt)})};async function createLibp2p(et={}){et.privateKey??(et.privateKey=await generateKeyPair());const o=new Libp2p({...await validateConfig(et),peerId:peerIdFromPrivateKey(et.privateKey)});return et.start!==!1&&await o.start(),o}const enrTree={SANDBOX:"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",TEST:"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"},DEFAULT_BOOTSTRAP_TAG_NAME="bootstrap",DEFAULT_BOOTSTRAP_TAG_VALUE=50,DEFAULT_BOOTSTRAP_TAG_TTL=1e8,DEFAULT_NODE_REQUIREMENTS={store:1,filter:2,lightPush:2},ERR_INVALID_ID="Invalid record id",MULTIADDR_LENGTH_SIZE=2,__viteBrowserExternal={},__viteBrowserExternal$1=Object.freeze(Object.defineProperty({__proto__:null,default:__viteBrowserExternal},Symbol.toStringTag,{value:"Module"}));/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const _0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_3n=BigInt(3),_8n=BigInt(8),CURVE=Object.freeze({a:_0n,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:_1n,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),divNearest=(et,o)=>(et+o/_2n)/o,endo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(et){const{n:o}=CURVE,tt=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),rt=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),nt=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),ot=tt,it=BigInt("0x100000000000000000000000000000000"),st=divNearest(ot*et,o),at=divNearest(-rt*et,o);let ct=mod(et-st*tt-at*nt,o),lt=mod(-st*rt-at*ot,o);const dt=ct>it,ht=lt>it;if(dt&&(ct=o-ct),ht&&(lt=o-lt),ct>it||lt>it)throw new Error("splitScalarEndo: Endomorphism failed, k="+et);return{k1neg:dt,k1:ct,k2neg:ht,k2:lt}}},fieldLen=32,groupLen=32,hashLen=32,compressedLen=fieldLen+1,uncompressedLen=2*fieldLen+1;function weierstrass(et){const{a:o,b:tt}=CURVE,rt=mod(et*et),nt=mod(rt*et);return mod(nt+o*et+tt)}const USE_ENDOMORPHISM=CURVE.a===_0n;class ShaError extends Error{constructor(o){super(o)}}function assertJacPoint(et){if(!(et instanceof JacobianPoint))throw new TypeError("JacobianPoint expected")}class JacobianPoint{constructor(o,tt,rt){this.x=o,this.y=tt,this.z=rt}static fromAffine(o){if(!(o instanceof Point))throw new TypeError("JacobianPoint#fromAffine: expected Point");return o.equals(Point.ZERO)?JacobianPoint.ZERO:new JacobianPoint(o.x,o.y,_1n)}static toAffineBatch(o){const tt=invertBatch(o.map(rt=>rt.z));return o.map((rt,nt)=>rt.toAffine(tt[nt]))}static normalizeZ(o){return JacobianPoint.toAffineBatch(o).map(JacobianPoint.fromAffine)}equals(o){assertJacPoint(o);const{x:tt,y:rt,z:nt}=this,{x:ot,y:it,z:st}=o,at=mod(nt*nt),ct=mod(st*st),lt=mod(tt*ct),dt=mod(ot*at),ht=mod(mod(rt*st)*ct),mt=mod(mod(it*nt)*at);return lt===dt&&ht===mt}negate(){return new JacobianPoint(this.x,mod(-this.y),this.z)}double(){const{x:o,y:tt,z:rt}=this,nt=mod(o*o),ot=mod(tt*tt),it=mod(ot*ot),st=o+ot,at=mod(_2n*(mod(st*st)-nt-it)),ct=mod(_3n*nt),lt=mod(ct*ct),dt=mod(lt-_2n*at),ht=mod(ct*(at-dt)-_8n*it),mt=mod(_2n*tt*rt);return new JacobianPoint(dt,ht,mt)}add(o){assertJacPoint(o);const{x:tt,y:rt,z:nt}=this,{x:ot,y:it,z:st}=o;if(ot===_0n||it===_0n)return this;if(tt===_0n||rt===_0n)return o;const at=mod(nt*nt),ct=mod(st*st),lt=mod(tt*ct),dt=mod(ot*at),ht=mod(mod(rt*st)*ct),mt=mod(mod(it*nt)*at),ft=mod(dt-lt),pt=mod(mt-ht);if(ft===_0n)return pt===_0n?this.double():JacobianPoint.ZERO;const gt=mod(ft*ft),yt=mod(ft*gt),bt=mod(lt*gt),xt=mod(pt*pt-yt-_2n*bt),vt=mod(pt*(bt-xt)-ht*yt),Et=mod(nt*st*ft);return new JacobianPoint(xt,vt,Et)}subtract(o){return this.add(o.negate())}multiplyUnsafe(o){const tt=JacobianPoint.ZERO;if(typeof o=="bigint"&&o===_0n)return tt;let rt=normalizeScalar(o);if(rt===_1n)return this;if(!USE_ENDOMORPHISM){let dt=tt,ht=this;for(;rt>_0n;)rt&_1n&&(dt=dt.add(ht)),ht=ht.double(),rt>>=_1n;return dt}let{k1neg:nt,k1:ot,k2neg:it,k2:st}=endo.splitScalar(rt),at=tt,ct=tt,lt=this;for(;ot>_0n||st>_0n;)ot&_1n&&(at=at.add(lt)),st&_1n&&(ct=ct.add(lt)),lt=lt.double(),ot>>=_1n,st>>=_1n;return nt&&(at=at.negate()),it&&(ct=ct.negate()),ct=new JacobianPoint(mod(ct.x*endo.beta),ct.y,ct.z),at.add(ct)}precomputeWindow(o){const tt=USE_ENDOMORPHISM?128/o+1:256/o+1,rt=[];let nt=this,ot=nt;for(let it=0;it>=dt,ft>at&&(ft-=lt,o+=_1n);const pt=mt,gt=mt+Math.abs(ft)-1,yt=ht%2!==0,bt=ft<0;ft===0?it=it.add(constTimeNegate(yt,nt[pt])):ot=ot.add(constTimeNegate(bt,nt[gt]))}return{p:ot,f:it}}multiply(o,tt){let rt=normalizeScalar(o),nt,ot;if(USE_ENDOMORPHISM){const{k1neg:it,k1:st,k2neg:at,k2:ct}=endo.splitScalar(rt);let{p:lt,f:dt}=this.wNAF(st,tt),{p:ht,f:mt}=this.wNAF(ct,tt);lt=constTimeNegate(it,lt),ht=constTimeNegate(at,ht),ht=new JacobianPoint(mod(ht.x*endo.beta),ht.y,ht.z),nt=lt.add(ht),ot=dt.add(mt)}else{const{p:it,f:st}=this.wNAF(rt,tt);nt=it,ot=st}return JacobianPoint.normalizeZ([nt,ot])[0]}toAffine(o){const{x:tt,y:rt,z:nt}=this,ot=this.equals(JacobianPoint.ZERO);o==null&&(o=ot?_8n:invert(nt));const it=o,st=mod(it*it),at=mod(st*it),ct=mod(tt*st),lt=mod(rt*at),dt=mod(nt*it);if(ot)return Point.ZERO;if(dt!==_1n)throw new Error("invZ was invalid");return new Point(ct,lt)}}JacobianPoint.BASE=new JacobianPoint(CURVE.Gx,CURVE.Gy,_1n);JacobianPoint.ZERO=new JacobianPoint(_0n,_1n,_0n);function constTimeNegate(et,o){const tt=o.negate();return et?tt:o}const pointPrecomputes=new WeakMap;class Point{constructor(o,tt){this.x=o,this.y=tt}_setWindowSize(o){this._WINDOW_SIZE=o,pointPrecomputes.delete(this)}hasEvenY(){return this.y%_2n===_0n}static fromCompressedHex(o){const tt=o.length===32,rt=bytesToNumber(tt?o:o.subarray(1));if(!isValidFieldElement(rt))throw new Error("Point is not on curve");const nt=weierstrass(rt);let ot=sqrtMod(nt);const it=(ot&_1n)===_1n;tt?it&&(ot=mod(-ot)):(o[0]&1)===1!==it&&(ot=mod(-ot));const st=new Point(rt,ot);return st.assertValidity(),st}static fromUncompressedHex(o){const tt=bytesToNumber(o.subarray(1,fieldLen+1)),rt=bytesToNumber(o.subarray(fieldLen+1,fieldLen*2+1)),nt=new Point(tt,rt);return nt.assertValidity(),nt}static fromHex(o){const tt=ensureBytes(o),rt=tt.length,nt=tt[0];if(rt===fieldLen)return this.fromCompressedHex(tt);if(rt===compressedLen&&(nt===2||nt===3))return this.fromCompressedHex(tt);if(rt===uncompressedLen&&nt===4)return this.fromUncompressedHex(tt);throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${rt}`)}static fromPrivateKey(o){return Point.BASE.multiply(normalizePrivateKey(o))}static fromSignature(o,tt,rt){const{r:nt,s:ot}=normalizeSignature(tt);if(![0,1,2,3].includes(rt))throw new Error("Cannot recover: invalid recovery bit");const it=truncateHash(ensureBytes(o)),{n:st}=CURVE,at=rt===2||rt===3?nt+st:nt,ct=invert(at,st),lt=mod(-it*ct,st),dt=mod(ot*ct,st),ht=rt&1?"03":"02",mt=Point.fromHex(ht+numTo32bStr(at)),ft=Point.BASE.multiplyAndAddUnsafe(mt,lt,dt);if(!ft)throw new Error("Cannot recover signature: point at infinify");return ft.assertValidity(),ft}toRawBytes(o=!1){return hexToBytes(this.toHex(o))}toHex(o=!1){const tt=numTo32bStr(this.x);return o?`${this.hasEvenY()?"02":"03"}${tt}`:`04${tt}${numTo32bStr(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const o="Point is not on elliptic curve",{x:tt,y:rt}=this;if(!isValidFieldElement(tt)||!isValidFieldElement(rt))throw new Error(o);const nt=mod(rt*rt),ot=weierstrass(tt);if(mod(nt-ot)!==_0n)throw new Error(o)}equals(o){return this.x===o.x&&this.y===o.y}negate(){return new Point(this.x,mod(-this.y))}double(){return JacobianPoint.fromAffine(this).double().toAffine()}add(o){return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(o)).toAffine()}subtract(o){return this.add(o.negate())}multiply(o){return JacobianPoint.fromAffine(this).multiply(o,this).toAffine()}multiplyAndAddUnsafe(o,tt,rt){const nt=JacobianPoint.fromAffine(this),ot=tt===_0n||tt===_1n||this!==Point.BASE?nt.multiplyUnsafe(tt):nt.multiply(tt),it=JacobianPoint.fromAffine(o).multiplyUnsafe(rt),st=ot.add(it);return st.equals(JacobianPoint.ZERO)?void 0:st.toAffine()}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy);Point.ZERO=new Point(_0n,_0n);function sliceDER(et){return Number.parseInt(et[0],16)>=8?"00"+et:et}function parseDERInt(et){if(et.length<2||et[0]!==2)throw new Error(`Invalid signature integer tag: ${bytesToHex(et)}`);const o=et[1],tt=et.subarray(2,o+2);if(!o||tt.length!==o)throw new Error("Invalid signature integer: wrong length");if(tt[0]===0&&tt[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:bytesToNumber(tt),left:et.subarray(o+2)}}function parseDERSignature(et){if(et.length<2||et[0]!=48)throw new Error(`Invalid signature tag: ${bytesToHex(et)}`);if(et[1]!==et.length-2)throw new Error("Invalid signature: incorrect length");const{data:o,left:tt}=parseDERInt(et.subarray(2)),{data:rt,left:nt}=parseDERInt(tt);if(nt.length)throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(nt)}`);return{r:o,s:rt}}class Signature{constructor(o,tt){this.r=o,this.s=tt,this.assertValidity()}static fromCompact(o){const tt=o instanceof Uint8Array,rt="Signature.fromCompact";if(typeof o!="string"&&!tt)throw new TypeError(`${rt}: Expected string or Uint8Array`);const nt=tt?bytesToHex(o):o;if(nt.length!==128)throw new Error(`${rt}: Expected 64-byte hex`);return new Signature(hexToNumber(nt.slice(0,64)),hexToNumber(nt.slice(64,128)))}static fromDER(o){const tt=o instanceof Uint8Array;if(typeof o!="string"&&!tt)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:rt,s:nt}=parseDERSignature(tt?o:hexToBytes(o));return new Signature(rt,nt)}static fromHex(o){return this.fromDER(o)}assertValidity(){const{r:o,s:tt}=this;if(!isWithinCurveOrder(o))throw new Error("Invalid Signature: r must be 0 < r < n");if(!isWithinCurveOrder(tt))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const o=CURVE.n>>_1n;return this.s>o}normalizeS(){return this.hasHighS()?new Signature(this.r,mod(-this.s,CURVE.n)):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){const o=sliceDER(numberToHexUnpadded(this.s)),tt=sliceDER(numberToHexUnpadded(this.r)),rt=o.length/2,nt=tt.length/2,ot=numberToHexUnpadded(rt),it=numberToHexUnpadded(nt);return`30${numberToHexUnpadded(nt+rt+4)}02${it}${tt}02${ot}${o}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}}function concatBytes(...et){if(!et.every(rt=>rt instanceof Uint8Array))throw new Error("Uint8Array list expected");if(et.length===1)return et[0];const o=et.reduce((rt,nt)=>rt+nt.length,0),tt=new Uint8Array(o);for(let rt=0,nt=0;rto.toString(16).padStart(2,"0"));function bytesToHex(et){if(!(et instanceof Uint8Array))throw new Error("Expected Uint8Array");let o="";for(let tt=0;tt0)return BigInt(et);if(typeof et=="bigint"&&isWithinCurveOrder(et))return et;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function mod(et,o=CURVE.P){const tt=et%o;return tt>=_0n?tt:o+tt}function pow2(et,o){const{P:tt}=CURVE;let rt=et;for(;o-- >_0n;)rt*=rt,rt%=tt;return rt}function sqrtMod(et){const{P:o}=CURVE,tt=BigInt(6),rt=BigInt(11),nt=BigInt(22),ot=BigInt(23),it=BigInt(44),st=BigInt(88),at=et*et*et%o,ct=at*at*et%o,lt=pow2(ct,_3n)*ct%o,dt=pow2(lt,_3n)*ct%o,ht=pow2(dt,_2n)*at%o,mt=pow2(ht,rt)*ht%o,ft=pow2(mt,nt)*mt%o,pt=pow2(ft,it)*ft%o,gt=pow2(pt,st)*pt%o,yt=pow2(gt,it)*ft%o,bt=pow2(yt,_3n)*ct%o,xt=pow2(bt,ot)*mt%o,vt=pow2(xt,tt)*at%o,Et=pow2(vt,_2n);if(Et*Et%o!==et)throw new Error("Cannot find square root");return Et}function invert(et,o=CURVE.P){if(et===_0n||o<=_0n)throw new Error(`invert: expected positive integers, got n=${et} mod=${o}`);let tt=mod(et,o),rt=o,nt=_0n,ot=_1n;for(;tt!==_0n;){const st=rt/tt,at=rt%tt,ct=nt-ot*st;rt=tt,tt=at,nt=ot,ot=ct}if(rt!==_1n)throw new Error("invert: does not exist");return mod(nt,o)}function invertBatch(et,o=CURVE.P){const tt=new Array(et.length),rt=et.reduce((ot,it,st)=>it===_0n?ot:(tt[st]=ot,mod(ot*it,o)),_1n),nt=invert(rt,o);return et.reduceRight((ot,it,st)=>it===_0n?ot:(tt[st]=mod(ot*tt[st],o),mod(ot*it,o)),nt),tt}function bits2int_2(et){const o=et.length*8-groupLen*8,tt=bytesToNumber(et);return o>0?tt>>BigInt(o):tt}function truncateHash(et,o=!1){const tt=bits2int_2(et);if(o)return tt;const{n:rt}=CURVE;return tt>=rt?tt-rt:tt}let _sha256Sync,_hmacSha256Sync;class HmacDrbg{constructor(o,tt){if(this.hashLen=o,this.qByteLen=tt,typeof o!="number"||o<2)throw new Error("hashLen must be a number");if(typeof tt!="number"||tt<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(o).fill(1),this.k=new Uint8Array(o).fill(0),this.counter=0}hmac(...o){return utils.hmacSha256(this.k,...o)}hmacSync(...o){return _hmacSha256Sync(this.k,...o)}checkSync(){if(typeof _hmacSha256Sync!="function")throw new ShaError("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(o=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),o),this.v=await this.hmac(this.v),o.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),o),this.v=await this.hmac(this.v))}reseedSync(o=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),o),this.v=this.hmacSync(this.v),o.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),o),this.v=this.hmacSync(this.v))}async generate(){this.incr();let o=0;const tt=[];for(;o0)o=BigInt(et);else if(typeof et=="string"){if(et.length!==2*groupLen)throw new Error("Expected 32 bytes of private key");o=hexToNumber(et)}else if(et instanceof Uint8Array){if(et.length!==groupLen)throw new Error("Expected 32 bytes of private key");o=bytesToNumber(et)}else throw new TypeError("Expected valid private key");if(!isWithinCurveOrder(o))throw new Error("Expected private key: 0 < key < n");return o}function normalizePublicKey(et){return et instanceof Point?(et.assertValidity(),et):Point.fromHex(et)}function normalizeSignature(et){if(et instanceof Signature)return et.assertValidity(),et;try{return Signature.fromDER(et)}catch{return Signature.fromCompact(et)}}function bits2int(et){const o=et.length>fieldLen?et.slice(0,fieldLen):et;return bytesToNumber(o)}function bits2octets(et){const o=bits2int(et),tt=mod(o,CURVE.n);return int2octets(tt<_0n?o:tt)}function int2octets(et){return numTo32b(et)}function initSigArgs(et,o,tt){if(et==null)throw new Error(`sign: expected valid message hash, not "${et}"`);const rt=ensureBytes(et),nt=normalizePrivateKey(o),ot=[int2octets(nt),bits2octets(rt)];if(tt!=null){tt===!0&&(tt=utils.randomBytes(fieldLen));const at=ensureBytes(tt);if(at.length!==fieldLen)throw new Error(`sign: Expected ${fieldLen} bytes of extra data`);ot.push(at)}const it=concatBytes(...ot),st=bits2int(rt);return{seed:it,m:st,d:nt}}function finalizeSig(et,o){const{sig:tt,recovery:rt}=et,{der:nt,recovered:ot}=Object.assign({canonical:!0,der:!0},o),it=nt?tt.toDERRawBytes():tt.toCompactRawBytes();return ot?[it,rt]:it}async function sign$1(et,o,tt={}){const{seed:rt,m:nt,d:ot}=initSigArgs(et,o,tt.extraEntropy),it=new HmacDrbg(hashLen,groupLen);await it.reseed(rt);let st;for(;!(st=kmdToSig(await it.generate(),nt,ot,tt.canonical));)await it.reseed();return finalizeSig(st,tt)}const vopts={strict:!0};function verify(et,o,tt,rt=vopts){let nt;try{nt=normalizeSignature(et),o=ensureBytes(o)}catch{return!1}const{r:ot,s:it}=nt;if(rt.strict&&nt.hasHighS())return!1;const st=truncateHash(o);let at;try{at=normalizePublicKey(tt)}catch{return!1}const{n:ct}=CURVE,lt=invert(it,ct),dt=mod(st*lt,ct),ht=mod(ot*lt,ct),mt=Point.BASE.multiplyAndAddUnsafe(at,dt,ht);return mt?mod(mt.x,ct)===ot:!1}Point.BASE._setWindowSize(8);const crypto$1={node:__viteBrowserExternal$1,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0},TAGGED_HASH_PREFIXES={},utils={bytesToHex,hexToBytes,concatBytes,mod,invert,isValidPrivateKey(et){try{return normalizePrivateKey(et),!0}catch{return!1}},_bigintTo32Bytes:numTo32b,_normalizePrivateKey:normalizePrivateKey,hashToPrivateKey:et=>{et=ensureBytes(et);const o=groupLen+8;if(et.length1024)throw new Error("Expected valid bytes of private key as per FIPS 186");const tt=mod(bytesToNumber(et),CURVE.n-_1n)+_1n;return numTo32b(tt)},randomBytes:(et=32)=>{if(crypto$1.web)return crypto$1.web.getRandomValues(new Uint8Array(et));if(crypto$1.node){const{randomBytes:o}=crypto$1.node;return Uint8Array.from(o(et))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>utils.hashToPrivateKey(utils.randomBytes(groupLen+8)),precompute(et=8,o=Point.BASE){const tt=o===Point.BASE?o:new Point(o.x,o.y);return tt._setWindowSize(et),tt.multiply(_3n),tt},sha256:async(...et)=>{if(crypto$1.web){const o=await crypto$1.web.subtle.digest("SHA-256",concatBytes(...et));return new Uint8Array(o)}else if(crypto$1.node){const{createHash:o}=crypto$1.node,tt=o("sha256");return et.forEach(rt=>tt.update(rt)),Uint8Array.from(tt.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(et,...o)=>{if(crypto$1.web){const tt=await crypto$1.web.subtle.importKey("raw",et,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),rt=concatBytes(...o),nt=await crypto$1.web.subtle.sign("HMAC",tt,rt);return new Uint8Array(nt)}else if(crypto$1.node){const{createHmac:tt}=crypto$1.node,rt=tt("sha256",et);return o.forEach(nt=>rt.update(nt)),Uint8Array.from(rt.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(et,...o)=>{let tt=TAGGED_HASH_PREFIXES[et];if(tt===void 0){const rt=await utils.sha256(Uint8Array.from(et,nt=>nt.charCodeAt(0)));tt=concatBytes(rt,rt),TAGGED_HASH_PREFIXES[et]=tt}return utils.sha256(tt,...o)},taggedHashSync:(et,...o)=>{if(typeof _sha256Sync!="function")throw new ShaError("sha256Sync is undefined, you need to set it");let tt=TAGGED_HASH_PREFIXES[et];if(tt===void 0){const rt=_sha256Sync(Uint8Array.from(et,nt=>nt.charCodeAt(0)));tt=concatBytes(rt,rt),TAGGED_HASH_PREFIXES[et]=tt}return _sha256Sync(tt,...o)},_JacobianPoint:JacobianPoint};Object.defineProperties(utils,{sha256Sync:{configurable:!1,get(){return _sha256Sync},set(et){_sha256Sync||(_sha256Sync=et)}},hmacSha256Sync:{configurable:!1,get(){return _hmacSha256Sync},set(et){_hmacSha256Sync||(_hmacSha256Sync=et)}}});var sha3$1={exports:{}};/** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.9.3 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2023 + * @license MIT + */(function(et){(function(){var o="input is invalid type",tt="finalize already called",rt=typeof window=="object",nt=rt?window:{};nt.JS_SHA3_NO_WINDOW&&(rt=!1);var ot=!rt&&typeof self=="object",it=!nt.JS_SHA3_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;it?nt=commonjsGlobal:ot&&(nt=self);for(var st=!nt.JS_SHA3_NO_COMMON_JS&&!0&&et.exports,at=!nt.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",ct="0123456789abcdef".split(""),lt=[31,7936,2031616,520093696],dt=[4,1024,262144,67108864],ht=[1,256,65536,16777216],mt=[6,1536,393216,100663296],ft=[0,8,16,24],pt=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],gt=[224,256,384,512],yt=[128,256],bt=["hex","buffer","arrayBuffer","array","digest"],xt={128:168,256:136},vt=nt.JS_SHA3_NO_NODE_JS||!Array.isArray?function(Rt){return Object.prototype.toString.call(Rt)==="[object Array]"}:Array.isArray,Et=at&&(nt.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)?function(Rt){return typeof Rt=="object"&&Rt.buffer&&Rt.buffer.constructor===ArrayBuffer}:ArrayBuffer.isView,Ct=function(Rt){var Mt=typeof Rt;if(Mt==="string")return[Rt,!0];if(Mt!=="object"||Rt===null)throw new Error(o);if(at&&Rt.constructor===ArrayBuffer)return[new Uint8Array(Rt),!1];if(!vt(Rt)&&!Et(Rt))throw new Error(o);return[Rt,!1]},St=function(Rt){return Ct(Rt)[0].length===0},At=function(Rt){for(var Mt=[],Ut=0;Ut>5,this.byteCount=this.blockCount<<2,this.outputBlocks=Ut>>5,this.extraBytes=(Ut&31)>>3;for(var Zt=0;Zt<50;++Zt)this.s[Zt]=0}lr.prototype.update=function(Rt){if(this.finalized)throw new Error(tt);var Mt=Ct(Rt);Rt=Mt[0];for(var Ut=Mt[1],Zt=this.blocks,nr=this.byteCount,ar=Rt.length,dr=this.blockCount,cr=0,yr=this.s,pr,gr;cr>2]|=gr<>2]|=(192|gr>>6)<>2]|=(128|gr&63)<=57344?(Zt[pr>>2]|=(224|gr>>12)<>2]|=(128|gr>>6&63)<>2]|=(128|gr&63)<>2]|=(240|gr>>18)<>2]|=(128|gr>>12&63)<>2]|=(128|gr>>6&63)<>2]|=(128|gr&63)<>2]|=Rt[cr]<=nr){for(this.start=pr-nr,this.block=Zt[dr],pr=0;pr>8,Ut=Rt&255;Ut>0;)nr.unshift(Ut),Rt=Rt>>8,Ut=Rt&255,++Zt;return Mt?nr.push(Zt):nr.unshift(Zt),this.update(nr),nr.length},lr.prototype.encodeString=function(Rt){var Mt=Ct(Rt);Rt=Mt[0];var Ut=Mt[1],Zt=0,nr=Rt.length;if(Ut)for(var ar=0;ar=57344?Zt+=3:(dr=65536+((dr&1023)<<10|Rt.charCodeAt(++ar)&1023),Zt+=4)}else Zt=nr;return Zt+=this.encode(Zt*8),this.update(Rt),Zt},lr.prototype.bytepad=function(Rt,Mt){for(var Ut=this.encode(Mt),Zt=0;Zt>2]|=this.padding[Mt&3],this.lastByteIndex===this.byteCount)for(Rt[0]=Rt[Ut],Mt=1;Mt>4&15]+ct[cr&15]+ct[cr>>12&15]+ct[cr>>8&15]+ct[cr>>20&15]+ct[cr>>16&15]+ct[cr>>28&15]+ct[cr>>24&15];ar%Rt===0&&(Mt=At(Mt),Jt(Mt),nr=0)}return Zt&&(cr=Mt[nr],dr+=ct[cr>>4&15]+ct[cr&15],Zt>1&&(dr+=ct[cr>>12&15]+ct[cr>>8&15]),Zt>2&&(dr+=ct[cr>>20&15]+ct[cr>>16&15])),dr},lr.prototype.arrayBuffer=function(){this.finalize();var Rt=this.blockCount,Mt=this.s,Ut=this.outputBlocks,Zt=this.extraBytes,nr=0,ar=0,dr=this.outputBits>>3,cr;Zt?cr=new ArrayBuffer(Ut+1<<2):cr=new ArrayBuffer(dr);for(var yr=new Uint32Array(cr);ar>8&255,dr[cr+2]=yr>>16&255,dr[cr+3]=yr>>24&255;ar%Rt===0&&(Mt=At(Mt),Jt(Mt))}return Zt&&(cr=ar<<2,yr=Mt[nr],dr[cr]=yr&255,Zt>1&&(dr[cr+1]=yr>>8&255),Zt>2&&(dr[cr+2]=yr>>16&255)),dr};function rr(Rt,Mt,Ut){lr.call(this,Rt,Mt,Ut)}rr.prototype=new lr,rr.prototype.finalize=function(){return this.encode(this.outputBits,!0),lr.prototype.finalize.call(this)};var Jt=function(Rt){var Mt,Ut,Zt,nr,ar,dr,cr,yr,pr,gr,Pr,_r,Rr,mr,wr,ir,Tt,$t,_t,Dt,qt,er,sr,br,Ar,xr,Sr,vr,yo,bo,xo,vo,wo,Eo,Co,So,Ao,$o,ko,_o,Ro,To,Io,Po,jo,No,Do,Oo,Lo,Mo,Bo,Fo,Uo,zo,Vo,Ho,Wo,Go,Zo,qo,Ko,Qo,Yo;for(Zt=0;Zt<48;Zt+=2)nr=Rt[0]^Rt[10]^Rt[20]^Rt[30]^Rt[40],ar=Rt[1]^Rt[11]^Rt[21]^Rt[31]^Rt[41],dr=Rt[2]^Rt[12]^Rt[22]^Rt[32]^Rt[42],cr=Rt[3]^Rt[13]^Rt[23]^Rt[33]^Rt[43],yr=Rt[4]^Rt[14]^Rt[24]^Rt[34]^Rt[44],pr=Rt[5]^Rt[15]^Rt[25]^Rt[35]^Rt[45],gr=Rt[6]^Rt[16]^Rt[26]^Rt[36]^Rt[46],Pr=Rt[7]^Rt[17]^Rt[27]^Rt[37]^Rt[47],_r=Rt[8]^Rt[18]^Rt[28]^Rt[38]^Rt[48],Rr=Rt[9]^Rt[19]^Rt[29]^Rt[39]^Rt[49],Mt=_r^(dr<<1|cr>>>31),Ut=Rr^(cr<<1|dr>>>31),Rt[0]^=Mt,Rt[1]^=Ut,Rt[10]^=Mt,Rt[11]^=Ut,Rt[20]^=Mt,Rt[21]^=Ut,Rt[30]^=Mt,Rt[31]^=Ut,Rt[40]^=Mt,Rt[41]^=Ut,Mt=nr^(yr<<1|pr>>>31),Ut=ar^(pr<<1|yr>>>31),Rt[2]^=Mt,Rt[3]^=Ut,Rt[12]^=Mt,Rt[13]^=Ut,Rt[22]^=Mt,Rt[23]^=Ut,Rt[32]^=Mt,Rt[33]^=Ut,Rt[42]^=Mt,Rt[43]^=Ut,Mt=dr^(gr<<1|Pr>>>31),Ut=cr^(Pr<<1|gr>>>31),Rt[4]^=Mt,Rt[5]^=Ut,Rt[14]^=Mt,Rt[15]^=Ut,Rt[24]^=Mt,Rt[25]^=Ut,Rt[34]^=Mt,Rt[35]^=Ut,Rt[44]^=Mt,Rt[45]^=Ut,Mt=yr^(_r<<1|Rr>>>31),Ut=pr^(Rr<<1|_r>>>31),Rt[6]^=Mt,Rt[7]^=Ut,Rt[16]^=Mt,Rt[17]^=Ut,Rt[26]^=Mt,Rt[27]^=Ut,Rt[36]^=Mt,Rt[37]^=Ut,Rt[46]^=Mt,Rt[47]^=Ut,Mt=gr^(nr<<1|ar>>>31),Ut=Pr^(ar<<1|nr>>>31),Rt[8]^=Mt,Rt[9]^=Ut,Rt[18]^=Mt,Rt[19]^=Ut,Rt[28]^=Mt,Rt[29]^=Ut,Rt[38]^=Mt,Rt[39]^=Ut,Rt[48]^=Mt,Rt[49]^=Ut,mr=Rt[0],wr=Rt[1],No=Rt[11]<<4|Rt[10]>>>28,Do=Rt[10]<<4|Rt[11]>>>28,vr=Rt[20]<<3|Rt[21]>>>29,yo=Rt[21]<<3|Rt[20]>>>29,qo=Rt[31]<<9|Rt[30]>>>23,Ko=Rt[30]<<9|Rt[31]>>>23,To=Rt[40]<<18|Rt[41]>>>14,Io=Rt[41]<<18|Rt[40]>>>14,Eo=Rt[2]<<1|Rt[3]>>>31,Co=Rt[3]<<1|Rt[2]>>>31,ir=Rt[13]<<12|Rt[12]>>>20,Tt=Rt[12]<<12|Rt[13]>>>20,Oo=Rt[22]<<10|Rt[23]>>>22,Lo=Rt[23]<<10|Rt[22]>>>22,bo=Rt[33]<<13|Rt[32]>>>19,xo=Rt[32]<<13|Rt[33]>>>19,Qo=Rt[42]<<2|Rt[43]>>>30,Yo=Rt[43]<<2|Rt[42]>>>30,zo=Rt[5]<<30|Rt[4]>>>2,Vo=Rt[4]<<30|Rt[5]>>>2,So=Rt[14]<<6|Rt[15]>>>26,Ao=Rt[15]<<6|Rt[14]>>>26,$t=Rt[25]<<11|Rt[24]>>>21,_t=Rt[24]<<11|Rt[25]>>>21,Mo=Rt[34]<<15|Rt[35]>>>17,Bo=Rt[35]<<15|Rt[34]>>>17,vo=Rt[45]<<29|Rt[44]>>>3,wo=Rt[44]<<29|Rt[45]>>>3,br=Rt[6]<<28|Rt[7]>>>4,Ar=Rt[7]<<28|Rt[6]>>>4,Ho=Rt[17]<<23|Rt[16]>>>9,Wo=Rt[16]<<23|Rt[17]>>>9,$o=Rt[26]<<25|Rt[27]>>>7,ko=Rt[27]<<25|Rt[26]>>>7,Dt=Rt[36]<<21|Rt[37]>>>11,qt=Rt[37]<<21|Rt[36]>>>11,Fo=Rt[47]<<24|Rt[46]>>>8,Uo=Rt[46]<<24|Rt[47]>>>8,Po=Rt[8]<<27|Rt[9]>>>5,jo=Rt[9]<<27|Rt[8]>>>5,xr=Rt[18]<<20|Rt[19]>>>12,Sr=Rt[19]<<20|Rt[18]>>>12,Go=Rt[29]<<7|Rt[28]>>>25,Zo=Rt[28]<<7|Rt[29]>>>25,_o=Rt[38]<<8|Rt[39]>>>24,Ro=Rt[39]<<8|Rt[38]>>>24,er=Rt[48]<<14|Rt[49]>>>18,sr=Rt[49]<<14|Rt[48]>>>18,Rt[0]=mr^~ir&$t,Rt[1]=wr^~Tt&_t,Rt[10]=br^~xr&vr,Rt[11]=Ar^~Sr&yo,Rt[20]=Eo^~So&$o,Rt[21]=Co^~Ao&ko,Rt[30]=Po^~No&Oo,Rt[31]=jo^~Do&Lo,Rt[40]=zo^~Ho&Go,Rt[41]=Vo^~Wo&Zo,Rt[2]=ir^~$t&Dt,Rt[3]=Tt^~_t&qt,Rt[12]=xr^~vr&bo,Rt[13]=Sr^~yo&xo,Rt[22]=So^~$o&_o,Rt[23]=Ao^~ko&Ro,Rt[32]=No^~Oo&Mo,Rt[33]=Do^~Lo&Bo,Rt[42]=Ho^~Go&qo,Rt[43]=Wo^~Zo&Ko,Rt[4]=$t^~Dt&er,Rt[5]=_t^~qt&sr,Rt[14]=vr^~bo&vo,Rt[15]=yo^~xo&wo,Rt[24]=$o^~_o&To,Rt[25]=ko^~Ro&Io,Rt[34]=Oo^~Mo&Fo,Rt[35]=Lo^~Bo&Uo,Rt[44]=Go^~qo&Qo,Rt[45]=Zo^~Ko&Yo,Rt[6]=Dt^~er&mr,Rt[7]=qt^~sr&wr,Rt[16]=bo^~vo&br,Rt[17]=xo^~wo&Ar,Rt[26]=_o^~To&Eo,Rt[27]=Ro^~Io&Co,Rt[36]=Mo^~Fo&Po,Rt[37]=Bo^~Uo&jo,Rt[46]=qo^~Qo&zo,Rt[47]=Ko^~Yo&Vo,Rt[8]=er^~mr&ir,Rt[9]=sr^~wr&Tt,Rt[18]=vo^~br&xr,Rt[19]=wo^~Ar&Sr,Rt[28]=To^~Eo&So,Rt[29]=Io^~Co&Ao,Rt[38]=Fo^~Po&No,Rt[39]=Uo^~jo&Do,Rt[48]=Qo^~zo&Ho,Rt[49]=Yo^~Vo&Wo,Rt[0]^=pt[Zt],Rt[1]^=pt[Zt+1]};if(st)et.exports=Wt;else for(Xt=0;Xtot+MULTIADDR_LENGTH_SIZE+it.bytes.length,0),tt=new Uint8Array(o),rt=new DataView(tt.buffer);let nt=0;return et.forEach(ot=>{if(ot.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");rt.setUint16(nt,ot.bytes.length),nt+=MULTIADDR_LENGTH_SIZE,tt.set(ot.bytes,nt),nt+=ot.bytes.length}),tt}function encodeWaku2(et){let o=0;return et.lightPush&&(o+=1),o=o<<1,et.filter&&(o+=1),o=o<<1,et.store&&(o+=1),o=o<<1,et.relay&&(o+=1),o}function decodeWaku2(et){const o={relay:!1,store:!1,filter:!1,lightPush:!1};return et%2&&(o.relay=!0),et=et>>1,et%2&&(o.store=!0),et=et>>1,et%2&&(o.filter=!0),et=et>>1,et%2&&(o.lightPush=!0),o}class RawEnr extends Map{constructor(tt={},rt=BigInt(1),nt){super(Object.entries(tt));wt(this,"seq");wt(this,"signature");this.seq=rt,this.signature=nt}set(tt,rt){return this.signature=void 0,this.seq++,super.set(tt,rt)}get id(){const tt=this.get("id");if(!tt)throw new Error("id not found.");return bytesToUtf8(tt)}get publicKey(){switch(this.id){case"v4":return this.get("secp256k1");default:throw new Error(ERR_INVALID_ID)}}get rs(){const tt=this.get("rs");if(tt)return decodeRelayShard(tt)}get rsv(){const tt=this.get("rsv");if(tt)return decodeRelayShard(tt)}get ip(){return getStringValue(this,"ip","ip4")}set ip(tt){setStringValue(this,"ip","ip4",tt)}get tcp(){return getNumberAsStringValue(this,"tcp","tcp")}set tcp(tt){setNumberAsStringValue(this,"tcp","tcp",tt)}get udp(){return getNumberAsStringValue(this,"udp","udp")}set udp(tt){setNumberAsStringValue(this,"udp","udp",tt)}get ip6(){return getStringValue(this,"ip6","ip6")}set ip6(tt){setStringValue(this,"ip6","ip6",tt)}get tcp6(){return getNumberAsStringValue(this,"tcp6","tcp")}set tcp6(tt){setNumberAsStringValue(this,"tcp6","tcp",tt)}get udp6(){return getNumberAsStringValue(this,"udp6","udp")}set udp6(tt){setNumberAsStringValue(this,"udp6","udp",tt)}get multiaddrs(){const tt=this.get("multiaddrs");if(tt)return decodeMultiaddrs(tt)}set multiaddrs(tt){deleteUndefined(this,"multiaddrs",tt,encodeMultiaddrs)}get waku2(){const tt=this.get("waku2");if(tt)return decodeWaku2(tt[0])}set waku2(tt){deleteUndefined(this,"waku2",tt,rt=>new Uint8Array([encodeWaku2(rt)]))}}function getStringValue(et,o,tt){const rt=et.get(o);if(rt)return convertToString(tt,rt)}function getNumberAsStringValue(et,o,tt){const rt=et.get(o);if(rt)return Number(convertToString(tt,rt))}function setStringValue(et,o,tt,rt){deleteUndefined(et,o,rt,convertToBytes.bind({},tt))}function setNumberAsStringValue(et,o,tt,rt){setStringValue(et,o,tt,rt==null?void 0:rt.toString(10))}function deleteUndefined(et,o,tt,rt){tt!==void 0?et.set(o,rt(tt)):et.delete(o)}async function sign(et,o){return sign$1(keccak256(o),et,{der:!1})}function nodeId(et){const tt=Point.fromHex(et).toRawBytes(!1);return bytesToHex$1(keccak256(tt.slice(1)))}const log$9=new Logger$1("enr");var TransportProtocol;(function(et){et.TCP="tcp",et.UDP="udp"})(TransportProtocol||(TransportProtocol={}));var TransportProtocolPerIpVersion;(function(et){et.TCP4="tcp4",et.UDP4="udp4",et.TCP6="tcp6",et.UDP6="udp6"})(TransportProtocolPerIpVersion||(TransportProtocolPerIpVersion={}));const ss=class ss extends RawEnr{constructor(){super(...arguments);wt(this,"peerId");wt(this,"getLocationMultiaddr",locationMultiaddrFromEnrFields.bind({},this))}static create(tt={},rt=BigInt(1),nt){const ot=new ss(tt,rt,nt);try{const it=ot.publicKey;it&&(ot.peerId=createPeerIdFromPublicKey(it))}catch(it){log$9.error("Could not calculate peer id for ENR",it)}return ot}get nodeId(){switch(this.id){case"v4":return this.publicKey?nodeId(this.publicKey):void 0;default:throw new Error(ERR_INVALID_ID)}}get shardInfo(){return this.rs&&this.rsv&&log$9.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(tt){const rt=tt.protoNames();if(rt.length!==2&&rt[1]!=="udp"&&rt[1]!=="tcp")throw new Error("Invalid multiaddr");const nt=tt.tuples();if(!nt[0][1]||!nt[1][1])throw new Error("Invalid multiaddr");nt[0][0]===4?(this.set("ip",nt[0][1]),this.set(rt[1],nt[1][1])):(this.set("ip6",nt[0][1]),this.set(rt[1]+"6",nt[1][1]))}getAllLocationMultiaddrs(){const tt=[];for(const nt of Object.values(TransportProtocolPerIpVersion)){const ot=this.getLocationMultiaddr(nt);ot&&tt.push(ot)}const rt=this.multiaddrs??[];return tt.concat(rt).map(nt=>this.peerId?nt.encapsulate(`/p2p/${this.peerId.toString()}`):nt)}get peerInfo(){const tt=this.peerId;if(tt)return{id:tt,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(tt){if(this.peerId){const rt=this.getLocationMultiaddr(tt);if(rt)return rt.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const tt=this.peerId;return this.multiaddrs.map(rt=>rt.encapsulate(`/p2p/${tt.toString()}`))}return[]}verify(tt,rt){if(!this.get("id")||this.id!=="v4")throw new Error(ERR_INVALID_ID);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return verifySignature(rt,keccak256(tt),this.publicKey)}async sign(tt,rt){switch(this.id){case"v4":this.signature=await sign(rt,tt);break;default:throw new Error(ERR_INVALID_ID)}return this.signature}};wt(ss,"RECORD_PREFIX","enr:");let ENR=ss;const version$2="logger/5.7.0";let _permanentCensorErrors=!1,_censorErrors=!1;const LogLevels={debug:1,default:2,info:2,warning:3,error:4,off:5};let _logLevel=LogLevels.default,_globalLogger=null;function _checkNormalize(){try{const et=[];if(["NFD","NFC","NFKD","NFKC"].forEach(o=>{try{if("test".normalize(o)!=="test")throw new Error("bad normalize")}catch{et.push(o)}}),et.length)throw new Error("missing "+et.join(", "));if("é".normalize("NFD")!=="é")throw new Error("broken implementation")}catch(et){return et.message}return null}const _normalizeError=_checkNormalize();var LogLevel;(function(et){et.DEBUG="DEBUG",et.INFO="INFO",et.WARNING="WARNING",et.ERROR="ERROR",et.OFF="OFF"})(LogLevel||(LogLevel={}));var ErrorCode;(function(et){et.UNKNOWN_ERROR="UNKNOWN_ERROR",et.NOT_IMPLEMENTED="NOT_IMPLEMENTED",et.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",et.NETWORK_ERROR="NETWORK_ERROR",et.SERVER_ERROR="SERVER_ERROR",et.TIMEOUT="TIMEOUT",et.BUFFER_OVERRUN="BUFFER_OVERRUN",et.NUMERIC_FAULT="NUMERIC_FAULT",et.MISSING_NEW="MISSING_NEW",et.INVALID_ARGUMENT="INVALID_ARGUMENT",et.MISSING_ARGUMENT="MISSING_ARGUMENT",et.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",et.CALL_EXCEPTION="CALL_EXCEPTION",et.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",et.NONCE_EXPIRED="NONCE_EXPIRED",et.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",et.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",et.TRANSACTION_REPLACED="TRANSACTION_REPLACED",et.ACTION_REJECTED="ACTION_REJECTED"})(ErrorCode||(ErrorCode={}));const HEX="0123456789abcdef";class Logger{constructor(o){Object.defineProperty(this,"version",{enumerable:!0,value:o,writable:!1})}_log(o,tt){const rt=o.toLowerCase();LogLevels[rt]==null&&this.throwArgumentError("invalid log level name","logLevel",o),!(_logLevel>LogLevels[rt])&&console.log.apply(console,tt)}debug(...o){this._log(Logger.levels.DEBUG,o)}info(...o){this._log(Logger.levels.INFO,o)}warn(...o){this._log(Logger.levels.WARNING,o)}makeError(o,tt,rt){if(_censorErrors)return this.makeError("censored error",tt,{});tt||(tt=Logger.errors.UNKNOWN_ERROR),rt||(rt={});const nt=[];Object.keys(rt).forEach(at=>{const ct=rt[at];try{if(ct instanceof Uint8Array){let lt="";for(let dt=0;dt>4],lt+=HEX[ct[dt]&15];nt.push(at+"=Uint8Array(0x"+lt+")")}else nt.push(at+"="+JSON.stringify(ct))}catch{nt.push(at+"="+JSON.stringify(rt[at].toString()))}}),nt.push(`code=${tt}`),nt.push(`version=${this.version}`);const ot=o;let it="";switch(tt){case ErrorCode.NUMERIC_FAULT:{it="NUMERIC_FAULT";const at=o;switch(at){case"overflow":case"underflow":case"division-by-zero":it+="-"+at;break;case"negative-power":case"negative-width":it+="-unsupported";break;case"unbound-bitwise-result":it+="-unbound-result";break}break}case ErrorCode.CALL_EXCEPTION:case ErrorCode.INSUFFICIENT_FUNDS:case ErrorCode.MISSING_NEW:case ErrorCode.NONCE_EXPIRED:case ErrorCode.REPLACEMENT_UNDERPRICED:case ErrorCode.TRANSACTION_REPLACED:case ErrorCode.UNPREDICTABLE_GAS_LIMIT:it=tt;break}it&&(o+=" [ See: https://links.ethers.org/v5-errors-"+it+" ]"),nt.length&&(o+=" ("+nt.join(", ")+")");const st=new Error(o);return st.reason=ot,st.code=tt,Object.keys(rt).forEach(function(at){st[at]=rt[at]}),st}throwError(o,tt,rt){throw this.makeError(o,tt,rt)}throwArgumentError(o,tt,rt){return this.throwError(o,Logger.errors.INVALID_ARGUMENT,{argument:tt,value:rt})}assert(o,tt,rt,nt){o||this.throwError(tt,rt,nt)}assertArgument(o,tt,rt,nt){o||this.throwArgumentError(tt,rt,nt)}checkNormalize(o){_normalizeError&&this.throwError("platform missing String.prototype.normalize",Logger.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:_normalizeError})}checkSafeUint53(o,tt){typeof o=="number"&&(tt==null&&(tt="value not safe"),(o<0||o>=9007199254740991)&&this.throwError(tt,Logger.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:o}),o%1&&this.throwError(tt,Logger.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:o}))}checkArgumentCount(o,tt,rt){rt?rt=": "+rt:rt="",ott&&this.throwError("too many arguments"+rt,Logger.errors.UNEXPECTED_ARGUMENT,{count:o,expectedCount:tt})}checkNew(o,tt){(o===Object||o==null)&&this.throwError("missing new",Logger.errors.MISSING_NEW,{name:tt.name})}checkAbstract(o,tt){o===tt?this.throwError("cannot instantiate abstract class "+JSON.stringify(tt.name)+" directly; use a sub-class",Logger.errors.UNSUPPORTED_OPERATION,{name:o.name,operation:"new"}):(o===Object||o==null)&&this.throwError("missing new",Logger.errors.MISSING_NEW,{name:tt.name})}static globalLogger(){return _globalLogger||(_globalLogger=new Logger(version$2)),_globalLogger}static setCensorship(o,tt){if(!o&&tt&&this.globalLogger().throwError("cannot permanently disable censorship",Logger.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),_permanentCensorErrors){if(!o)return;this.globalLogger().throwError("error censorship permanent",Logger.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}_censorErrors=!!o,_permanentCensorErrors=!!tt}static setLogLevel(o){const tt=LogLevels[o.toLowerCase()];if(tt==null){Logger.globalLogger().warn("invalid log level - "+o);return}_logLevel=tt}static from(o){return new Logger(o)}}Logger.errors=ErrorCode;Logger.levels=LogLevel;const version$1="bytes/5.7.0",logger$1=new Logger(version$1);function isHexable(et){return!!et.toHexString}function addSlice(et){return et.slice||(et.slice=function(){const o=Array.prototype.slice.call(arguments);return addSlice(new Uint8Array(Array.prototype.slice.apply(et,o)))}),et}function isBytesLike(et){return isHexString(et)&&!(et.length%2)||isBytes(et)}function isInteger(et){return typeof et=="number"&&et==et&&et%1===0}function isBytes(et){if(et==null)return!1;if(et.constructor===Uint8Array)return!0;if(typeof et=="string"||!isInteger(et.length)||et.length<0)return!1;for(let o=0;o=256)return!1}return!0}function arrayify(et,o){if(o||(o={}),typeof et=="number"){logger$1.checkSafeUint53(et,"invalid arrayify value");const tt=[];for(;et;)tt.unshift(et&255),et=parseInt(String(et/256));return tt.length===0&&tt.push(0),addSlice(new Uint8Array(tt))}if(o.allowMissingPrefix&&typeof et=="string"&&et.substring(0,2)!=="0x"&&(et="0x"+et),isHexable(et)&&(et=et.toHexString()),isHexString(et)){let tt=et.substring(2);tt.length%2&&(o.hexPad==="left"?tt="0"+tt:o.hexPad==="right"?tt+="0":logger$1.throwArgumentError("hex data is odd-length","value",et));const rt=[];for(let nt=0;nt>4]+HexCharacters[nt&15]}return tt}return logger$1.throwArgumentError("invalid hexlify value","value",et)}const version="rlp/5.7.0",logger=new Logger(version);function arrayifyInteger(et){const o=[];for(;et;)o.unshift(et&255),et>>=8;return o}function unarrayifyInteger(et,o,tt){let rt=0;for(let nt=0;nto+1+rt&&logger.throwError("child data too short",Logger.errors.BUFFER_OVERRUN,{})}return{consumed:1+rt,result:nt}}function _decode(et,o){if(et.length===0&&logger.throwError("data too short",Logger.errors.BUFFER_OVERRUN,{}),et[o]>=248){const tt=et[o]-247;o+1+tt>et.length&&logger.throwError("data short segment too short",Logger.errors.BUFFER_OVERRUN,{});const rt=unarrayifyInteger(et,o+1,tt);return o+1+tt+rt>et.length&&logger.throwError("data long segment too short",Logger.errors.BUFFER_OVERRUN,{}),_decodeChildren(et,o,o+1+tt,tt+rt)}else if(et[o]>=192){const tt=et[o]-192;return o+1+tt>et.length&&logger.throwError("data array too short",Logger.errors.BUFFER_OVERRUN,{}),_decodeChildren(et,o,o+1,tt)}else if(et[o]>=184){const tt=et[o]-183;o+1+tt>et.length&&logger.throwError("data array too short",Logger.errors.BUFFER_OVERRUN,{});const rt=unarrayifyInteger(et,o+1,tt);o+1+tt+rt>et.length&&logger.throwError("data array too short",Logger.errors.BUFFER_OVERRUN,{});const nt=hexlify(et.slice(o+1+tt,o+1+tt+rt));return{consumed:1+tt+rt,result:nt}}else if(et[o]>=128){const tt=et[o]-128;o+1+tt>et.length&&logger.throwError("data too short",Logger.errors.BUFFER_OVERRUN,{});const rt=hexlify(et.slice(o+1,o+1+tt));return{consumed:1+tt,result:rt}}return{consumed:1,result:hexlify(et[o])}}function decode$8(et){const o=arrayify(et),tt=_decode(o,0);return tt.consumed!==o.length&&logger.throwArgumentError("invalid rlp data","data",et),tt.result}function base$1(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$2=base$1,_brrp__multiformats_scope_baseX$1=src$2;const coerce$2=et=>{if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")},fromString$3=et=>new TextEncoder().encode(et),toString$8=et=>new TextDecoder().decode(et);let Encoder$1=class{constructor(o,tt,rt){this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}},Decoder$1=class{constructor(o,tt,rt){if(this.name=o,this.prefix=tt,tt.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=tt.codePointAt(0),this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or$1(this,o)}},ComposedDecoder$1=class{constructor(o){this.decoders=o}or(o){return or$1(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const or$1=(et,o)=>new ComposedDecoder$1({...et.decoders||{[et.prefix]:et},...o.decoders||{[o.prefix]:o}});let Codec$1=class{constructor(o,tt,rt,nt){this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder$1(o,tt,rt),this.decoder=new Decoder$1(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}};const from$2=({name:et,prefix:o,encode:tt,decode:rt})=>new Codec$1(et,o,tt,rt),baseX$1=({prefix:et,name:o,alphabet:tt})=>{const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX$1(tt,o);return from$2({prefix:et,name:o,encode:rt,decode:ot=>coerce$2(nt(ot))})},decode$7=(et,o,tt,rt)=>{const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it},encode$6=(et,o,tt)=>{const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it&&(ot+=o[nt&st<from$2({prefix:o,name:et,encode(nt){return encode$6(nt,rt,tt)},decode(nt){return decode$7(nt,rt,tt,et)}}),identity$1=from$2({prefix:"\0",name:"identity",encode:et=>toString$8(et),decode:et=>fromString$3(et)}),identityBase$1=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$1},Symbol.toStringTag,{value:"Module"})),base2$2=rfc4648$1({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$3=Object.freeze(Object.defineProperty({__proto__:null,base2:base2$2},Symbol.toStringTag,{value:"Module"})),base8$2=rfc4648$1({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$3=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$2},Symbol.toStringTag,{value:"Module"})),base10$2=baseX$1({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$3=Object.freeze(Object.defineProperty({__proto__:null,base10:base10$2},Symbol.toStringTag,{value:"Module"})),base16$2=rfc4648$1({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper$1=rfc4648$1({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$3=Object.freeze(Object.defineProperty({__proto__:null,base16:base16$2,base16upper:base16upper$1},Symbol.toStringTag,{value:"Module"})),base32$4=rfc4648$1({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$1=rfc4648$1({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$1=rfc4648$1({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$1=rfc4648$1({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$1=rfc4648$1({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$1=rfc4648$1({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$1=rfc4648$1({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$1=rfc4648$1({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$1=rfc4648$1({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$5=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$4,base32hex:base32hex$1,base32hexpad:base32hexpad$1,base32hexpadupper:base32hexpadupper$1,base32hexupper:base32hexupper$1,base32pad:base32pad$1,base32padupper:base32padupper$1,base32upper:base32upper$1,base32z:base32z$1},Symbol.toStringTag,{value:"Module"})),base36$2=baseX$1({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$1=baseX$1({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$3=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$2,base36upper:base36upper$1},Symbol.toStringTag,{value:"Module"})),base58btc$1=baseX$1({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$1=baseX$1({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$1=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$1,base58flickr:base58flickr$1},Symbol.toStringTag,{value:"Module"})),base64$4=rfc4648$1({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$1=rfc4648$1({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$1=rfc4648$1({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$1=rfc4648$1({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$5=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$4,base64pad:base64pad$1,base64url:base64url$1,base64urlpad:base64urlpad$1},Symbol.toStringTag,{value:"Module"})),alphabet$1=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),alphabetBytesToChars$1=alphabet$1.reduce((et,o,tt)=>(et[tt]=o,et),[]),alphabetCharsToBytes$1=alphabet$1.reduce((et,o,tt)=>(et[o.codePointAt(0)]=tt,et),[]);function encode$5(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars$1[tt],o),"")}function decode$6(et){const o=[];for(const tt of et){const rt=alphabetCharsToBytes$1[tt.codePointAt(0)];if(rt===void 0)throw new Error(`Non-base256emoji character: ${tt}`);o.push(rt)}return new Uint8Array(o)}const base256emoji$2=from$2({prefix:"🚀",name:"base256emoji",encode:encode$5,decode:decode$6}),base256emoji$3=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$2},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases$1={...identityBase$1,...base2$3,...base8$3,...base10$3,...base16$3,...base32$5,...base36$3,...base58$1,...base64$5,...base256emoji$3};function createCodec$1(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$4=createCodec$1("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii$1=createCodec$1("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe$h(et.length);for(let tt=0;ttv4Regex$1.test(et),encode(et,o,tt){tt=~~tt,o=o||new Uint8Array(tt+v4Size);const rt=et.length;let nt=0;for(let ot=0;otet.length>0&&v6Regex$1.test(et),encode(et,o,tt){tt=~~tt;let rt=tt+v6Size,nt=-1,ot=0,it=0,st=!0,at=!1;o=o||new Uint8Array(tt+v6Size);for(let ct=0;ct>8),tt=97?lt-=87:lt>=65?lt-=55:(lt-=48,it=it*10+lt),ot=(ot<<4)+lt)}if(st===!1)at===!0?(tt>8),tt=nt+2;ct--)o[ct]=o[ct-2];o[nt]=0,o[nt+1]=0,nt=tt}if(nt!==tt&&nt!==-1)for(tt>rt-2&&(tt=rt-2);rt>nt;)o[--rt]=ttnt?o[--tt]:0;else for(;tt=SURROGATE_B||(et.charCodeAt(ot)&64512)!==SURROGATE_B?o+=3:(rt=ot,o+=4)}}return o}function encode$3(et,o,tt){const rt=et.length;tt==null&&(tt=0),o===void 0&&(o=new Uint8Array(encodingLength$1(et)+tt));let nt=tt;for(let ot=0;ot>6,o[nt++]=128|it&63;else if((it&63488)!==SURROGATE_A)o[nt++]=224|(it&61440)>>12,o[nt++]=128|(it&4032)>>6,o[nt++]=128|it&63;else{const st=ot+1;if(st===rt||it>=SURROGATE_B)o[nt++]=239,o[nt++]=191,o[nt++]=189;else{const at=et.charCodeAt(st);(at&64512)!==SURROGATE_B?(o[nt++]=239,o[nt++]=191,o[nt++]=189):(ot=st,it=65536|(it&1023)<<10|at&1023,o[nt++]=240|(it&1835008)>>18,o[nt++]=128|(it&258048)>>12,o[nt++]=128|(it&4032)>>6,o[nt++]=128|it&63)}}}return encode$3.bytes=nt-tt,o}encode$3.bytes=0;function decode$4(et,o,tt){let rt="";o==null&&(o=0),tt==null&&(tt=et.length);for(let nt=o;nt191&&ot<224)it=(ot&31)<<6|et[nt++]&63;else if(ot>239&&ot<365){it=((ot&7)<<18|(et[nt++]&63)<<12|(et[nt++]&63)<<6|et[nt++]&63)-65536;const st=SURROGATE_A|it>>10&1023;rt+=String.fromCharCode(st),it=SURROGATE_B|it&1023}else it=(ot&15)<<12|(et[nt++]&63)<<6|et[nt++]&63;rt+=String.fromCharCode(it)}return decode$4.bytes=tt-o,rt}decode$4.bytes=0;const isU8Arr=et=>et instanceof Uint8Array;function bytelength(et){return typeof et=="string"?encodingLength$1(et):et.byteLength}function from$1(et){return et instanceof Uint8Array?et:Array.isArray(et)?new Uint8Array(et):encode$3(et)}function write(et,o,tt){if(typeof o!="string")throw new Error("unknown input type");return encode$3(o,et,tt),encode$3.bytes}const P_24=Math.pow(2,24),P_16=Math.pow(2,16),P_8=Math.pow(2,8),readUInt32BE=(et,o)=>et[o]*P_24+et[o+1]*P_16+et[o+2]*P_8+et[o+3],readUInt16BE=(et,o)=>et[o]<<8|et[o+1],writeUInt32BE=(et,o,tt)=>(o=+o,et[tt+3]=o,o=o>>>8,et[tt+2]=o,o=o>>>8,et[tt+1]=o,o=o>>>8,et[tt]=o,tt+4),writeUInt16BE=(et,o,tt)=>(et[tt]=o>>8,et[tt+1]=o&255,tt+2);function copy(et,o,tt,rt,nt){return tt<0&&(rt-=tt,tt=0),rt<0&&(rt=0),nt<0?new Uint8Array(0):tt>=o.length||rt>=nt?0:_copyActual(et,o,tt,rt,nt)}function _copyActual(et,o,tt,rt,nt){nt-rt>o.length-tt&&(nt=rt+o.length-tt);let ot=nt-rt;const it=et.length-rt;return ot>it&&(ot=it),(rt!==0||ntet)}}const name$1=codec({encode(et,o,tt){o||(o=new Uint8Array(name$1.encodingLength(et))),tt||(tt=0);const rt=tt,nt=et.replace(/^\.|\.$/gm,"");if(nt.length){const ot=nt.split(".");for(let it=0;it=et.length)throw new Error("Cannot decode name (buffer overflow)");const st=et[o++];if(ot+=it?0:1,st===0)break;if(st&192)if((st&192)===192){if(o+1>et.length)throw new Error("Cannot decode name (buffer overflow)");const at=readUInt16BE(et,o-1)-49152;if(at>=rt)throw new Error("Cannot decode name (bad pointer)");o=at,rt=at,ot+=it?0:1,it=!0}else throw new Error("Cannot decode name (bad label)");else{if(o+st>et.length)throw new Error("Cannot decode name (buffer overflow)");if(nt+=st+1,nt>254)throw new Error("Cannot decode name (name too long)");tt.push(decode$4(et,o,o+st)),o+=st,ot+=it?0:st}}return name$1.decode.bytes=ot,tt.length===0?".":tt.join(".")},encodingLength(et){return et==="."||et===".."?1:bytelength(et.replace(/^\.|\.$/gm,""))+2}}),string$3=codec({encode(et,o,tt){o||(o=new Uint8Array(string$3.encodingLength(et))),tt||(tt=0);const rt=write(o,et,tt+1);return o[tt]=rt,string$3.encode.bytes=rt+1,o},decode(et,o){o||(o=0);const tt=et[o],rt=decode$4(et,o+1,o+1+tt);return string$3.decode.bytes=tt+1,rt},encodingLength(et){return bytelength(et)+1}}),header=codec({bytes:12,encode(et,o,tt){o||(o=new Uint8Array(header.encodingLength(et))),tt||(tt=0);const rt=(et.flags||0)&32767,nt=et.type==="response"?RESPONSE_FLAG:QUERY_FLAG;return writeUInt16BE(o,et.id||0,tt),writeUInt16BE(o,rt|nt,tt+2),writeUInt16BE(o,et.questions.length,tt+4),writeUInt16BE(o,et.answers.length,tt+6),writeUInt16BE(o,et.authorities.length,tt+8),writeUInt16BE(o,et.additionals.length,tt+10),o},decode(et,o){if(o||(o=0),et.length<12)throw new Error("Header must be 12 bytes");const tt=readUInt16BE(et,o+2);return{id:readUInt16BE(et,o),type:tt&RESPONSE_FLAG?"response":"query",flags:tt&32767,flag_qr:(tt>>15&1)===1,opcode:toString$5(tt>>11&15),flag_aa:(tt>>10&1)===1,flag_tc:(tt>>9&1)===1,flag_rd:(tt>>8&1)===1,flag_ra:(tt>>7&1)===1,flag_z:(tt>>6&1)===1,flag_ad:(tt>>5&1)===1,flag_cd:(tt>>4&1)===1,rcode:toString$6(tt&15),questions:new Array(readUInt16BE(et,o+4)),answers:new Array(readUInt16BE(et,o+6)),authorities:new Array(readUInt16BE(et,o+8)),additionals:new Array(readUInt16BE(et,o+10))}},encodingLength(){return 12}}),runknown=codec({encode(et,o,tt){o||(o=new Uint8Array(runknown.encodingLength(et))),tt||(tt=0);const rt=et.length;return writeUInt16BE(o,rt,tt),copy(et,o,tt+2,0,rt),runknown.encode.bytes=rt+2,o},decode(et,o){o||(o=0);const tt=readUInt16BE(et,o),rt=et.slice(o+2,o+2+tt);return runknown.decode.bytes=tt+2,rt},encodingLength(et){return et.length+2}}),rns=codec({encode(et,o,tt){return o||(o=new Uint8Array(rns.encodingLength(et))),tt||(tt=0),name$1.encode(et,o,tt+2),writeUInt16BE(o,name$1.encode.bytes,tt),rns.encode.bytes=name$1.encode.bytes+2,o},decode(et,o){o||(o=0);const tt=readUInt16BE(et,o),rt=name$1.decode(et,o+2);return rns.decode.bytes=tt+2,rt},encodingLength(et){return name$1.encodingLength(et)+2}}),rsoa=codec({encode(et,o,tt){o||(o=new Uint8Array(rsoa.encodingLength(et))),tt||(tt=0);const rt=tt;return tt+=2,name$1.encode(et.mname,o,tt),tt+=name$1.encode.bytes,name$1.encode(et.rname,o,tt),tt+=name$1.encode.bytes,writeUInt32BE(o,et.serial||0,tt),tt+=4,writeUInt32BE(o,et.refresh||0,tt),tt+=4,writeUInt32BE(o,et.retry||0,tt),tt+=4,writeUInt32BE(o,et.expire||0,tt),tt+=4,writeUInt32BE(o,et.minimum||0,tt),tt+=4,writeUInt16BE(o,tt-rt-2,rt),rsoa.encode.bytes=tt-rt,o},decode(et,o){o||(o=0);const tt=o,rt={};return o+=2,rt.mname=name$1.decode(et,o),o+=name$1.decode.bytes,rt.rname=name$1.decode(et,o),o+=name$1.decode.bytes,rt.serial=readUInt32BE(et,o),o+=4,rt.refresh=readUInt32BE(et,o),o+=4,rt.retry=readUInt32BE(et,o),o+=4,rt.expire=readUInt32BE(et,o),o+=4,rt.minimum=readUInt32BE(et,o),o+=4,rsoa.decode.bytes=o-tt,rt},encodingLength(et){return 22+name$1.encodingLength(et.mname)+name$1.encodingLength(et.rname)}}),rtxt=codec({encode(et,o,tt){Array.isArray(et)||(et=[et]);for(let nt=0;nt0;){const ot=et[o++];if(--rt,rtnew Uint8Array(et),roption=codec({encode(et,o,tt){o||(o=new Uint8Array(roption.encodingLength(et))),tt||(tt=0);const rt=tt,nt=toCode(et.code);if(writeUInt16BE(o,nt,tt),tt+=2,et.data)writeUInt16BE(o,et.data.length,tt),tt+=2,copy(et.data,o,tt),tt+=et.data.length;else switch(nt){case 8:{const ot=et.sourcePrefixLength||0,it=et.family||familyOf(et.ip),st=encode$4(et.ip,alloc),at=Math.ceil(ot/8);writeUInt16BE(o,at+4,tt),tt+=2,writeUInt16BE(o,it,tt),tt+=2,o[tt++]=ot,o[tt++]=et.scopePrefixLength||0,copy(st,o,tt,0,at),tt+=at}break;case 11:et.timeout?(writeUInt16BE(o,2,tt),tt+=2,writeUInt16BE(o,et.timeout,tt),tt+=2):(writeUInt16BE(o,0,tt),tt+=2);break;case 12:{const ot=et.length||0;writeUInt16BE(o,ot,tt),tt+=2,o.fill(0,tt,tt+ot),tt+=ot}break;case 14:{const ot=et.tags.length*2;writeUInt16BE(o,ot,tt),tt+=2;for(const it of et.tags)writeUInt16BE(o,it,tt),tt+=2}break;default:throw new Error(`Unknown roption code: ${et.code}`)}return roption.encode.bytes=tt-rt,o},decode(et,o){o||(o=0);const tt={};tt.code=readUInt16BE(et,o),tt.type=toString$3(tt.code),o+=2;const rt=readUInt16BE(et,o);switch(o+=2,tt.data=et.slice(o,o+rt),tt.code){case 8:tt.family=readUInt16BE(et,o),o+=2,tt.sourcePrefixLength=et[o++],tt.scopePrefixLength=et[o++];{const nt=new Uint8Array(tt.family===1?4:16);copy(et,nt,0,o,o+rt-4),tt.ip=decode$5(nt)}break;case 11:rt>0&&(tt.timeout=readUInt16BE(et,o),o+=2);break;case 14:tt.tags=[];for(let nt=0;nt0;)rt[ot++]=roption.decode(et,o),o+=roption.decode.bytes,nt-=roption.decode.bytes;return ropt.decode.bytes=o-tt,rt},encodingLength(et){return 2+encodingLengthList(et||[],roption)}}),rdnskey=codec({encode(et,o,tt){o||(o=new Uint8Array(rdnskey.encodingLength(et))),tt||(tt=0);const rt=tt,nt=et.key;if(!isU8Arr(nt))throw new Error("Key must be a Buffer");return tt+=2,writeUInt16BE(o,et.flags,tt),tt+=2,o[tt]=rdnskey.PROTOCOL_DNSSEC,tt+=1,o[tt]=et.algorithm,tt+=1,copy(nt,o,tt,0,nt.length),tt+=nt.length,rdnskey.encode.bytes=tt-rt,writeUInt16BE(o,rdnskey.encode.bytes-2,rt),o},decode(et,o){o||(o=0);const tt=o,rt={},nt=readUInt16BE(et,o);if(o+=2,rt.flags=readUInt16BE(et,o),o+=2,et[o]!==rdnskey.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return o+=1,rt.algorithm=et[o],o+=1,rt.key=et.slice(o,tt+nt+2),o+=rt.key.length,rdnskey.decode.bytes=o-tt,rt},encodingLength(et){return 6+bytelength(et.key)}});rdnskey.PROTOCOL_DNSSEC=3;rdnskey.ZONE_KEY=128;rdnskey.SECURE_ENTRYPOINT=32768;const rrrsig=codec({encode(et,o,tt){o||(o=new Uint8Array(rrrsig.encodingLength(et))),tt||(tt=0);const rt=tt,nt=et.signature;if(!isU8Arr(nt))throw new Error("Signature must be a Buffer");return tt+=2,writeUInt16BE(o,toType(et.typeCovered),tt),tt+=2,o[tt]=et.algorithm,tt+=1,o[tt]=et.labels,tt+=1,writeUInt32BE(o,et.originalTTL,tt),tt+=4,writeUInt32BE(o,et.expiration,tt),tt+=4,writeUInt32BE(o,et.inception,tt),tt+=4,writeUInt16BE(o,et.keyTag,tt),tt+=2,name$1.encode(et.signersName,o,tt),tt+=name$1.encode.bytes,copy(nt,o,tt,0,nt.length),tt+=nt.length,rrrsig.encode.bytes=tt-rt,writeUInt16BE(o,rrrsig.encode.bytes-2,rt),o},decode(et,o){o||(o=0);const tt=o,rt={},nt=readUInt16BE(et,o);return o+=2,rt.typeCovered=toString$7(readUInt16BE(et,o)),o+=2,rt.algorithm=et[o],o+=1,rt.labels=et[o],o+=1,rt.originalTTL=readUInt32BE(et,o),o+=4,rt.expiration=readUInt32BE(et,o),o+=4,rt.inception=readUInt32BE(et,o),o+=4,rt.keyTag=readUInt16BE(et,o),o+=2,rt.signersName=name$1.decode(et,o),o+=name$1.decode.bytes,rt.signature=et.slice(o,tt+nt+2),o+=rt.signature.length,rrrsig.decode.bytes=o-tt,rt},encodingLength(et){return 20+name$1.encodingLength(et.signersName)+bytelength(et.signature)}}),rrp=codec({encode(et,o,tt){o||(o=new Uint8Array(rrp.encodingLength(et))),tt||(tt=0);const rt=tt;return tt+=2,name$1.encode(et.mbox||".",o,tt),tt+=name$1.encode.bytes,name$1.encode(et.txt||".",o,tt),tt+=name$1.encode.bytes,rrp.encode.bytes=tt-rt,writeUInt16BE(o,rrp.encode.bytes-2,rt),o},decode(et,o){o||(o=0);const tt=o,rt={};return o+=2,rt.mbox=name$1.decode(et,o)||".",o+=name$1.decode.bytes,rt.txt=name$1.decode(et,o)||".",o+=name$1.decode.bytes,rrp.decode.bytes=o-tt,rt},encodingLength(et){return 2+name$1.encodingLength(et.mbox||".")+name$1.encodingLength(et.txt||".")}}),typebitmap=codec({encode(et,o,tt){o||(o=new Uint8Array(typebitmap.encodingLength(et))),tt||(tt=0);const rt=tt,nt=[];for(let ot=0;ot>8]===void 0&&(nt[it>>8]=[]),nt[it>>8][it>>3&31]|=1<<7-(it&7)}for(let ot=0;ot>8]=Math.max(o[nt>>8]||0,nt&255)}let tt=0;for(let rt=0;rt>15&1)===1,tt.options=ropt.decode(et,o+8),o+=8+ropt.decode.bytes;else{const nt=readUInt16BE(et,o+2);tt.ttl=readUInt32BE(et,o+4),tt.class=toString$4(nt&NOT_FLUSH_MASK),tt.flush=!!(nt&FLUSH_MASK);const ot=renc(tt.type);tt.data=ot.decode(et,o+8),o+=8+ot.decode.bytes}return answer.decode.bytes=o-rt,tt},encodingLength(et){const o=et.data!==null&&et.data!==void 0?et.data:et.options;return name$1.encodingLength(et.name)+8+renc(et.type).encodingLength(o)}}),question=codec({encode(et,o,tt){o||(o=new Uint8Array(question.encodingLength(et))),tt||(tt=0);const rt=tt;return name$1.encode(et.name,o,tt),tt+=name$1.encode.bytes,writeUInt16BE(o,toType(et.type),tt),tt+=2,writeUInt16BE(o,toClass(et.class===void 0?"IN":et.class),tt),tt+=2,question.encode.bytes=tt-rt,et},decode(et,o){o||(o=0);const tt=o,rt={};return rt.name=name$1.decode(et,o),o+=name$1.decode.bytes,rt.type=toString$7(readUInt16BE(et,o)),o+=2,rt.class=toString$4(readUInt16BE(et,o)),o+=2,!!(rt.class&QU_MASK)&&(rt.class&=NOT_QU_MASK),question.decode.bytes=o-tt,rt},encodingLength(et){return name$1.encodingLength(et.name)+4}}),RECURSION_DESIRED=256,packet={encode:function(et,o,tt){const rt=!o;rt&&(o=new Uint8Array(encodingLength(et))),tt||(tt=0);const nt=tt;return et.questions||(et.questions=[]),et.answers||(et.answers=[]),et.authorities||(et.authorities=[]),et.additionals||(et.additionals=[]),header.encode(et,o,tt),tt+=header.encode.bytes,tt=encodeList(et.questions,question,o,tt),tt=encodeList(et.answers,answer,o,tt),tt=encodeList(et.authorities,answer,o,tt),tt=encodeList(et.additionals,answer,o,tt),packet.encode.bytes=tt-nt,rt&&encode$2.bytes!==o.length?o.slice(0,encode$2.bytes):o},decode:function(et,o){o||(o=0);const tt=o,rt=header.decode(et,o);return o+=header.decode.bytes,o=decodeList(rt.questions,question,et,o),o=decodeList(rt.answers,answer,et,o),o=decodeList(rt.authorities,answer,et,o),o=decodeList(rt.additionals,answer,et,o),packet.decode.bytes=o-tt,rt},encodingLength:function(et){return header.encodingLength(et)+encodingLengthList(et.questions||[],question)+encodingLengthList(et.answers||[],answer)+encodingLengthList(et.authorities||[],answer)+encodingLengthList(et.additionals||[],answer)}};packet.encode.bytes=0;packet.decode.bytes=0;const encode$2=packet.encode,decode$3=packet.decode,encodingLength=packet.encodingLength;function encodingLengthList(et,o){let tt=0;for(let rt=0;rt255)throw new Error(`Character #${at} in charset [code=${ct}, char=${o.charAt(at)}] is too high! (max=255)`);if(nt[ct]!==0)throw new Error(`Character [code=${ct}, char=${o.charAt(at)}] is more than once in the charset!`);nt[ct]=at,ot[at]=ct}const it=tt.charCodeAt(0),st={name:et,encodingLength(at){const ct=at.length,lt=ct*.75|0;return at.charCodeAt(ct-1)===it?at.charCodeAt(ct-2)===it?lt-2:lt-1:lt},encode(at,ct,lt){ct==null&&(ct=new Uint8Array(st.encodingLength(at))),lt==null&&(lt=0);let dt=at.length;at.charCodeAt(dt-1)===it&&(at.charCodeAt(dt-2)===it?dt-=2:dt-=1);const ht=dt%4,mt=dt-ht;let ft=lt,pt=0;for(;pt>16,ct[ft++]=gt>>8,ct[ft++]=gt,pt+=4}if(ht===3){const gt=nt[at.charCodeAt(pt)]<<10|nt[at.charCodeAt(pt+1)]<<4|nt[at.charCodeAt(pt+2)]>>2;ct[ft++]=gt>>8,ct[ft++]=gt}else ht===2&&(ct[ft++]=nt[at.charCodeAt(pt)]<<2|nt[at.charCodeAt(pt+1)]>>4);return st.encode.bytes=ft-lt,ct},decode(at,ct,lt){ct==null&&(ct=0),lt==null&&(lt=at.length);const dt=lt-ct,ht=dt%3,mt=ct+dt-ht,ft=[];for(let pt=ct;pt>18&63],ot[gt>>12&63],ot[gt>>6&63],ot[gt&63])}if(ht===2){const pt=(at[lt-2]<<8)+at[lt-1];ft.push(ot[pt>>10],ot[pt>>4&63],ot[pt<<2&63]),rt===PREFERS_PADDING&&ft.push(it)}else if(ht===1){const pt=at[lt-1];ft.push(ot[pt>>2],ot[pt<<4&63]),rt===PREFERS_PADDING&&ft.push(it,it)}return st.decode.bytes=dt,String.fromCharCode.apply(String,ft)}};return st}make("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",PREFERS_PADDING);const base64URL=make("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",PREFERS_NO_PADDING);let AbortError=typeof global<"u"?global.AbortError:typeof window<"u"?window.AbortError:null;AbortError||(AbortError=class extends Error{constructor(o="Request aborted."){super(o)}});AbortError.prototype.name="AbortError";AbortError.prototype.code="ABORT_ERR";const URL$1=typeof globalThis<"u"&&globalThis.URL||require("url").URL;class HTTPStatusError extends Error{constructor(o,tt,rt){super("status="+tt+" while requesting "+o+" ["+rt+"]"),this.uri=o,this.status=tt,this.method=rt}toJSON(){return{code:this.code,uri:this.uri,status:this.status,method:this.method,endpoint:this.endpoint}}}HTTPStatusError.prototype.name="HTTPStatusError";HTTPStatusError.prototype.code="HTTP_STATUS";class ResponseError extends Error{constructor(o,tt){super(o),this.cause=tt}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:reduceError(this.cause)}}}ResponseError.prototype.name="ResponseError";ResponseError.prototype.code="RESPONSE_ERR";class TimeoutError extends Error{constructor(o){super("Timeout (t="+o+")."),this.timeout=o}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}TimeoutError.prototype.name="TimeoutError";TimeoutError.prototype.code="ETIMEOUT";const v4Regex=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,v6Regex=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i;function reduceError(et){if(typeof et=="string")return{message:et};try{const tt=JSON.stringify(et);if(tt!=="{}")return JSON.parse(tt)}catch{}const o={message:String(et.message||et)};return et.code!==void 0&&(o.code=String(et.code)),o}const baseParts=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,httpFlags=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/ig,updFlags=/\[(((pk|name)=([^\]]+)))\]/ig;function parseEndpoint(et){const o=baseParts.exec(et),tt=o[2]||"https:",rt=o[3],nt=o[5],ot=o[6],it=o[7];if(tt==="https:"||tt==="http:"){const st=parseFlags(it,httpFlags);return{name:st.name,protocol:tt,ipv4:st.ipv4,ipv6:st.ipv6,host:rt,port:nt,path:ot,method:st.post?"POST":"GET"}}if(tt==="udp:"||tt==="udp4:"||tt==="udp6:"){const st=parseFlags(it,updFlags),at=/^\[(.*)\]$/.exec(rt);if(at&&tt==="udp4:")throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${et})`);if(!at&&tt==="udp6:")throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${et})`);return at?new UDP6Endpoint({protocol:"udp6:",ipv6:at[1],port:nt,pk:st.pk,name:st.name}):new UDP4Endpoint({protocol:"udp4:",ipv4:rt,port:nt,pk:st.pk,name:st.name})}throw new InvalidProtocolError(tt,et)}function parseFlags(et,o){o.lastIndex=0;const tt={};for(;;){const rt=o.exec(et);if(!rt)break;rt[2]?tt[rt[3].toLowerCase()]=rt[4]:tt[rt[1].toLowerCase()]=!0}return tt}class InvalidProtocolError extends Error{constructor(o,tt){super(`Invalid Endpoint: unsupported protocol "${o}" for endpoint: ${tt}, supported protocols: ${supportedProtocols.join(", ")}`),this.protocol=o,this.endpoint=tt}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}InvalidProtocolError.prototype.name="InvalidProtocolError";InvalidProtocolError.prototype.code="EPROTOCOL";const supportedProtocols=["http:","https:","udp4:","udp6:"];class BaseEndpoint{constructor(o,tt){this.name=o.name||null,this.protocol=o.protocol;const rt=typeof o.port=="string"?o.port=parseInt(o.port,10):o.port;if(rt==null)this.port=tt?this.protocol==="https:"?443:80:o.pk?443:53;else{if(typeof rt!="number"&&!isNaN(rt))throw new Error(`Invalid Endpoint: port "${o.port}" needs to be a number: ${JSON.stringify(o)}`);this.port=rt}}toJSON(){return this.toString()}}class UDPEndpoint extends BaseEndpoint{constructor(o){super(o,!1),this.pk=o.pk||null}toString(){const o=this.port!==(this.pk?443:53)?`:${this.port}`:"",tt=this.pk?` [pk=${this.pk}]`:"",rt=this.name?` [name=${this.name}]`:"";return`udp://${this.ipv4||`[${this.ipv6}]`}${o}${tt}${rt}`}}class UDP4Endpoint extends UDPEndpoint{constructor(o){if(super(Object.assign({protocol:"udp4:"},o)),!o.ipv4||typeof o.ipv4!="string")throw new Error(`Invalid Endpoint: .ipv4 "${o.ipv4}" needs to be set: ${JSON.stringify(o)}`);this.ipv4=o.ipv4}}class UDP6Endpoint extends UDPEndpoint{constructor(o){if(super(Object.assign({protocol:"udp6:"},o)),!o.ipv6||typeof o.ipv6!="string")throw new Error(`Invalid Endpoint: .ipv6 "${o.ipv6}" needs to be set: ${JSON.stringify(o)}`);this.ipv6=o.ipv6}}function safeHost(et){return v6Regex.test(et)&&!v4Regex.test(et)?`[${et}]`:et}class HTTPEndpoint extends BaseEndpoint{constructor(o){if(super(Object.assign({protocol:"https:"},o),!0),o.host||(o.ipv4&&(o.host=o.ipv4),o.ipv6&&(o.host=`[${o.ipv6}]`)),!o.host||typeof o.host!="string")throw new Error(`Invalid Endpoint: host "${o.path}" needs to be set: ${JSON.stringify(o)}`);if(this.host=o.host,this.path=o.path||"/dns-query",this.method=/^post$/i.test(o.method)?"POST":"GET",this.ipv4=o.ipv4,this.ipv6=o.ipv6,!this.ipv6){const rt=v6Regex.exec(this.host);rt&&(this.ipv6=rt[1])}this.ipv4||v4Regex.test(this.host)&&(this.ipv4=this.host);const tt=`${this.protocol}//${safeHost(this.host)}:${this.port}${this.path}`;try{this.url=new URL$1(tt)}catch(rt){throw new Error(rt.message+` [${tt}]`)}}toString(){const o=this.protocol==="https:"?"":"http://",tt=this.port!==(this.protocol==="https:"?443:80)?`:${this.port}`:"",rt=this.method!=="GET"?" [post]":"",nt=this.path==="/dns-query"?"":this.path,ot=this.name?` [name=${this.name}]`:"",it=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",st=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${o}${safeHost(this.host)}${tt}${nt}${rt}${it}${st}${ot}`}}function toEndpoint(et){let o;if(typeof et=="string")o=parseEndpoint(et);else{if(typeof et!="object"||et===null||Array.isArray(et))throw new Error(`Can not convert ${et} to an endpoint`);if(et instanceof BaseEndpoint)return et;o=et}(o.protocol===null||o.protocol===void 0)&&(o.protocol="https:");const tt=o.protocol;if(tt==="udp4:")return new UDP4Endpoint(o);if(tt==="udp6:")return new UDP6Endpoint(o);if(tt==="https:"||tt==="http:")return new HTTPEndpoint(o);throw new InvalidProtocolError(tt,JSON.stringify(o))}const contentType="application/dns-message";function noop$1(){}function queryDns(){throw new Error('Only "doh" endpoints are supported in the browser')}async function loadJSON(et,o,tt,rt){const nt=o?o.localStoragePrefix+o.name:null;if(nt)try{const st=JSON.parse(localStorage.getItem(nt));if(st&&st.time>o.maxTime)return st}catch{}const{data:ot}=await requestRaw(et,"GET",null,tt,rt),it={time:Date.now(),data:JSON.parse(decode$4(ot))};if(nt)try{localStorage.setItem(nt,JSON.stringify(it))}catch{it.time=null}return it}function requestRaw(et,o,tt,rt,nt){return new Promise((ot,it)=>{const st=new URL$1(et);o==="GET"&&tt&&(st.search="?dns="+base64URL.decode(tt));const at=st.toString(),ct=new XMLHttpRequest;ct.open(o,at,!0),ct.setRequestHeader("Accept",contentType),o==="POST"&&ct.setRequestHeader("Content-Type",contentType),ct.responseType="arraybuffer",ct.timeout=rt,ct.ontimeout=lt,ct.onreadystatechange=ht,ct.onerror=ft,ct.onload=dt,o==="POST"?ct.send(tt):ct.send(),nt&&nt.addEventListener("abort",pt);function lt(){mt(new TimeoutError(rt));try{ct.abort()}catch{}}function dt(){if(ct.status!==200)mt(new HTTPStatusError(at,ct.status,o));else{let gt;if(typeof ct.response=="string")gt=encode$3(ct.response);else if(ct.response instanceof Uint8Array)gt=ct.response;else if(Array.isArray(ct.response)||ct.response instanceof ArrayBuffer)gt=new Uint8Array(ct.response);else throw new Error("Unprocessable response "+ct.response);mt(null,gt)}}function ht(){if(ct.readyState>1&&ct.status!==200&&ct.status!==0){mt(new HTTPStatusError(at,ct.status,o));try{ct.abort()}catch{}}}let mt=function(gt,yt){mt=noop$1,nt&&nt.removeEventListener("abort",pt),ot(gt?{error:gt,response:ct}:{data:yt,response:ct})};function ft(){mt(ct.status===200?new Error("Inexplicable XHR Error"):new HTTPStatusError(at,ct.status,o))}function pt(){mt(new AbortError);try{ct.abort()}catch{}}})}function request(et,o,tt,rt,nt){return requestRaw(et,o,tt,rt,nt)}function processResolvers$1(et){return et.filter(o=>o.cors||o.endpoint.cors)}const resolvers={data:[{name:"adfree.usableprivacy.net",endpoint:{protocol:"https:",host:"adfree.usableprivacy.net"},description:`Public updns DoH service with advertising, tracker and malware filters. +Hosted in Europe by @usableprivacy, details see: https://docs.usableprivacy.com`,country:"Germany",location:{lat:51.2993,long:9.491},filter:!0},{name:"adguard-dns-doh",endpoint:{protocol:"https:",host:"dns.adguard.com",ipv4:"94.140.15.15"},description:"Remove ads and protect your computer from malware (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-family-doh",endpoint:{protocol:"https:",host:"dns-family.adguard.com",ipv4:"94.140.15.16"},description:"Adguard DNS with safesearch and adult content blocking (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-unfiltered-doh",endpoint:{protocol:"https:",host:"dns-unfiltered.adguard.com",ipv4:"94.140.14.140"},description:"AdGuard public DNS servers without filters (over DoH)",country:"France",location:{lat:48.8582,long:2.3387}},{name:"ahadns-doh-chi",endpoint:{protocol:"https:",host:"doh.chi.ahadns.net",cors:!0},description:`A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Chicago, USA. By https://ahadns.com/ +Server statistics can be seen at: https://statistics.ahadns.com/?server=chi`,country:"United States",location:{lat:41.8483,long:-87.6517},filter:!0,cors:!0},{name:"ahadns-doh-in",endpoint:{protocol:"https:",host:"doh.in.ahadns.net",cors:!0},description:`A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Mumbai, India. By https://ahadns.com/ +Server statistics can be seen at: https://statistics.ahadns.com/?server=in`,country:"India",location:{lat:19.0748,long:72.8856},filter:!0,cors:!0},{name:"ahadns-doh-la",endpoint:{protocol:"https:",host:"doh.la.ahadns.net",cors:!0},description:`A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Los Angeles, USA. By https://ahadns.com/ +Server statistics can be seen at: https://statistics.ahadns.com/?server=la`,country:"United States",location:{lat:34.0549,long:-118.2578},filter:!0,cors:!0},{name:"ahadns-doh-nl",endpoint:{protocol:"https:",host:"doh.nl.ahadns.net",cors:!0},description:`A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Amsterdam, Netherlands. By https://ahadns.com/ +Server statistics can be seen at: https://statistics.ahadns.com/?server=nl`,country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"ahadns-doh-ny",endpoint:{protocol:"https:",host:"doh.ny.ahadns.net",cors:!0},description:`A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in New York. By https://ahadns.com/ +Server statistics can be seen at: https://statistics.ahadns.com/?server=ny`,country:"United States",location:{lat:40.7308,long:-73.9975},filter:!0,cors:!0},{name:"ahadns-doh-pl",endpoint:{protocol:"https:",host:"doh.pl.ahadns.net",cors:!0},description:`A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Poland. By https://ahadns.com/ +Server statistics can be seen at: https://statistics.ahadns.com/?server=pl`,country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"alidns-doh",endpoint:{protocol:"https:",host:"dns.alidns.com",ipv4:"223.5.5.5",cors:!0},description:`A public DNS resolver that supports DoH/DoT in mainland China, provided by Alibaba-Cloud. +Warning: GFW filtering rules are applied by that resolver. +Homepage: https://alidns.com/`,country:"China",location:{lat:34.7725,long:113.7266},filter:!0,log:!0,cors:!0},{name:"ams-ads-doh-nl",endpoint:{protocol:"https:",host:"dnsnl-noads.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging. Blocks ads, malware and trackers. DNSSEC enabled.",country:"Romania",location:{lat:45.9968,long:24.997},filter:!0},{name:"ams-doh-nl",endpoint:{protocol:"https:",host:"dnsnl.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Romania",location:{lat:45.9968,long:24.997}},{name:"att",endpoint:{protocol:"https:",host:"dohtrial.att.net"},description:"AT&T test DoH server.",log:!0},{name:"bcn-ads-doh",endpoint:{protocol:"https:",host:"dnses-noads.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, remove ads and malware, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611},filter:!0},{name:"bcn-doh",endpoint:{protocol:"https:",host:"dnses.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611}},{name:"brahma-world",endpoint:{protocol:"https:",host:"dns.brahma.world"},description:`DNS-over-HTTPS server. Non Logging, filters ads, trackers and malware. DNSSEC ready, QNAME Minimization, No EDNS Client-Subnet. +Hosted in Stockholm, Sweden. (https://dns.brahma.world)`,country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"cisco-doh",endpoint:{protocol:"https:",host:"doh.opendns.com",ipv4:"146.112.41.2"},description:`Remove your DNS blind spot (DoH protocol) +Warning: modifies your queries to include a copy of your network +address when forwarding them to a selection of companies and organizations.`,country:"United States",location:{lat:37.751,long:-97.822},filter:!0,log:!0},{name:"cloudflare",endpoint:{protocol:"https:",host:"dns.cloudflare.com",ipv4:"1.0.0.1",cors:!0},description:"Cloudflare DNS (anycast) - aka 1.1.1.1 / 1.0.0.1",country:"Australia",location:{lat:-33.494,long:143.2104},cors:!0},{name:"cloudflare-family",endpoint:{protocol:"https:",host:"family.cloudflare-dns.com",ipv4:"1.0.0.3",cors:!0},description:"Cloudflare DNS (anycast) with malware protection and parental control - aka 1.1.1.3 / 1.0.0.3",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"cloudflare-ipv6",endpoint:{protocol:"https:",host:"1dot1dot1dot1.cloudflare-dns.com",cors:!0},description:"Cloudflare DNS over IPv6 (anycast)",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"cloudflare-security",endpoint:{protocol:"https:",host:"security.cloudflare-dns.com",ipv4:"1.0.0.2",cors:!0},description:"Cloudflare DNS (anycast) with malware blocking - aka 1.1.1.2 / 1.0.0.2",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"controld-block-malware",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p1"},description:`ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns +This DNS blocks Malware domains.`,country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p2"},description:`ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns +This DNS blocks Malware, Ads & Tracking domains.`,country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad-social",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p3"},description:`ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns +This DNS blocks Malware, Ads & Tracking and Social Networks domains.`,country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-family-friendly",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/family"},description:`ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns +This DNS blocks Malware, Ads & Tracking, Adult Content and Drugs domains.`,country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-uncensored",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/uncensored"},description:`ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns +This DNS unblocks censored domains from various countries.`,country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"controld-unfiltered",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p0"},description:`ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns +This is a Unfiltered DNS, no DNS record blocking or manipulation here, if you want to block Malware, Ads & Tracking or Social Network domains, use the other ControlD DNS configs.`,country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"dns.digitale-gesellschaft.ch",endpoint:{protocol:"https:",host:"dns.digitale-gesellschaft.ch"},description:`Public DoH resolver operated by the Digital Society (https://www.digitale-gesellschaft.ch). +Hosted in Zurich, Switzerland. +Non-logging, non-filtering, supports DNSSEC.`,country:"Switzerland",location:{lat:47.1449,long:8.1551}},{name:"dns.ryan-palmer",endpoint:{protocol:"https:",host:"dns1.ryan-palmer.com"},description:"Non-logging, non-filtering, DNSSEC DoH Server. Hosted in the UK.",country:"United Kingdom",location:{lat:51.5164,long:-.093}},{name:"dns.sb",endpoint:{protocol:"https:",host:"doh.sb",ipv4:"185.222.222.222",cors:!0},description:`DNSSEC-enabled DoH server by https://xtom.com/ +https://dns.sb/doh/`,country:"Unknown",location:{lat:47,long:8},cors:!0},{name:"dns.therifleman.name",endpoint:{protocol:"https:",host:"dns.therifleman.name"},description:`DNS-over-HTTPS DNS forwarder from Mumbai, India. Blocks web and Android trackers and ads. +IP addresses are not logged, but queries are logged for 24 hours for debugging. +Report issues, send suggestions @ joker349 at protonmail.com. +Also supports DoT (for android) @ dns.therifleman.name and plain DNS @ 172.104.206.174`,country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"dnsforfamily-doh",endpoint:{protocol:"https:",host:"dns-doh.dnsforfamily.com"},description:`(DoH Protocol) (Now supports DNSSEC). Block adult websites, gambling websites, malwares and advertisements. +It also enforces safe search in: Google, YouTube, Bing, DuckDuckGo and Yandex. +Social websites like Facebook and Instagram are not blocked. No DNS queries are logged. +As of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily. +Completely free, no ads or any commercial motive. Operating for 4 years now. +Provided by: https://dnsforfamily.com`,country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforfamily-doh-no-safe-search",endpoint:{protocol:"https:",host:"dns-doh-no-safe-search.dnsforfamily.com"},description:`(DoH Protocol) (Now supports DNSSEC) Block adult websites, gambling websites, malwares and advertisements. +Unlike other dnsforfamily servers, this one does not enforces safe search. So Google, YouTube, Bing, DuckDuckGo and Yandex are completely accessible without any restriction. +Social websites like Facebook and Instagram are not blocked. No DNS queries are logged. +As of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily. +Completely free, no ads or any commercial motive. Operating for 4 years now. +Warning: This server is incompatible with anonymization. +Provided by: https://dnsforfamily.com`,country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforge.de",endpoint:{protocol:"https:",host:"dnsforge.de",cors:!0},description:`Public DoH resolver running with Pihole for Adblocking (https://dnsforge.de). +Non-logging, AD-filtering, supports DNSSEC. Hosted in Germany.`,country:"Germany",location:{lat:52.2998,long:9.447},filter:!0,cors:!0},{name:"dnshome-doh",endpoint:{protocol:"https:",host:"dns.dnshome.de"},description:"https://www.dnshome.de/ public resolver in Germany"},{name:"dnspod-doh",endpoint:{protocol:"https:",host:"doh.pub",cors:!0},description:`A public DNS resolver in mainland China provided by DNSPod (Tencent Cloud). +https://www.dnspod.cn/Products/Public.DNS?lang=en`,filter:!0,log:!0,cors:!0},{name:"dnswarden-asia-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adblock"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-adultfilter-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adultfilter"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-uncensor-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/uncensored"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547}},{name:"dnswarden-eu-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.eu.dnswarden.com"},description:"Hosted in Germany. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Germany",location:{lat:50.1103,long:8.7147},filter:!0},{name:"dnswarden-us-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.us.dnswarden.com"},description:"Hosted in USA (Dallas) . For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"United States",location:{lat:32.7889,long:-96.8021},filter:!0},{name:"doh-ch-blahdns",endpoint:{protocol:"https:",host:"doh-ch.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Switzerland. By https://blahdns.com/",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"doh-cleanbrowsing-adult",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/adult-filter/",cors:!0},description:`Blocks access to all adult, pornographic and explicit sites. It does +not block proxy or VPNs, nor mixed-content sites. Sites like Reddit +are allowed. Google and Bing are set to the Safe Mode. +By https://cleanbrowsing.org/`,filter:!0,cors:!0},{name:"doh-cleanbrowsing-family",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/family-filter/",cors:!0},description:`Blocks access to all adult, pornographic and explicit sites. It also +blocks proxy and VPN domains that are used to bypass the filters. +Mixed content sites (like Reddit) are also blocked. Google, Bing and +Youtube are set to the Safe Mode. +By https://cleanbrowsing.org/`,filter:!0,cors:!0},{name:"doh-cleanbrowsing-security",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/security-filter/",cors:!0},description:`Block access to phishing, malware and malicious domains. It does not block adult content. +By https://cleanbrowsing.org/`,filter:!0,cors:!0},{name:"doh-crypto-sx",endpoint:{protocol:"https:",host:"doh.crypto.sx",cors:!0},description:`DNS-over-HTTPS server. Anycast, no logs, no censorship, DNSSEC. +Backend hosted by Scaleway, globally cached via Cloudflare. +Maintained by Frank Denis.`,country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-crypto-sx-ipv6",endpoint:{protocol:"https:",host:"doh-ipv6.crypto.sx",cors:!0},description:`DNS-over-HTTPS server accessible over IPv6. Anycast, no logs, no censorship, DNSSEC. +Backend hosted by Scaleway, globally cached via Cloudflare. +Maintained by Frank Denis.`,country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-de-blahdns",endpoint:{protocol:"https:",host:"doh-de.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Germany. By https://blahdns.com/",country:"Germany",location:{lat:51.2993,long:9.491},filter:!0,cors:!0},{name:"doh-fi-blahdns",endpoint:{protocol:"https:",host:"doh-fi.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Finland. By https://blahdns.com/",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0,cors:!0},{name:"doh-ibksturm",endpoint:{protocol:"https:",host:"ibksturm.synology.me"},description:`DoH & DoT Server, No Logging, No Filters, DNSSEC +Running privately by ibksturm in Thurgau, Switzerland`},{name:"doh-jp-blahdns",endpoint:{protocol:"https:",host:"doh-jp.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Japan. By https://blahdns.com/",country:"Japan",location:{lat:35.6882,long:139.7532},filter:!0,cors:!0},{name:"doh.ffmuc.net",endpoint:{protocol:"https:",host:"doh.ffmuc.net"},description:`An open (non-logging, non-filtering, non-censoring) DoH resolver operated by Freifunk Munich with nodes in DE. +https://ffmuc.net/`,country:"Germany",location:{lat:51.2993,long:9.491}},{name:"doh.tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org"},description:`Non-Logging DNS-over-HTTPS server, cached via Cloudflare. +Filters out ads, trackers and malware, NO ECS, supports DNSSEC.`,country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"google",endpoint:{protocol:"https:",host:"dns.google",ipv4:"8.8.8.8",cors:!0},description:"Google DNS (anycast)",country:"United States",location:{lat:37.751,long:-97.822},log:!0,cors:!0},{name:"hdns",endpoint:{protocol:"https:",host:"query.hdns.io",cors:!0},description:`HDNS is a public DNS resolver that supports Handshake domains. +https://www.hdns.io`,country:"United States",location:{lat:37.7771,long:-122.406},cors:!0},{name:"he",endpoint:{protocol:"https:",host:"ordns.he.net"},description:`Hurricane Electric DoH server (anycast) +Unknown logging policy.`,country:"United States",location:{lat:37.751,long:-97.822},log:!0},{name:"id-gmail-doh",endpoint:{protocol:"https:",host:"doh.tiar.app"},description:`Non-Logging DNS-over-HTTPS server located in Singapore. +Filters out ads, trackers and malware, supports DNSSEC, provided by id-gmail.`,country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"iij",endpoint:{protocol:"https:",host:"public.dns.iij.jp"},description:`DoH server operated by Internet Initiative Japan in Tokyo. +https://www.iij.ad.jp/`,country:"Japan",location:{lat:35.69,long:139.69},log:!0},{name:"iqdns-doh",endpoint:{protocol:"https:",host:"a.passcloud.xyz"},description:`Non-logging DoH service runned by V2EX.com user johnsonwil. +Returns "no such domain" for anti-Chinese government websites. Supports DNSSEC. +For more information: https://www.v2ex.com/t/785666`,filter:!0},{name:"jp.tiar.app-doh",endpoint:{protocol:"https:",host:"jp.tiar.app"},description:`Non-Logging, Non-Filtering DNS-over-HTTPS server in Japan. +No ECS, Support DNSSEC`,country:"Japan",location:{lat:35.6882,long:139.7532}},{name:"jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org"},description:`DNS-over-HTTPS Server. Non-Logging, Non-Filtering, No ECS, Support DNSSEC. +Cached via Cloudflare.`},{name:"libredns",endpoint:{protocol:"https:",host:"doh.libredns.gr"},description:`DoH server in Germany. No logging, but no DNS padding and no DNSSEC support. +https://libredns.gr/`,country:"Germany",location:{lat:51.2993,long:9.491}},{name:"nextdns",endpoint:{protocol:"https:",host:"anycsast.dns.nextdns.io"},description:`NextDNS is a cloud-based private DNS service that gives you full control +over what is allowed and what is blocked on the Internet. +DNSSEC, Anycast, Non-logging, NoFilters +https://www.nextdns.io/`,country:"Netherlands",location:{lat:52.3891,long:4.6563}},{name:"nextdns-ultralow",endpoint:{protocol:"https:",host:"dns.nextdns.io",path:"/dnscrypt-proxy"},description:`NextDNS is a cloud-based private DNS service that gives you full control +over what is allowed and what is blocked on the Internet. +https://www.nextdns.io/ +To select the server location, the "-ultralow" variant relies on bootstrap servers +instead of anycast.`},{name:"njalla-doh",endpoint:{protocol:"https:",host:"dns.njal.la",cors:!0},description:`Non-logging DoH server in Sweden operated by Njalla. +https://dns.njal.la/`,country:"Sweden",location:{lat:59.3247,long:18.056},cors:!0},{name:"odoh-cloudflare",endpoint:{protocol:"https:",host:"odoh.cloudflare-dns.com",cors:!0},description:`Cloudflare ODoH server. +https://cloudflare.com`,cors:!0},{name:"odoh-crypto-sx",endpoint:{protocol:"https:",host:"odoh.crypto.sx",cors:!0},description:`ODoH target server. Anycast, no logs. +Backend hosted by Scaleway. Maintained by Frank Denis.`,cors:!0},{name:"odoh-id-gmail",endpoint:{protocol:"https:",host:"doh.tiar.app",path:"/odoh"},description:`ODoH target server. Based in Singapore, no logs. +Filter ads, trackers and malware.`,filter:!0},{name:"odoh-jp.tiar.app",endpoint:{protocol:"https:",host:"jp.tiar.app",path:"/odoh"},description:"ODoH target server. no logs."},{name:"odoh-jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org",path:"/odoh"},description:"ODoH target server via Cloudflare, no logs."},{name:"odoh-resolver4.dns.openinternet.io",endpoint:{protocol:"https:",host:"resolver4.dns.openinternet.io"},description:`ODoH target server. no logs, no filter, DNSSEC. +Running on dedicated hardware colocated at Sonic.net in Santa Rosa, CA in the United States. +Uses Sonic's recusrive DNS servers as upstream resolvers (but is not affiliated with Sonic +in any way). Provided by https://openinternet.io`},{name:"odoh-tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org",path:"/odoh"},description:`ODoH target server via Cloudflare, no logs. +Filter ads, trackers and malware.`,filter:!0},{name:"publicarray-au2-doh",endpoint:{protocol:"https:",host:"doh-2.seby.io",cors:!0},description:`DNSSEC • OpenNIC • Non-logging • Uncensored - hosted on ovh.com.au +Maintained by publicarray - https://dns.seby.io`,country:"Australia",location:{lat:-33.8591,long:151.2002},cors:!0},{name:"puredns-doh",endpoint:{protocol:"https:",host:"puredns.org",ipv4:"146.190.6.13",cors:!0},description:`Public uncensored DNS resolver in Singapore - https://puredns.org +** Only available in Indonesia and Singapore **`,country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"quad101",endpoint:{protocol:"https:",host:"dns.twnic.tw",cors:!0},description:`DNSSEC-aware public resolver by the Taiwan Network Information Center (TWNIC) +https://101.101.101.101/index_en.html`,cors:!0},{name:"quad9-doh-ip4-port443-filter-ecs-pri",endpoint:{protocol:"https:",host:"dns11.quad9.net",ipv4:"149.112.112.11"},description:"Quad9 (anycast) dnssec/no-log/filter/ecs 9.9.9.11 - 149.112.112.11",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-filter-pri",endpoint:{protocol:"https:",host:"dns.quad9.net",ipv4:"149.112.112.112"},description:"Quad9 (anycast) dnssec/no-log/filter 9.9.9.9 - 149.112.112.9 - 149.112.112.112",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-nofilter-ecs-pri",endpoint:{protocol:"https:",host:"dns12.quad9.net",ipv4:"9.9.9.12"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter/ecs 9.9.9.12 - 149.112.112.12",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip4-port443-nofilter-pri",endpoint:{protocol:"https:",host:"dns10.quad9.net",ipv4:"149.112.112.10"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter 9.9.9.10 - 149.112.112.10",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip6-port5053-filter-pri",endpoint:{protocol:"https:",host:"dns9.quad9.net"},description:"Quad9 (anycast) dnssec/no-log/filter 2620:fe::fe - 2620:fe::9 - 2620:fe::fe:9",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"safesurfer-doh",endpoint:{protocol:"https:",host:"doh.safesurfer.io"},description:`Family safety focused blocklist for over 2 million adult sites, as well as phishing and malware and more. +Free to use, paid for customizing blocking for more categories+sites and viewing usage at my.safesurfer.io. Logs taken for viewing +usage, data never sold - https://safesurfer.io`,filter:!0,log:!0},{name:"sth-ads-doh-se",endpoint:{protocol:"https:",host:"dnsse-noads.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, remove ads and malware, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332},filter:!0},{name:"sth-doh-se",endpoint:{protocol:"https:",host:"dnsse.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, non-filtering, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332}},{name:"switch",endpoint:{protocol:"https:",host:"dns.switch.ch"},description:`Public DoH service provided by SWITCH in Switzerland +https://www.switch.ch +Provides protection against malware, but does not block ads.`,filter:!0},{name:"uncensoreddns-dk-ipv4",endpoint:{protocol:"https:",host:"unicast.uncensoreddns.org"},description:`Also known as censurfridns. +DoH, no logs, no filter, DNSSEC, unicast hosted in Denmark - https://blog.uncensoreddns.org`,country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"uncensoreddns-ipv4",endpoint:{protocol:"https:",host:"anycast.uncensoreddns.org"},description:`Also known as censurfridns. +DoH, no logs, no filter, DNSSEC, anycast - https://blog.uncensoreddns.org`,country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"v.dnscrypt.uk-doh-ipv4",endpoint:{protocol:"https:",host:"v.dnscrypt.uk"},description:`DoH, no logs, uncensored, DNSSEC. Hosted in London UK on Digital Ocean +https://www.dnscrypt.uk`,country:"United Kingdom",location:{lat:51.4964,long:-.1224}}],time:1654187067783};function processResolvers(et){const o=et.time===null||et.time===void 0?Date.now():et.time,tt=processResolvers$1(et.data.map(nt=>(nt.endpoint=toEndpoint(Object.assign({name:nt.name},nt.endpoint)),nt))),rt=tt.map(nt=>nt.endpoint);return{data:{resolvers:tt,resolverByName:tt.reduce((nt,ot)=>(nt[ot.name]=ot,nt),{}),endpoints:rt,endpointByName:rt.reduce((nt,ot)=>(nt[ot.name]=ot,nt),{})},time:o}}const backup=processResolvers(resolvers);function toMultiQuery(et){const o=Object.assign({type:"query"},et);return delete o.question,o.questions=[],et.question&&o.questions.push(et.question),o}function queryOne(et,o,tt,rt){return rt&&rt.aborted?Promise.reject(new AbortError):et.protocol==="udp4:"||et.protocol==="udp6:"?queryDns():queryDoh(et,o,tt,rt)}function queryDoh(et,o,tt,rt){return request(et.url,et.method,encode$2(Object.assign({flags:RECURSION_DESIRED},o)),tt,rt).then(function(nt){const ot=nt.data,it=nt.response;let st=nt.error;if(st===void 0)if(ot.length===0)st=new ResponseError("Empty.");else try{const at=decode$3(ot);return at.response=it,at}catch(at){st=new ResponseError("Invalid packet (cause="+at.message+")",at)}throw Object.assign(st,{response:it})})}const UPDATE_URL=new URL$1("https://martinheidegger.github.io/dns-query/resolvers.json");function isNameString(et){return/^@/.test(et)}class Wellknown{constructor(o){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:UPDATE_URL,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},o),this._dataP=null}_data(o,tt){return!o&&this._dataP!==null?this._dataP.then(rt=>rt.timeprocessResolvers({data:rt.data.resolvers,time:rt.time})).catch(()=>tt||backup):Promise.resolve(backup),this._dataP)}data(){return this._data(!1).then(o=>o.data)}endpoints(o){if(o==null)return this.data().then(tt=>tt.endpoints);if(o==="doh"&&(o=filterDoh),o==="dns"&&(o=filterDns),typeof o=="function")return this.data().then(tt=>tt.endpoints.filter(o));if(typeof o=="string"||typeof o[Symbol.iterator]!="function")return Promise.reject(new Error(`Endpoints (${o}) needs to be iterable (array).`));if(o=Array.from(o).filter(Boolean),o.findIndex(isNameString)===-1)try{return Promise.resolve(o.map(toEndpoint))}catch(tt){return Promise.reject(tt)}return this.data().then(tt=>o.map(rt=>{if(isNameString(rt)){const nt=tt.endpointByName[rt.substring(1)];if(!nt)throw new Error(`Endpoint ${rt} is not known.`);return nt}return toEndpoint(rt)}))}}const wellknown=new Wellknown;function isPromise(et){return et===null||typeof et!="object"?!1:typeof et.then=="function"}function toPromise(et){return isPromise(et)?et:Promise.resolve(et)}function query(et,o){return o=Object.assign({retries:5,timeout:3e4},o),et.question?toPromise(o.endpoints).then(tt=>{if(!Array.isArray(tt)||tt.length===0)throw new Error("No endpoints defined to lookup dns records.");return queryN(tt.map(toEndpoint),toMultiQuery(et),o)}).then(tt=>(tt.question=tt.questions[0],delete tt.questions,tt)):Promise.reject(new Error("To request data you need to specify a .question!"))}function queryN(et,o,tt){const rt=et.length===1?et[0]:et[Math.floor(Math.random()*et.length)%et.length];return queryOne(rt,o,tt.timeout,tt.signal).then(nt=>(nt.endpoint=rt.toString(),nt),nt=>{if(nt.name==="AbortError"||tt.retries===0)throw nt.endpoint=rt.toString(),nt;return tt.retries>0&&(tt.retries-=1),queryN(et,o,tt)})}function filterDoh(et){return et.protocol==="https:"||et.protocol==="http:"}function filterDns(et){return et.protocol==="udp4:"||et.protocol==="udp6:"}const log$7=new Logger$1("dns-over-https");class DnsOverHttps{constructor(o,tt=3){wt(this,"endpoints");wt(this,"retries");this.endpoints=o,this.retries=tt}static async create(o,tt){const rt=o??await wellknown.endpoints("doh");return new DnsOverHttps(rt,tt)}async resolveTXT(o){let tt;try{tt=(await query({question:{type:"TXT",name:o}},{endpoints:this.endpoints,retries:this.retries})).answers}catch(ot){throw log$7.error("query failed: ",ot),new Error("DNS query failed")}if(!tt)throw new Error(`Could not resolve ${o}`);const rt=tt.map(ot=>ot.data),nt=[];return rt.forEach(ot=>{typeof ot=="string"?nt.push(ot):Array.isArray(ot)?ot.forEach(it=>{typeof it=="string"?nt.push(it):nt.push(bytesToUtf8(it))}):nt.push(bytesToUtf8(ot))}),nt}}var base32$3={exports:{}};/* + * [hi-base32]{@link https://github.com/emn178/hi-base32} + * + * @version 0.5.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + */(function(et){(function(){var o=typeof window=="object"?window:{},tt=!o.HI_BASE32_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;tt&&(o=commonjsGlobal);var rt=!o.HI_BASE32_NO_COMMON_JS&&!0&&et.exports,nt="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),ot={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},it=[0,0,0,0,0,0,0,0],st=function(gt,yt){yt.length>10&&(yt="..."+yt.substr(-10));var bt=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+gt+" bytes: "+yt+" <-");throw bt.position=gt,bt},at=function(gt){for(var yt="",bt=gt.length,xt=0,vt=0,Et,Ct;xt191&&Et<=223?(Ct=Et&31,vt=1):Et<=239?(Ct=Et&15,vt=2):Et<=247?(Ct=Et&7,vt=3):st(xt,yt);for(var St=0;St191)&&st(xt,yt),Ct<<=6,Ct+=Et&63;Ct>=55296&&Ct<=57343&&st(xt,yt),Ct>1114111&&st(xt,yt),Ct<=65535?yt+=String.fromCharCode(Ct):(Ct-=65536,yt+=String.fromCharCode((Ct>>10)+55296),yt+=String.fromCharCode((Ct&1023)+56320))}return yt},ct=function(gt){if(gt==="")return[];if(!/^[A-Z2-7=]+$/.test(gt))throw new Error("Invalid base32 characters");gt=gt.replace(/=/g,"");for(var yt,bt,xt,vt,Et,Ct,St,At,kt=[],It=0,Ot=gt.length,Nt=0,Yt=Ot>>3<<3;Nt>>2)&255,kt[It++]=(bt<<6|xt<<1|vt>>>4)&255,kt[It++]=(vt<<4|Et>>>1)&255,kt[It++]=(Et<<7|Ct<<2|St>>>3)&255,kt[It++]=(St<<5|At)&255;var Ft=Ot-Yt;return Ft===2?(yt=ot[gt.charAt(Nt++)],bt=ot[gt.charAt(Nt++)],kt[It++]=(yt<<3|bt>>>2)&255):Ft===4?(yt=ot[gt.charAt(Nt++)],bt=ot[gt.charAt(Nt++)],xt=ot[gt.charAt(Nt++)],vt=ot[gt.charAt(Nt++)],kt[It++]=(yt<<3|bt>>>2)&255,kt[It++]=(bt<<6|xt<<1|vt>>>4)&255):Ft===5?(yt=ot[gt.charAt(Nt++)],bt=ot[gt.charAt(Nt++)],xt=ot[gt.charAt(Nt++)],vt=ot[gt.charAt(Nt++)],Et=ot[gt.charAt(Nt++)],kt[It++]=(yt<<3|bt>>>2)&255,kt[It++]=(bt<<6|xt<<1|vt>>>4)&255,kt[It++]=(vt<<4|Et>>>1)&255):Ft===7&&(yt=ot[gt.charAt(Nt++)],bt=ot[gt.charAt(Nt++)],xt=ot[gt.charAt(Nt++)],vt=ot[gt.charAt(Nt++)],Et=ot[gt.charAt(Nt++)],Ct=ot[gt.charAt(Nt++)],St=ot[gt.charAt(Nt++)],kt[It++]=(yt<<3|bt>>>2)&255,kt[It++]=(bt<<6|xt<<1|vt>>>4)&255,kt[It++]=(vt<<4|Et>>>1)&255,kt[It++]=(Et<<7|Ct<<2|St>>>3)&255),kt},lt=function(gt){for(var yt,bt,xt,vt,Et,Ct="",St=gt.length,At=0,kt=parseInt(St/5)*5;At>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[(bt<<4|xt>>>4)&31]+nt[(xt<<1|vt>>>7)&31]+nt[vt>>>2&31]+nt[(vt<<3|Et>>>5)&31]+nt[Et&31];var It=St-kt;return It===1?(yt=gt.charCodeAt(At),Ct+=nt[yt>>>3]+nt[yt<<2&31]+"======"):It===2?(yt=gt.charCodeAt(At++),bt=gt.charCodeAt(At),Ct+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[bt<<4&31]+"===="):It===3?(yt=gt.charCodeAt(At++),bt=gt.charCodeAt(At++),xt=gt.charCodeAt(At),Ct+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[(bt<<4|xt>>>4)&31]+nt[xt<<1&31]+"==="):It===4&&(yt=gt.charCodeAt(At++),bt=gt.charCodeAt(At++),xt=gt.charCodeAt(At++),vt=gt.charCodeAt(At),Ct+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[(bt<<4|xt>>>4)&31]+nt[(xt<<1|vt>>>7)&31]+nt[vt>>>2&31]+nt[vt<<3&31]+"="),Ct},dt=function(gt){var yt,bt,xt,vt,Et,Ct,St=!1,At="",kt=0,It,Ot=0,Nt=gt.length;if(gt==="")return At;do{for(it[0]=it[5],it[1]=it[6],it[2]=it[7],It=Ot;kt>6,it[It++]=128|Ct&63):Ct<55296||Ct>=57344?(it[It++]=224|Ct>>12,it[It++]=128|Ct>>6&63,it[It++]=128|Ct&63):(Ct=65536+((Ct&1023)<<10|gt.charCodeAt(++kt)&1023),it[It++]=240|Ct>>18,it[It++]=128|Ct>>12&63,it[It++]=128|Ct>>6&63,it[It++]=128|Ct&63);Ot=It-5,kt===Nt&&++kt,kt>Nt&&It<6&&(St=!0),yt=it[0],It>4?(bt=it[1],xt=it[2],vt=it[3],Et=it[4],At+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[(bt<<4|xt>>>4)&31]+nt[(xt<<1|vt>>>7)&31]+nt[vt>>>2&31]+nt[(vt<<3|Et>>>5)&31]+nt[Et&31]):It===1?At+=nt[yt>>>3]+nt[yt<<2&31]+"======":It===2?(bt=it[1],At+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[bt<<4&31]+"===="):It===3?(bt=it[1],xt=it[2],At+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[(bt<<4|xt>>>4)&31]+nt[xt<<1&31]+"==="):(bt=it[1],xt=it[2],vt=it[3],At+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[(bt<<4|xt>>>4)&31]+nt[(xt<<1|vt>>>7)&31]+nt[vt>>>2&31]+nt[vt<<3&31]+"=")}while(!St);return At},ht=function(gt){for(var yt,bt,xt,vt,Et,Ct="",St=gt.length,At=0,kt=parseInt(St/5)*5;At>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[(bt<<4|xt>>>4)&31]+nt[(xt<<1|vt>>>7)&31]+nt[vt>>>2&31]+nt[(vt<<3|Et>>>5)&31]+nt[Et&31];var It=St-kt;return It===1?(yt=gt[At],Ct+=nt[yt>>>3]+nt[yt<<2&31]+"======"):It===2?(yt=gt[At++],bt=gt[At],Ct+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[bt<<4&31]+"===="):It===3?(yt=gt[At++],bt=gt[At++],xt=gt[At],Ct+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[(bt<<4|xt>>>4)&31]+nt[xt<<1&31]+"==="):It===4&&(yt=gt[At++],bt=gt[At++],xt=gt[At++],vt=gt[At],Ct+=nt[yt>>>3]+nt[(yt<<2|bt>>>6)&31]+nt[bt>>>1&31]+nt[(bt<<4|xt>>>4)&31]+nt[(xt<<1|vt>>>7)&31]+nt[vt>>>2&31]+nt[vt<<3&31]+"="),Ct},mt=function(gt,yt){var bt=typeof gt!="string";return bt&>.constructor===ArrayBuffer&&(gt=new Uint8Array(gt)),bt?ht(gt):yt?lt(gt):dt(gt)},ft=function(gt,yt){if(!yt)return at(ct(gt));if(gt==="")return"";if(!/^[A-Z2-7=]+$/.test(gt))throw new Error("Invalid base32 characters");var bt,xt,vt,Et,Ct,St,At,kt,It="",Ot=gt.indexOf("=");Ot===-1&&(Ot=gt.length);for(var Nt=0,Yt=Ot>>3<<3;Nt>>2)&255)+String.fromCharCode((xt<<6|vt<<1|Et>>>4)&255)+String.fromCharCode((Et<<4|Ct>>>1)&255)+String.fromCharCode((Ct<<7|St<<2|At>>>3)&255)+String.fromCharCode((At<<5|kt)&255);var Ft=Ot-Yt;return Ft===2?(bt=ot[gt.charAt(Nt++)],xt=ot[gt.charAt(Nt++)],It+=String.fromCharCode((bt<<3|xt>>>2)&255)):Ft===4?(bt=ot[gt.charAt(Nt++)],xt=ot[gt.charAt(Nt++)],vt=ot[gt.charAt(Nt++)],Et=ot[gt.charAt(Nt++)],It+=String.fromCharCode((bt<<3|xt>>>2)&255)+String.fromCharCode((xt<<6|vt<<1|Et>>>4)&255)):Ft===5?(bt=ot[gt.charAt(Nt++)],xt=ot[gt.charAt(Nt++)],vt=ot[gt.charAt(Nt++)],Et=ot[gt.charAt(Nt++)],Ct=ot[gt.charAt(Nt++)],It+=String.fromCharCode((bt<<3|xt>>>2)&255)+String.fromCharCode((xt<<6|vt<<1|Et>>>4)&255)+String.fromCharCode((Et<<4|Ct>>>1)&255)):Ft===7&&(bt=ot[gt.charAt(Nt++)],xt=ot[gt.charAt(Nt++)],vt=ot[gt.charAt(Nt++)],Et=ot[gt.charAt(Nt++)],Ct=ot[gt.charAt(Nt++)],St=ot[gt.charAt(Nt++)],At=ot[gt.charAt(Nt++)],It+=String.fromCharCode((bt<<3|xt>>>2)&255)+String.fromCharCode((xt<<6|vt<<1|Et>>>4)&255)+String.fromCharCode((Et<<4|Ct>>>1)&255)+String.fromCharCode((Ct<<7|St<<2|At>>>3)&255)),It},pt={encode:mt,decode:ft};ft.asBytes=ct,rt?et.exports=pt:o.base32=pt})()})(base32$3);var base32Exports=base32$3.exports;const base32$2=getDefaultExportFromCjs(base32Exports);function coerce$1(et){if(et instanceof Uint8Array&&et.constructor.name==="Uint8Array")return et;if(et instanceof ArrayBuffer)return new Uint8Array(et);if(ArrayBuffer.isView(et))return new Uint8Array(et.buffer,et.byteOffset,et.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$1(et){return new TextEncoder().encode(et)}function toString$2(et){return new TextDecoder().decode(et)}function base(et,o){if(et.length>=255)throw new TypeError("Alphabet too long");for(var tt=new Uint8Array(256),rt=0;rt>>0,vt=new Uint8Array(xt);yt!==bt;){for(var Et=ft[yt],Ct=0,St=xt-1;(Et!==0||Ct>>0,vt[St]=Et%st>>>0,Et=Et/st>>>0;if(Et!==0)throw new Error("Non-zero carry");gt=Ct,yt++}for(var At=xt-gt;At!==xt&&vt[At]===0;)At++;for(var kt=at.repeat(pt);At>>0,xt=new Uint8Array(bt);ft[pt];){var vt=tt[ft.charCodeAt(pt)];if(vt===255)return;for(var Et=0,Ct=bt-1;(vt!==0||Et>>0,xt[Ct]=vt%256>>>0,vt=vt/256>>>0;if(vt!==0)throw new Error("Non-zero carry");yt=Et,pt++}if(ft[pt]!==" "){for(var St=bt-yt;St!==bt&&xt[St]===0;)St++;for(var At=new Uint8Array(gt+(bt-St)),kt=gt;St!==bt;)At[kt++]=xt[St++];return At}}}function mt(ft){var pt=ht(ft);if(pt)return pt;throw new Error(`Non-${o} character`)}return{encode:dt,decodeUnsafe:ht,decode:mt}}var src$1=base,_brrp__multiformats_scope_baseX=src$1;class Encoder{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");this.name=o,this.prefix=tt,this.baseEncode=rt}encode(o){if(o instanceof Uint8Array)return`${this.prefix}${this.baseEncode(o)}`;throw Error("Unknown type, must be binary type")}}class Decoder{constructor(o,tt,rt){wt(this,"name");wt(this,"prefix");wt(this,"baseDecode");wt(this,"prefixCodePoint");this.name=o,this.prefix=tt;const nt=tt.codePointAt(0);if(nt===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=nt,this.baseDecode=rt}decode(o){if(typeof o=="string"){if(o.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(o)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(o.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(o){return or(this,o)}}class ComposedDecoder{constructor(o){wt(this,"decoders");this.decoders=o}or(o){return or(this,o)}decode(o){const tt=o[0],rt=this.decoders[tt];if(rt!=null)return rt.decode(o);throw RangeError(`Unable to decode multibase string ${JSON.stringify(o)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function or(et,o){return new ComposedDecoder({...et.decoders??{[et.prefix]:et},...o.decoders??{[o.prefix]:o}})}class Codec{constructor(o,tt,rt,nt){wt(this,"name");wt(this,"prefix");wt(this,"baseEncode");wt(this,"baseDecode");wt(this,"encoder");wt(this,"decoder");this.name=o,this.prefix=tt,this.baseEncode=rt,this.baseDecode=nt,this.encoder=new Encoder(o,tt,rt),this.decoder=new Decoder(o,tt,nt)}encode(o){return this.encoder.encode(o)}decode(o){return this.decoder.decode(o)}}function from({name:et,prefix:o,encode:tt,decode:rt}){return new Codec(et,o,tt,rt)}function baseX({name:et,prefix:o,alphabet:tt}){const{encode:rt,decode:nt}=_brrp__multiformats_scope_baseX(tt,et);return from({prefix:o,name:et,encode:rt,decode:ot=>coerce$1(nt(ot))})}function decode$2(et,o,tt,rt){const nt={};for(let lt=0;lt=8&&(st-=8,it[ct++]=255&at>>st)}if(st>=tt||255&at<<8-st)throw new SyntaxError("Unexpected end of data");return it}function encode$1(et,o,tt){const rt=o[o.length-1]==="=",nt=(1<tt;)it-=tt,ot+=o[nt&st>>it];if(it!==0&&(ot+=o[nt&st<(et[tt]=o,et),[]),alphabetCharsToBytes=alphabet.reduce((et,o,tt)=>{const rt=o.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${o}`);return et[rt]=tt,et},[]);function encode(et){return et.reduce((o,tt)=>(o+=alphabetBytesToChars[tt],o),"")}function decode$1(et){const o=[];for(const tt of et){const rt=tt.codePointAt(0);if(rt==null)throw new Error(`Invalid character: ${tt}`);const nt=alphabetCharsToBytes[rt];if(nt==null)throw new Error(`Non-base256emoji character: ${tt}`);o.push(nt)}return new Uint8Array(o)}const base256emoji=from({prefix:"🚀",name:"base256emoji",encode,decode:decode$1}),base256emoji$1=Object.freeze(Object.defineProperty({__proto__:null,base256emoji},Symbol.toStringTag,{value:"Module"})),base32=rfc4648({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper=rfc4648({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad=rfc4648({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper=rfc4648({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex=rfc4648({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper=rfc4648({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad=rfc4648({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper=rfc4648({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z=rfc4648({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$1=Object.freeze(Object.defineProperty({__proto__:null,base32,base32hex,base32hexpad,base32hexpadupper,base32hexupper,base32pad,base32padupper,base32upper,base32z},Symbol.toStringTag,{value:"Module"})),base36=baseX({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper=baseX({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$1=Object.freeze(Object.defineProperty({__proto__:null,base36,base36upper},Symbol.toStringTag,{value:"Module"})),base58btc=baseX({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr=baseX({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58=Object.freeze(Object.defineProperty({__proto__:null,base58btc,base58flickr},Symbol.toStringTag,{value:"Module"})),base64$2=rfc4648({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad=rfc4648({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url=rfc4648({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad=rfc4648({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$3=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$2,base64pad,base64url,base64urlpad},Symbol.toStringTag,{value:"Module"})),base8=rfc4648({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$1=Object.freeze(Object.defineProperty({__proto__:null,base8},Symbol.toStringTag,{value:"Module"})),identity=from({prefix:"\0",name:"identity",encode:et=>toString$2(et),decode:et=>fromString$1(et)}),identityBase=Object.freeze(Object.defineProperty({__proto__:null,identity},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases={...identityBase,...base2$1,...base8$1,...base10$1,...base16$1,...base32$1,...base36$1,...base58,...base64$3,...base256emoji$1};function allocUnsafe(et=0){return new Uint8Array(et)}function createCodec(et,o,tt,rt){return{name:et,prefix:o,encoder:{name:et,prefix:o,encode:tt},decoder:{decode:rt}}}const string$2=createCodec("utf8","u",et=>"u"+new TextDecoder("utf8").decode(et),et=>new TextEncoder().encode(et.substring(1))),ascii=createCodec("ascii","a",et=>{let o="a";for(let tt=0;tt{et=et.substring(1);const o=allocUnsafe(et.length);for(let tt=0;tt=et.relay&&o.store>=et.store&&o.filter>=et.filter&&o.lightPush>=et.lightPush}function isNewPeer(et,o){if(!et.nodeId)return!1;for(const tt of o)if(et.nodeId===tt.nodeId)return!1;return!0}function addCapabilities(et,o){et.relay&&(o.relay+=1),et.store&&(o.store+=1),et.filter&&(o.filter+=1),et.lightPush&&(o.lightPush+=1)}function helpsSatisfyCapabilities(et,o,tt){if(isSatisfied(o,tt))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";const rt=missingCapabilities(o,tt);return rt.relay&&et.relay||rt.store&&et.store||rt.filter&&et.filter||rt.lightPush&&et.lightPush}function missingCapabilities(et,o){return{relay:o.relaythis._search(ot,it));return log$5.info("retrieved peers: ",st.map(at=>{var ct,lt;return{id:(ct=at.peerId)==null?void 0:ct.toString(),multiaddrs:(lt=at.multiaddrs)==null?void 0:lt.map(dt=>dt.toString())}})),st}async*getNextPeer(o,tt){const rt=Math.floor(Math.random()*o.length),{publicKey:nt,domain:ot}=ENRTree.parseTree(o[rt]),it={domain:ot,publicKey:nt,visits:{}};for await(const st of yieldNodesUntilCapabilitiesFulfilled(tt,this._errorTolerance,()=>this._search(ot,it)))yield st}async _search(o,tt){try{const rt=await this._getTXTRecord(o,tt);tt.visits[o]=!0;let nt,ot;const it=getEntryType(rt);try{switch(it){case ENRTree.ROOT_PREFIX:return nt=ENRTree.parseAndVerifyRoot(rt,tt.publicKey),await this._search(nt,tt);case ENRTree.BRANCH_PREFIX:return ot=ENRTree.parseBranch(rt),nt=selectRandomPath(ot,tt),await this._search(nt,tt);case ENRTree.RECORD_PREFIX:return EnrDecoder.fromString(rt);default:return null}}catch(st){return log$5.error(`Failed to search DNS tree ${it} at subdomain ${o}: ${st}`),null}}catch(rt){return log$5.error(`Failed to retrieve TXT record at subdomain ${o}: ${rt}`),null}}async _getTXTRecord(o,tt){if(this._DNSTreeCache[o])return this._DNSTreeCache[o];const rt=o!==tt.domain?`${o}.${tt.domain}`:tt.domain,nt=await this.dns.resolveTXT(rt);if(!nt.length)throw new Error("Received empty result array while fetching TXT record");if(!nt[0].length)throw new Error("Received empty TXT record");const ot=nt.join("");return this._DNSTreeCache[o]=ot,ot}}function getEntryType(et){return et.startsWith(ENRTree.ROOT_PREFIX)?ENRTree.ROOT_PREFIX:et.startsWith(ENRTree.BRANCH_PREFIX)?ENRTree.BRANCH_PREFIX:et.startsWith(ENRTree.RECORD_PREFIX)?ENRTree.RECORD_PREFIX:""}function selectRandomPath(et,o){const tt={};for(const[nt,ot]of et.entries())o.visits[ot]&&(tt[nt]=!0);if(Object.keys(tt).length===et.length)throw new Error("Unresolvable circular path detected");let rt;do rt=Math.floor(Math.random()*et.length);while(tt[rt]);return et[rt]}const log$4=new Logger$1("peer-discovery-dns");class PeerDiscoveryDns extends TypedEventEmitter$3{constructor(tt,rt){super();wt(this,"nextPeer");wt(this,"_started");wt(this,"_components");wt(this,"_options");this._started=!1,this._components=tt,this._options=rt;const{enrUrls:nt}=rt;log$4.info("Use following EIP-1459 ENR Tree URLs: ",nt)}async start(){log$4.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:tt}=this._options;Array.isArray(tt)||(tt=[tt]);const{wantedNodeCapabilityCount:rt}=this._options,nt=await DnsNodeDiscovery.dnsOverHttp();this.nextPeer=nt.getNextPeer.bind(nt,tt,rt)}for await(const tt of this.nextPeer()){if(!this._started)return;const{peerInfo:rt,shardInfo:nt}=tt;if(!rt)continue;const ot={[DEFAULT_BOOTSTRAP_TAG_NAME]:{value:this._options.tagValue??DEFAULT_BOOTSTRAP_TAG_VALUE,ttl:this._options.tagTTL??DEFAULT_BOOTSTRAP_TAG_TTL}};let it=!1;await this._components.peerStore.has(rt.id)?(await this._components.peerStore.get(rt.id)).tags.has(DEFAULT_BOOTSTRAP_TAG_NAME)||(it=!0,await this._components.peerStore.merge(rt.id,{tags:ot})):(it=!0,await this._components.peerStore.save(rt.id,{tags:ot,...nt&&{metadata:{shardInfo:encodeRelayShard(nt)}}})),it&&this.dispatchEvent(new CustomEvent("peer",{detail:rt}))}}stop(){this._started=!1}get[peerDiscoverySymbol$2](){return!0}get[Symbol.toStringTag](){return DNS_DISCOVERY_TAG}}function wakuDnsDiscovery(et,o=DEFAULT_NODE_REQUIREMENTS){return tt=>new PeerDiscoveryDns(tt,{enrUrls:et,wantedNodeCapabilityCount:o})}class PeerExchangeRPC{constructor(o){wt(this,"proto");this.proto=o}static createRequest(o){const{numPeers:tt}=o;return new PeerExchangeRPC({query:{numPeers:tt},response:void 0})}encode(){return PeerExchangeRPC$1.encode(this.proto)}static decode(o){const tt=PeerExchangeRPC$1.decode(o);return new PeerExchangeRPC(tt)}get query(){return this.proto.query}get response(){return this.proto.response}}const PeerExchangeCodec="/vac/waku/peer-exchange/2.0.0-alpha1",log$3=new Logger$1("peer-exchange");class WakuPeerExchange extends BaseProtocol{constructor(o,tt){super(PeerExchangeCodec,o,log$3,tt)}async query(o){const{numPeers:tt,peerId:rt}=o,nt=PeerExchangeRPC.createRequest({numPeers:BigInt(tt)}),ot=await this.components.peerStore.get(rt);if(!ot)return{peerInfos:null,error:ProtocolError$1.NO_PEER_AVAILABLE};let it;try{it=await this.getStream(ot)}catch(at){return log$3.error("Failed to get stream",at),{peerInfos:null,error:ProtocolError$1.NO_STREAM_AVAILABLE}}const st=await pipe([nt.encode()],encode$K,it,decode$U,async at=>await all$2(at));try{const at=new Uint8ArrayList;st.forEach(dt=>{at.append(dt)});const{response:ct}=PeerExchangeRPC.decode(at);return ct?{peerInfos:await Promise.all(ct.peerInfos.map(dt=>dt.enr).filter(isDefined).map(async dt=>({ENR:await EnrDecoder.fromRLP(dt)}))),error:null}:(log$3.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:ProtocolError$1.EMPTY_PAYLOAD})}catch(at){return log$3.error("Failed to decode push reply",at),{peerInfos:null,error:ProtocolError$1.DECODE_FAILED}}}}const log$2=new Logger$1("peer-exchange-discovery"),DEFAULT_PEER_EXCHANGE_REQUEST_NODES=10,DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS=10*1e3,DEFAULT_MAX_RETRIES=3,DEFAULT_PEER_EXCHANGE_TAG_NAME=Tags.PEER_EXCHANGE,DEFAULT_PEER_EXCHANGE_TAG_VALUE=50,DEFAULT_PEER_EXCHANGE_TAG_TTL=1e8;class PeerExchangeDiscovery extends TypedEventEmitter$3{constructor(tt,rt,nt={}){super();wt(this,"components");wt(this,"peerExchange");wt(this,"options");wt(this,"isStarted");wt(this,"queryingPeers",new Set);wt(this,"queryAttempts",new Map);wt(this,"handleDiscoveredPeer",tt=>{const{protocols:rt,peerId:nt}=tt.detail;!rt.includes(PeerExchangeCodec)||this.queryingPeers.has(nt.toString())||(this.queryingPeers.add(nt.toString()),this.startRecurringQueries(nt).catch(ot=>log$2.error(`Error querying peer ${ot}`)))});wt(this,"startRecurringQueries",async tt=>{const rt=tt.toString(),{queryInterval:nt=DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS,maxRetries:ot=DEFAULT_MAX_RETRIES}=this.options;log$2.info(`Querying peer: ${rt} (attempt ${this.queryAttempts.get(rt)??1})`),await this.query(tt);const it=this.queryAttempts.get(rt)??1;if(it>ot){this.abortQueriesForPeer(rt);return}setTimeout(()=>{this.queryAttempts.set(rt,it+1),this.startRecurringQueries(tt).catch(st=>{log$2.error(`Error in startRecurringQueries: ${st}`)})},nt*it)});this.components=tt,this.peerExchange=new WakuPeerExchange(tt,rt),this.options=nt,this.isStarted=!1}start(){this.isStarted||(this.dispatchEvent(new CustomEvent("waku:peer-exchange:started",{detail:!0})),log$2.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(log$2.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[peerDiscoverySymbol$2](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}async query(tt){const{error:rt,peerInfos:nt}=await this.peerExchange.query({numPeers:DEFAULT_PEER_EXCHANGE_REQUEST_NODES,peerId:tt});if(rt)return log$2.error("Peer exchange query failed",rt),{error:rt,peerInfos:null};for(const ot of nt){const{ENR:it}=ot;if(!it){log$2.warn("No ENR in peerInfo object, skipping");continue}const{peerId:st,peerInfo:at,shardInfo:ct}=it;if(!st||!at)continue;if(await this.components.peerStore.has(st)){const{hasMultiaddrDiff:dt,hasShardDiff:ht}=await this.checkPeerInfoDiff(at,ct);if(dt||ht){log$2.info(`Peer ${st.toString()} has updated multiaddrs or shardInfo, updating`),dt&&(log$2.info(`Peer ${st.toString()} has updated multiaddrs, updating`),await this.components.peerStore.patch(st,{multiaddrs:at.multiaddrs})),ht&&ct&&(log$2.info(`Peer ${st.toString()} has updated shardInfo, updating`),await this.components.peerStore.merge(st,{metadata:{shardInfo:encodeRelayShard(ct)}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:st,multiaddrs:at.multiaddrs}})));continue}}await this.components.peerStore.save(st,{tags:{[DEFAULT_PEER_EXCHANGE_TAG_NAME]:{value:this.options.tagValue??DEFAULT_PEER_EXCHANGE_TAG_VALUE,ttl:this.options.tagTTL??DEFAULT_PEER_EXCHANGE_TAG_TTL}},...ct&&{metadata:{shardInfo:encodeRelayShard(ct)}},...at.multiaddrs&&{multiaddrs:at.multiaddrs}}),log$2.info(`Discovered peer: ${st.toString()}`),this.dispatchEvent(new CustomEvent("peer",{detail:{id:st,multiaddrs:at.multiaddrs}}))}return{error:null,peerInfos:nt}}abortQueriesForPeer(tt){log$2.info(`Aborting queries for peer: ${tt}`),this.queryingPeers.delete(tt),this.queryAttempts.delete(tt)}async checkPeerInfoDiff(tt,rt){const{id:nt}=tt,ot=await this.components.peerStore.get(nt),it=ot.addresses.map(dt=>dt.multiaddr.toString()),st=tt.multiaddrs.map(dt=>dt.toString()),at=it.some(dt=>!st.includes(dt));let ct=!1;const lt=ot.metadata.get("shardInfo");if(lt){const dt=decodeRelayShard(lt);(dt||rt)&&(ct=dt.clusterId!==(rt==null?void 0:rt.clusterId)||dt.shards.some(ht=>!(rt!=null&&rt.shards.includes(ht))))}return{hasMultiaddrDiff:at,hasShardDiff:ct}}}function wakuPeerExchangeDiscovery(et){return o=>new PeerExchangeDiscovery(o,et)}const log$1=new Logger$1("peer-exchange-discovery"),DEFAULT_LOCAL_TAG_NAME=Tags.LOCAL,DEFAULT_LOCAL_TAG_VALUE=50,DEFAULT_LOCAL_TAG_TTL=1e8;class LocalPeerCacheDiscovery extends TypedEventEmitter$3{constructor(tt,rt){super();wt(this,"components");wt(this,"options");wt(this,"isStarted");wt(this,"peers",[]);wt(this,"handleNewPeers",tt=>{const{peerId:rt,listenAddrs:nt}=tt.detail,ot=getWsMultiaddrFromMultiaddrs(nt),it=this.getPeersFromLocalStorage(),st=it.findIndex(at=>at.id===rt.toString());st>=0?it[st].address=ot.toString():it.push({id:rt.toString(),address:ot.toString()}),this.peers=it,this.savePeersToLocalStorage()});this.components=tt,this.options=rt,this.isStarted=!1,this.peers=this.getPeersFromLocalStorage()}get[Symbol.toStringTag](){return"@waku/local-peer-cache-discovery"}async start(){var tt,rt,nt;if(!this.isStarted){log$1.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers);for(const{id:ot,address:it}of this.peers){const st=peerIdFromString$1(ot);await this.components.peerStore.has(st)||(await this.components.peerStore.save(st,{multiaddrs:[multiaddr(it)],tags:{[((tt=this.options)==null?void 0:tt.tagName)??DEFAULT_LOCAL_TAG_NAME]:{value:((rt=this.options)==null?void 0:rt.tagValue)??DEFAULT_LOCAL_TAG_VALUE,ttl:((nt=this.options)==null?void 0:nt.tagTTL)??DEFAULT_LOCAL_TAG_TTL}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:st,multiaddrs:[multiaddr(it)]}})))}log$1.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(log$1.info("Stopping Local Storage Discovery"),this.components.events.removeEventListener("peer:identify",this.handleNewPeers),this.isStarted=!1,this.savePeersToLocalStorage())}getPeersFromLocalStorage(){try{const tt=localStorage.getItem("waku:peers");return tt?JSON.parse(tt).filter(isValidStoredPeer):[]}catch(tt){return log$1.error("Error parsing peers from local storage:",tt),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(tt){log$1.error("Error saving peers to local storage:",tt)}}}function isValidStoredPeer(et){return et&&typeof et=="object"&&typeof et.id=="string"&&typeof et.address=="string"}function wakuLocalPeerCacheDiscovery(){return(et,o)=>new LocalPeerCacheDiscovery(et,o)}function defaultPeerDiscoveries(et){const o=[enrTree.SANDBOX,enrTree.TEST];return[wakuDnsDiscovery(o),wakuLocalPeerCacheDiscovery(),wakuPeerExchangeDiscovery(et)]}const log=new Logger$1("sdk:create");async function defaultLibp2p(et,o,tt){var ot,it;!(o!=null&&o.hideWebSocketInfo)&&((ot=process==null?void 0:process.env)==null?void 0:ot.NODE_ENV)!=="test"&&(console.info("%cIgnore WebSocket connection failures","background: gray; color: white; font-size: x-large"),console.info("%cWaku tries to discover peers and some of them are expected to fail","background: gray; color: white; font-size: x-large"));const rt=et?{metadata:wakuMetadata(et)}:{},nt=(o==null?void 0:o.filterMultiaddrs)===!1||((it=process==null?void 0:process.env)==null?void 0:it.NODE_ENV)==="test"?all$1:wss;return createLibp2p({transports:[webSockets({filter:nt})],streamMuxers:[mplex()],connectionEncrypters:[noise()],...o,services:{identify:identify({agentVersion:tt??DefaultUserAgent}),ping:ping({maxInboundStreams:(o==null?void 0:o.pingMaxInboundStreams)??DefaultPingMaxInboundStreams}),...rt,...o==null?void 0:o.services}})}async function createLibp2pAndUpdateOptions(et){const{networkConfig:o}=et,tt=derivePubsubTopicsFromNetworkConfig(o??DefaultNetworkConfig);log.info("Creating Waku node with pubsub topics",tt);const rt=(et==null?void 0:et.libp2p)??{},nt=rt.peerDiscovery??[];return et!=null&&et.defaultBootstrap&&nt.push(...defaultPeerDiscoveries(tt)),et!=null&&et.bootstrapPeers&&nt.push(bootstrap({list:et.bootstrapPeers})),rt.peerDiscovery=nt,{libp2p:await defaultLibp2p(tt,rt,et==null?void 0:et.userAgent),pubsubTopics:tt}}async function createLightNode(et={}){const{libp2p:o,pubsubTopics:tt}=await createLibp2pAndUpdateOptions(et);return new WakuNode(tt,et,o,{store:!0,lightpush:!0,filter:!0})}React.createContext({decoder:void 0,encoder:void 0});const useCreateNode=et=>{const{factory:o,options:tt,protocols:rt=[]}=et,[nt,ot]=React.useState(void 0),[it,st]=React.useState(!0),[at,ct]=React.useState(void 0);return React.useEffect(()=>{let lt=!1;return st(!0),o(tt).then(async dt=>{lt||(await dt.start(),await waitForRemotePeer(dt,rt),ot(dt),st(!1))}).catch(dt=>{st(!1),ct(`Failed at creating node: ${(dt==null?void 0:dt.message)||"no message"}`)}),()=>{lt=!0}},[]),{node:nt,error:at,isLoading:it}},useCreateLightNode=et=>useCreateNode({...et,factory:createLightNode}),WakuContext=React.createContext({node:void 0,isLoading:!1,error:void 0}),useWaku=()=>React.useContext(WakuContext),LightNodeProvider=et=>{const o=useCreateLightNode({options:et.options,protocols:et.protocols});return React.createElement(WakuContext.Provider,{value:o},et.children)};/** + * @license lucide-react v0.453.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const toKebabCase=et=>et.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),mergeClasses=(...et)=>et.filter((o,tt,rt)=>!!o&&rt.indexOf(o)===tt).join(" ");/** + * @license lucide-react v0.453.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var defaultAttributes={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.453.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Icon=reactExports.forwardRef(({color:et="currentColor",size:o=24,strokeWidth:tt=2,absoluteStrokeWidth:rt,className:nt="",children:ot,iconNode:it,...st},at)=>reactExports.createElement("svg",{ref:at,...defaultAttributes,width:o,height:o,stroke:et,strokeWidth:rt?Number(tt)*24/Number(o):tt,className:mergeClasses("lucide",nt),...st},[...it.map(([ct,lt])=>reactExports.createElement(ct,lt)),...Array.isArray(ot)?ot:[ot]]));/** + * @license lucide-react v0.453.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const createLucideIcon=(et,o)=>{const tt=reactExports.forwardRef(({className:rt,...nt},ot)=>reactExports.createElement(Icon,{ref:ot,iconNode:o,className:mergeClasses(`lucide-${toKebabCase(et)}`,rt),...nt}));return tt.displayName=`${et}`,tt};/** + * @license lucide-react v0.453.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Check=createLucideIcon("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** + * @license lucide-react v0.453.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Copy=createLucideIcon("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** + * @license lucide-react v0.453.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const LoaderCircle=createLucideIcon("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),Header=({wakuStatus:et})=>{const{address:o,isConnected:tt}=useAccount(),{disconnect:rt}=useDisconnect(),{isLoading:nt,error:ot,node:it}=useWaku(),[st,at]=reactExports.useState(0),ct=useLocation(),{data:lt}=useEnsName({address:o});reactExports.useEffect(()=>{if(it){const ht=()=>{at(it.libp2p.getConnections().length)};return ht(),it.libp2p.addEventListener("peer:connect",ht),it.libp2p.addEventListener("peer:disconnect",ht),()=>{it.libp2p.removeEventListener("peer:connect",ht),it.libp2p.removeEventListener("peer:disconnect",ht)}}},[it]);const dt=ht=>{switch(ht){case"success":return"bg-green-500";case"in-progress":return"bg-yellow-500";case"error":return"bg-red-500"}};return jsxRuntimeExports.jsx("header",{className:"border-b",children:jsxRuntimeExports.jsx("div",{className:"container mx-auto px-4 py-2 md:py-4",children:jsxRuntimeExports.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-center space-y-2 md:space-y-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4 w-full md:w-auto",children:[jsxRuntimeExports.jsx("h1",{className:"text-xl md:text-2xl font-bold",children:"BuddyBook"}),jsxRuntimeExports.jsx("nav",{className:"w-full md:w-auto",children:jsxRuntimeExports.jsxs("ul",{className:"flex justify-center md:justify-start space-x-4",children:[jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsx(Link,{to:"/create",className:`text-sm ${ct.pathname==="/create"?"text-primary font-semibold":"text-muted-foreground"}`,children:"Create Chain"})}),jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsx(Link,{to:"/view",className:`text-sm ${ct.pathname==="/view"?"text-primary font-semibold":"text-muted-foreground"}`,children:"View Chains"})}),jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsx(Link,{to:"/telemetry",className:`text-sm ${ct.pathname==="/telemetry"?"text-primary font-semibold":"text-muted-foreground"}`,children:"Telemetry"})})]})})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap justify-center md:justify-end items-center gap-2 w-full md:w-auto",children:[jsxRuntimeExports.jsx("div",{className:"flex items-center space-x-2 text-xs md:text-sm",children:nt?jsxRuntimeExports.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Connecting..."})]}):ot?jsxRuntimeExports.jsx("span",{className:"text-destructive",children:"Network Error"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center space-x-1",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Filter:"}),jsxRuntimeExports.jsx("div",{className:`w-2 h-2 md:w-3 md:h-3 rounded-full ${dt(et.filter)}`})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center space-x-1",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Store:"}),jsxRuntimeExports.jsx("div",{className:`w-2 h-2 md:w-3 md:h-3 rounded-full ${dt(et.store)}`})]}),jsxRuntimeExports.jsx("span",{className:"text-xs md:text-sm text-muted-foreground hidden md:inline",children:st>0?`${st} peer${st===1?"":"s"}`:"Connecting..."})]})}),jsxRuntimeExports.jsxs("div",{className:"flex items-center space-x-2",children:[nt?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}):ot?jsxRuntimeExports.jsx("span",{className:"text-xs md:text-sm text-red-500",children:"Waku Error"}):jsxRuntimeExports.jsxs("span",{className:"text-xs md:text-sm text-muted-foreground hidden md:inline",children:["Waku Connections: ",st]}),tt?jsxRuntimeExports.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntimeExports.jsx("span",{className:"text-xs md:text-sm text-muted-foreground truncate max-w-[120px] md:max-w-none",children:lt||(o?`${o.slice(0,6)}...${o.slice(-4)}`:"")}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",onClick:()=>rt(),children:"Logout"})]}):jsxRuntimeExports.jsx(ConnectKitButton,{})]})]})]})})})},Input=reactExports.forwardRef(({className:et,type:o,...tt},rt)=>jsxRuntimeExports.jsx("input",{type:o,className:cn("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",et),ref:rt,...tt}));Input.displayName="Input";const Textarea=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx("textarea",{className:cn("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",et),ref:tt,...o}));Textarea.displayName="Textarea";var NODES=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Primitive=NODES.reduce((et,o)=>{const tt=reactExports.forwardRef((rt,nt)=>{const{asChild:ot,...it}=rt,st=ot?Slot:o;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),jsxRuntimeExports.jsx(st,{...it,ref:nt})});return tt.displayName=`Primitive.${o}`,{...et,[o]:tt}},{});function dispatchDiscreteCustomEvent(et,o){et&&reactDomExports.flushSync(()=>et.dispatchEvent(o))}var NAME="Label",Label$1=reactExports.forwardRef((et,o)=>jsxRuntimeExports.jsx(Primitive.label,{...et,ref:o,onMouseDown:tt=>{var nt;tt.target.closest("button, input, select, textarea")||((nt=et.onMouseDown)==null||nt.call(et,tt),!tt.defaultPrevented&&tt.detail>1&&tt.preventDefault())}}));Label$1.displayName=NAME;var Root$3=Label$1;const labelVariants=cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Label=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx(Root$3,{ref:tt,className:cn(labelVariants(),et),...o}));Label.displayName=Root$3.displayName;const Card=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx("div",{ref:tt,className:cn("rounded-lg border bg-card text-card-foreground shadow-sm p-4 md:p-6",et),...o}));Card.displayName="Card";const CardHeader=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx("div",{ref:tt,className:cn("flex flex-col space-y-1.5 p-4 md:p-6",et),...o}));CardHeader.displayName="CardHeader";const CardTitle=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx("h3",{ref:tt,className:cn("font-semibold leading-none tracking-tight",et),...o}));CardTitle.displayName="CardTitle";const CardDescription=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx("p",{ref:tt,className:cn("text-sm text-muted-foreground",et),...o}));CardDescription.displayName="CardDescription";const CardContent=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx("div",{ref:tt,className:cn("p-6 pt-0",et),...o}));CardContent.displayName="CardContent";const CardFooter=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx("div",{ref:tt,className:cn("flex items-center p-6 pt-0",et),...o}));CardFooter.displayName="CardFooter";function composeEventHandlers(et,o,{checkForDefaultPrevented:tt=!0}={}){return function(nt){if(et==null||et(nt),tt===!1||!nt.defaultPrevented)return o==null?void 0:o(nt)}}function createContext2(et,o){const tt=reactExports.createContext(o),rt=ot=>{const{children:it,...st}=ot,at=reactExports.useMemo(()=>st,Object.values(st));return jsxRuntimeExports.jsx(tt.Provider,{value:at,children:it})};rt.displayName=et+"Provider";function nt(ot){const it=reactExports.useContext(tt);if(it)return it;if(o!==void 0)return o;throw new Error(`\`${ot}\` must be used within \`${et}\``)}return[rt,nt]}function createContextScope(et,o=[]){let tt=[];function rt(ot,it){const st=reactExports.createContext(it),at=tt.length;tt=[...tt,it];const ct=dt=>{var yt;const{scope:ht,children:mt,...ft}=dt,pt=((yt=ht==null?void 0:ht[et])==null?void 0:yt[at])||st,gt=reactExports.useMemo(()=>ft,Object.values(ft));return jsxRuntimeExports.jsx(pt.Provider,{value:gt,children:mt})};ct.displayName=ot+"Provider";function lt(dt,ht){var pt;const mt=((pt=ht==null?void 0:ht[et])==null?void 0:pt[at])||st,ft=reactExports.useContext(mt);if(ft)return ft;if(it!==void 0)return it;throw new Error(`\`${dt}\` must be used within \`${ot}\``)}return[ct,lt]}const nt=()=>{const ot=tt.map(it=>reactExports.createContext(it));return function(st){const at=(st==null?void 0:st[et])||ot;return reactExports.useMemo(()=>({[`__scope${et}`]:{...st,[et]:at}}),[st,at])}};return nt.scopeName=et,[rt,composeContextScopes(nt,...o)]}function composeContextScopes(...et){const o=et[0];if(et.length===1)return o;const tt=()=>{const rt=et.map(nt=>({useScope:nt(),scopeName:nt.scopeName}));return function(ot){const it=rt.reduce((st,{useScope:at,scopeName:ct})=>{const dt=at(ot)[`__scope${ct}`];return{...st,...dt}},{});return reactExports.useMemo(()=>({[`__scope${o.scopeName}`]:it}),[it])}};return tt.scopeName=o.scopeName,tt}var useLayoutEffect2=globalThis!=null&&globalThis.document?reactExports.useLayoutEffect:()=>{},useReactId=React$1.useId||(()=>{}),count$1=0;function useId(et){const[o,tt]=reactExports.useState(useReactId());return useLayoutEffect2(()=>{et||tt(rt=>rt??String(count$1++))},[et]),et||(o?`radix-${o}`:"")}function useCallbackRef$1(et){const o=reactExports.useRef(et);return reactExports.useEffect(()=>{o.current=et}),reactExports.useMemo(()=>(...tt)=>{var rt;return(rt=o.current)==null?void 0:rt.call(o,...tt)},[])}function useControllableState({prop:et,defaultProp:o,onChange:tt=()=>{}}){const[rt,nt]=useUncontrolledState({defaultProp:o,onChange:tt}),ot=et!==void 0,it=ot?et:rt,st=useCallbackRef$1(tt),at=reactExports.useCallback(ct=>{if(ot){const dt=typeof ct=="function"?ct(et):ct;dt!==et&&st(dt)}else nt(ct)},[ot,et,nt,st]);return[it,at]}function useUncontrolledState({defaultProp:et,onChange:o}){const tt=reactExports.useState(et),[rt]=tt,nt=reactExports.useRef(rt),ot=useCallbackRef$1(o);return reactExports.useEffect(()=>{nt.current!==rt&&(ot(rt),nt.current=rt)},[rt,nt,ot]),tt}function useEscapeKeydown(et,o=globalThis==null?void 0:globalThis.document){const tt=useCallbackRef$1(et);reactExports.useEffect(()=>{const rt=nt=>{nt.key==="Escape"&&tt(nt)};return o.addEventListener("keydown",rt,{capture:!0}),()=>o.removeEventListener("keydown",rt,{capture:!0})},[tt,o])}var DISMISSABLE_LAYER_NAME="DismissableLayer",CONTEXT_UPDATE="dismissableLayer.update",POINTER_DOWN_OUTSIDE="dismissableLayer.pointerDownOutside",FOCUS_OUTSIDE="dismissableLayer.focusOutside",originalBodyPointerEvents,DismissableLayerContext=reactExports.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),DismissableLayer=reactExports.forwardRef((et,o)=>{const{disableOutsidePointerEvents:tt=!1,onEscapeKeyDown:rt,onPointerDownOutside:nt,onFocusOutside:ot,onInteractOutside:it,onDismiss:st,...at}=et,ct=reactExports.useContext(DismissableLayerContext),[lt,dt]=reactExports.useState(null),ht=(lt==null?void 0:lt.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,mt]=reactExports.useState({}),ft=useComposedRefs(o,St=>dt(St)),pt=Array.from(ct.layers),[gt]=[...ct.layersWithOutsidePointerEventsDisabled].slice(-1),yt=pt.indexOf(gt),bt=lt?pt.indexOf(lt):-1,xt=ct.layersWithOutsidePointerEventsDisabled.size>0,vt=bt>=yt,Et=usePointerDownOutside(St=>{const At=St.target,kt=[...ct.branches].some(It=>It.contains(At));!vt||kt||(nt==null||nt(St),it==null||it(St),St.defaultPrevented||st==null||st())},ht),Ct=useFocusOutside(St=>{const At=St.target;[...ct.branches].some(It=>It.contains(At))||(ot==null||ot(St),it==null||it(St),St.defaultPrevented||st==null||st())},ht);return useEscapeKeydown(St=>{bt===ct.layers.size-1&&(rt==null||rt(St),!St.defaultPrevented&&st&&(St.preventDefault(),st()))},ht),reactExports.useEffect(()=>{if(lt)return tt&&(ct.layersWithOutsidePointerEventsDisabled.size===0&&(originalBodyPointerEvents=ht.body.style.pointerEvents,ht.body.style.pointerEvents="none"),ct.layersWithOutsidePointerEventsDisabled.add(lt)),ct.layers.add(lt),dispatchUpdate(),()=>{tt&&ct.layersWithOutsidePointerEventsDisabled.size===1&&(ht.body.style.pointerEvents=originalBodyPointerEvents)}},[lt,ht,tt,ct]),reactExports.useEffect(()=>()=>{lt&&(ct.layers.delete(lt),ct.layersWithOutsidePointerEventsDisabled.delete(lt),dispatchUpdate())},[lt,ct]),reactExports.useEffect(()=>{const St=()=>mt({});return document.addEventListener(CONTEXT_UPDATE,St),()=>document.removeEventListener(CONTEXT_UPDATE,St)},[]),jsxRuntimeExports.jsx(Primitive.div,{...at,ref:ft,style:{pointerEvents:xt?vt?"auto":"none":void 0,...et.style},onFocusCapture:composeEventHandlers(et.onFocusCapture,Ct.onFocusCapture),onBlurCapture:composeEventHandlers(et.onBlurCapture,Ct.onBlurCapture),onPointerDownCapture:composeEventHandlers(et.onPointerDownCapture,Et.onPointerDownCapture)})});DismissableLayer.displayName=DISMISSABLE_LAYER_NAME;var BRANCH_NAME="DismissableLayerBranch",DismissableLayerBranch=reactExports.forwardRef((et,o)=>{const tt=reactExports.useContext(DismissableLayerContext),rt=reactExports.useRef(null),nt=useComposedRefs(o,rt);return reactExports.useEffect(()=>{const ot=rt.current;if(ot)return tt.branches.add(ot),()=>{tt.branches.delete(ot)}},[tt.branches]),jsxRuntimeExports.jsx(Primitive.div,{...et,ref:nt})});DismissableLayerBranch.displayName=BRANCH_NAME;function usePointerDownOutside(et,o=globalThis==null?void 0:globalThis.document){const tt=useCallbackRef$1(et),rt=reactExports.useRef(!1),nt=reactExports.useRef(()=>{});return reactExports.useEffect(()=>{const ot=st=>{if(st.target&&!rt.current){let at=function(){handleAndDispatchCustomEvent(POINTER_DOWN_OUTSIDE,tt,ct,{discrete:!0})};const ct={originalEvent:st};st.pointerType==="touch"?(o.removeEventListener("click",nt.current),nt.current=at,o.addEventListener("click",nt.current,{once:!0})):at()}else o.removeEventListener("click",nt.current);rt.current=!1},it=window.setTimeout(()=>{o.addEventListener("pointerdown",ot)},0);return()=>{window.clearTimeout(it),o.removeEventListener("pointerdown",ot),o.removeEventListener("click",nt.current)}},[o,tt]),{onPointerDownCapture:()=>rt.current=!0}}function useFocusOutside(et,o=globalThis==null?void 0:globalThis.document){const tt=useCallbackRef$1(et),rt=reactExports.useRef(!1);return reactExports.useEffect(()=>{const nt=ot=>{ot.target&&!rt.current&&handleAndDispatchCustomEvent(FOCUS_OUTSIDE,tt,{originalEvent:ot},{discrete:!1})};return o.addEventListener("focusin",nt),()=>o.removeEventListener("focusin",nt)},[o,tt]),{onFocusCapture:()=>rt.current=!0,onBlurCapture:()=>rt.current=!1}}function dispatchUpdate(){const et=new CustomEvent(CONTEXT_UPDATE);document.dispatchEvent(et)}function handleAndDispatchCustomEvent(et,o,tt,{discrete:rt}){const nt=tt.originalEvent.target,ot=new CustomEvent(et,{bubbles:!1,cancelable:!0,detail:tt});o&&nt.addEventListener(et,o,{once:!0}),rt?dispatchDiscreteCustomEvent(nt,ot):nt.dispatchEvent(ot)}var AUTOFOCUS_ON_MOUNT="focusScope.autoFocusOnMount",AUTOFOCUS_ON_UNMOUNT="focusScope.autoFocusOnUnmount",EVENT_OPTIONS={bubbles:!1,cancelable:!0},FOCUS_SCOPE_NAME="FocusScope",FocusScope=reactExports.forwardRef((et,o)=>{const{loop:tt=!1,trapped:rt=!1,onMountAutoFocus:nt,onUnmountAutoFocus:ot,...it}=et,[st,at]=reactExports.useState(null),ct=useCallbackRef$1(nt),lt=useCallbackRef$1(ot),dt=reactExports.useRef(null),ht=useComposedRefs(o,pt=>at(pt)),mt=reactExports.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;reactExports.useEffect(()=>{if(rt){let pt=function(xt){if(mt.paused||!st)return;const vt=xt.target;st.contains(vt)?dt.current=vt:focus(dt.current,{select:!0})},gt=function(xt){if(mt.paused||!st)return;const vt=xt.relatedTarget;vt!==null&&(st.contains(vt)||focus(dt.current,{select:!0}))},yt=function(xt){if(document.activeElement===document.body)for(const Et of xt)Et.removedNodes.length>0&&focus(st)};document.addEventListener("focusin",pt),document.addEventListener("focusout",gt);const bt=new MutationObserver(yt);return st&&bt.observe(st,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",pt),document.removeEventListener("focusout",gt),bt.disconnect()}}},[rt,st,mt.paused]),reactExports.useEffect(()=>{if(st){focusScopesStack.add(mt);const pt=document.activeElement;if(!st.contains(pt)){const yt=new CustomEvent(AUTOFOCUS_ON_MOUNT,EVENT_OPTIONS);st.addEventListener(AUTOFOCUS_ON_MOUNT,ct),st.dispatchEvent(yt),yt.defaultPrevented||(focusFirst(removeLinks(getTabbableCandidates(st)),{select:!0}),document.activeElement===pt&&focus(st))}return()=>{st.removeEventListener(AUTOFOCUS_ON_MOUNT,ct),setTimeout(()=>{const yt=new CustomEvent(AUTOFOCUS_ON_UNMOUNT,EVENT_OPTIONS);st.addEventListener(AUTOFOCUS_ON_UNMOUNT,lt),st.dispatchEvent(yt),yt.defaultPrevented||focus(pt??document.body,{select:!0}),st.removeEventListener(AUTOFOCUS_ON_UNMOUNT,lt),focusScopesStack.remove(mt)},0)}}},[st,ct,lt,mt]);const ft=reactExports.useCallback(pt=>{if(!tt&&!rt||mt.paused)return;const gt=pt.key==="Tab"&&!pt.altKey&&!pt.ctrlKey&&!pt.metaKey,yt=document.activeElement;if(gt&&yt){const bt=pt.currentTarget,[xt,vt]=getTabbableEdges(bt);xt&&vt?!pt.shiftKey&&yt===vt?(pt.preventDefault(),tt&&focus(xt,{select:!0})):pt.shiftKey&&yt===xt&&(pt.preventDefault(),tt&&focus(vt,{select:!0})):yt===bt&&pt.preventDefault()}},[tt,rt,mt.paused]);return jsxRuntimeExports.jsx(Primitive.div,{tabIndex:-1,...it,ref:ht,onKeyDown:ft})});FocusScope.displayName=FOCUS_SCOPE_NAME;function focusFirst(et,{select:o=!1}={}){const tt=document.activeElement;for(const rt of et)if(focus(rt,{select:o}),document.activeElement!==tt)return}function getTabbableEdges(et){const o=getTabbableCandidates(et),tt=findVisible(o,et),rt=findVisible(o.reverse(),et);return[tt,rt]}function getTabbableCandidates(et){const o=[],tt=document.createTreeWalker(et,NodeFilter.SHOW_ELEMENT,{acceptNode:rt=>{const nt=rt.tagName==="INPUT"&&rt.type==="hidden";return rt.disabled||rt.hidden||nt?NodeFilter.FILTER_SKIP:rt.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;tt.nextNode();)o.push(tt.currentNode);return o}function findVisible(et,o){for(const tt of et)if(!isHidden(tt,{upTo:o}))return tt}function isHidden(et,{upTo:o}){if(getComputedStyle(et).visibility==="hidden")return!0;for(;et;){if(o!==void 0&&et===o)return!1;if(getComputedStyle(et).display==="none")return!0;et=et.parentElement}return!1}function isSelectableInput(et){return et instanceof HTMLInputElement&&"select"in et}function focus(et,{select:o=!1}={}){if(et&&et.focus){const tt=document.activeElement;et.focus({preventScroll:!0}),et!==tt&&isSelectableInput(et)&&o&&et.select()}}var focusScopesStack=createFocusScopesStack();function createFocusScopesStack(){let et=[];return{add(o){const tt=et[0];o!==tt&&(tt==null||tt.pause()),et=arrayRemove(et,o),et.unshift(o)},remove(o){var tt;et=arrayRemove(et,o),(tt=et[0])==null||tt.resume()}}}function arrayRemove(et,o){const tt=[...et],rt=tt.indexOf(o);return rt!==-1&&tt.splice(rt,1),tt}function removeLinks(et){return et.filter(o=>o.tagName!=="A")}var PORTAL_NAME$1="Portal",Portal$1=reactExports.forwardRef((et,o)=>{var st;const{container:tt,...rt}=et,[nt,ot]=reactExports.useState(!1);useLayoutEffect2(()=>ot(!0),[]);const it=tt||nt&&((st=globalThis==null?void 0:globalThis.document)==null?void 0:st.body);return it?ReactDOM.createPortal(jsxRuntimeExports.jsx(Primitive.div,{...rt,ref:o}),it):null});Portal$1.displayName=PORTAL_NAME$1;function useStateMachine$1(et,o){return reactExports.useReducer((tt,rt)=>o[tt][rt]??tt,et)}var Presence=et=>{const{present:o,children:tt}=et,rt=usePresence(o),nt=typeof tt=="function"?tt({present:rt.isPresent}):reactExports.Children.only(tt),ot=useComposedRefs(rt.ref,getElementRef(nt));return typeof tt=="function"||rt.isPresent?reactExports.cloneElement(nt,{ref:ot}):null};Presence.displayName="Presence";function usePresence(et){const[o,tt]=reactExports.useState(),rt=reactExports.useRef({}),nt=reactExports.useRef(et),ot=reactExports.useRef("none"),it=et?"mounted":"unmounted",[st,at]=useStateMachine$1(it,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return reactExports.useEffect(()=>{const ct=getAnimationName(rt.current);ot.current=st==="mounted"?ct:"none"},[st]),useLayoutEffect2(()=>{const ct=rt.current,lt=nt.current;if(lt!==et){const ht=ot.current,mt=getAnimationName(ct);et?at("MOUNT"):mt==="none"||(ct==null?void 0:ct.display)==="none"?at("UNMOUNT"):at(lt&&ht!==mt?"ANIMATION_OUT":"UNMOUNT"),nt.current=et}},[et,at]),useLayoutEffect2(()=>{if(o){let ct;const lt=o.ownerDocument.defaultView??window,dt=mt=>{const pt=getAnimationName(rt.current).includes(mt.animationName);if(mt.target===o&&pt&&(at("ANIMATION_END"),!nt.current)){const gt=o.style.animationFillMode;o.style.animationFillMode="forwards",ct=lt.setTimeout(()=>{o.style.animationFillMode==="forwards"&&(o.style.animationFillMode=gt)})}},ht=mt=>{mt.target===o&&(ot.current=getAnimationName(rt.current))};return o.addEventListener("animationstart",ht),o.addEventListener("animationcancel",dt),o.addEventListener("animationend",dt),()=>{lt.clearTimeout(ct),o.removeEventListener("animationstart",ht),o.removeEventListener("animationcancel",dt),o.removeEventListener("animationend",dt)}}else at("ANIMATION_END")},[o,at]),{isPresent:["mounted","unmountSuspended"].includes(st),ref:reactExports.useCallback(ct=>{ct&&(rt.current=getComputedStyle(ct)),tt(ct)},[])}}function getAnimationName(et){return(et==null?void 0:et.animationName)||"none"}function getElementRef(et){var rt,nt;let o=(rt=Object.getOwnPropertyDescriptor(et.props,"ref"))==null?void 0:rt.get,tt=o&&"isReactWarning"in o&&o.isReactWarning;return tt?et.ref:(o=(nt=Object.getOwnPropertyDescriptor(et,"ref"))==null?void 0:nt.get,tt=o&&"isReactWarning"in o&&o.isReactWarning,tt?et.props.ref:et.props.ref||et.ref)}var count=0;function useFocusGuards(){reactExports.useEffect(()=>{const et=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",et[0]??createFocusGuard()),document.body.insertAdjacentElement("beforeend",et[1]??createFocusGuard()),count++,()=>{count===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(o=>o.remove()),count--}},[])}function createFocusGuard(){const et=document.createElement("span");return et.setAttribute("data-radix-focus-guard",""),et.tabIndex=0,et.style.outline="none",et.style.opacity="0",et.style.position="fixed",et.style.pointerEvents="none",et}var zeroRightClassName="right-scroll-bar-position",fullWidthClassName="width-before-scroll-bar",noScrollbarsClassName="with-scroll-bars-hidden",removedBarSizeVariable="--removed-body-scroll-bar-size";function assignRef(et,o){return typeof et=="function"?et(o):et&&(et.current=o),et}function useCallbackRef(et,o){var tt=reactExports.useState(function(){return{value:et,callback:o,facade:{get current(){return tt.value},set current(rt){var nt=tt.value;nt!==rt&&(tt.value=rt,tt.callback(rt,nt))}}}})[0];return tt.callback=o,tt.facade}var useIsomorphicLayoutEffect=typeof window<"u"?reactExports.useLayoutEffect:reactExports.useEffect,currentValues=new WeakMap;function useMergeRefs(et,o){var tt=useCallbackRef(null,function(rt){return et.forEach(function(nt){return assignRef(nt,rt)})});return useIsomorphicLayoutEffect(function(){var rt=currentValues.get(tt);if(rt){var nt=new Set(rt),ot=new Set(et),it=tt.current;nt.forEach(function(st){ot.has(st)||assignRef(st,null)}),ot.forEach(function(st){nt.has(st)||assignRef(st,it)})}currentValues.set(tt,et)},[et]),tt}function ItoI(et){return et}function innerCreateMedium(et,o){o===void 0&&(o=ItoI);var tt=[],rt=!1,nt={read:function(){if(rt)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return tt.length?tt[tt.length-1]:et},useMedium:function(ot){var it=o(ot,rt);return tt.push(it),function(){tt=tt.filter(function(st){return st!==it})}},assignSyncMedium:function(ot){for(rt=!0;tt.length;){var it=tt;tt=[],it.forEach(ot)}tt={push:function(st){return ot(st)},filter:function(){return tt}}},assignMedium:function(ot){rt=!0;var it=[];if(tt.length){var st=tt;tt=[],st.forEach(ot),it=tt}var at=function(){var lt=it;it=[],lt.forEach(ot)},ct=function(){return Promise.resolve().then(at)};ct(),tt={push:function(lt){it.push(lt),ct()},filter:function(lt){return it=it.filter(lt),tt}}}};return nt}function createSidecarMedium(et){et===void 0&&(et={});var o=innerCreateMedium(null);return o.options=__assign({async:!0,ssr:!1},et),o}var SideCar$1=function(et){var o=et.sideCar,tt=__rest(et,["sideCar"]);if(!o)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var rt=o.read();if(!rt)throw new Error("Sidecar medium not found");return reactExports.createElement(rt,__assign({},tt))};SideCar$1.isSideCarExport=!0;function exportSidecar(et,o){return et.useMedium(o),SideCar$1}var effectCar=createSidecarMedium(),nothing=function(){},RemoveScroll=reactExports.forwardRef(function(et,o){var tt=reactExports.useRef(null),rt=reactExports.useState({onScrollCapture:nothing,onWheelCapture:nothing,onTouchMoveCapture:nothing}),nt=rt[0],ot=rt[1],it=et.forwardProps,st=et.children,at=et.className,ct=et.removeScrollBar,lt=et.enabled,dt=et.shards,ht=et.sideCar,mt=et.noIsolation,ft=et.inert,pt=et.allowPinchZoom,gt=et.as,yt=gt===void 0?"div":gt,bt=et.gapMode,xt=__rest(et,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as","gapMode"]),vt=ht,Et=useMergeRefs([tt,o]),Ct=__assign(__assign({},xt),nt);return reactExports.createElement(reactExports.Fragment,null,lt&&reactExports.createElement(vt,{sideCar:effectCar,removeScrollBar:ct,shards:dt,noIsolation:mt,inert:ft,setCallbacks:ot,allowPinchZoom:!!pt,lockRef:tt,gapMode:bt}),it?reactExports.cloneElement(reactExports.Children.only(st),__assign(__assign({},Ct),{ref:Et})):reactExports.createElement(yt,__assign({},Ct,{className:at,ref:Et}),st))});RemoveScroll.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};RemoveScroll.classNames={fullWidth:fullWidthClassName,zeroRight:zeroRightClassName};var getNonce=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function makeStyleTag(){if(!document)return null;var et=document.createElement("style");et.type="text/css";var o=getNonce();return o&&et.setAttribute("nonce",o),et}function injectStyles(et,o){et.styleSheet?et.styleSheet.cssText=o:et.appendChild(document.createTextNode(o))}function insertStyleTag(et){var o=document.head||document.getElementsByTagName("head")[0];o.appendChild(et)}var stylesheetSingleton=function(){var et=0,o=null;return{add:function(tt){et==0&&(o=makeStyleTag())&&(injectStyles(o,tt),insertStyleTag(o)),et++},remove:function(){et--,!et&&o&&(o.parentNode&&o.parentNode.removeChild(o),o=null)}}},styleHookSingleton=function(){var et=stylesheetSingleton();return function(o,tt){reactExports.useEffect(function(){return et.add(o),function(){et.remove()}},[o&&tt])}},styleSingleton=function(){var et=styleHookSingleton(),o=function(tt){var rt=tt.styles,nt=tt.dynamic;return et(rt,nt),null};return o},zeroGap={left:0,top:0,right:0,gap:0},parse$2=function(et){return parseInt(et||"",10)||0},getOffset=function(et){var o=window.getComputedStyle(document.body),tt=o[et==="padding"?"paddingLeft":"marginLeft"],rt=o[et==="padding"?"paddingTop":"marginTop"],nt=o[et==="padding"?"paddingRight":"marginRight"];return[parse$2(tt),parse$2(rt),parse$2(nt)]},getGapWidth=function(et){if(et===void 0&&(et="margin"),typeof window>"u")return zeroGap;var o=getOffset(et),tt=document.documentElement.clientWidth,rt=window.innerWidth;return{left:o[0],top:o[1],right:o[2],gap:Math.max(0,rt-tt+o[2]-o[0])}},Style=styleSingleton(),lockAttribute="data-scroll-locked",getStyles=function(et,o,tt,rt){var nt=et.left,ot=et.top,it=et.right,st=et.gap;return tt===void 0&&(tt="margin"),` + .`.concat(noScrollbarsClassName,` { + overflow: hidden `).concat(rt,`; + padding-right: `).concat(st,"px ").concat(rt,`; + } + body[`).concat(lockAttribute,`] { + overflow: hidden `).concat(rt,`; + overscroll-behavior: contain; + `).concat([o&&"position: relative ".concat(rt,";"),tt==="margin"&&` + padding-left: `.concat(nt,`px; + padding-top: `).concat(ot,`px; + padding-right: `).concat(it,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(st,"px ").concat(rt,`; + `),tt==="padding"&&"padding-right: ".concat(st,"px ").concat(rt,";")].filter(Boolean).join(""),` + } + + .`).concat(zeroRightClassName,` { + right: `).concat(st,"px ").concat(rt,`; + } + + .`).concat(fullWidthClassName,` { + margin-right: `).concat(st,"px ").concat(rt,`; + } + + .`).concat(zeroRightClassName," .").concat(zeroRightClassName,` { + right: 0 `).concat(rt,`; + } + + .`).concat(fullWidthClassName," .").concat(fullWidthClassName,` { + margin-right: 0 `).concat(rt,`; + } + + body[`).concat(lockAttribute,`] { + `).concat(removedBarSizeVariable,": ").concat(st,`px; + } +`)},getCurrentUseCounter=function(){var et=parseInt(document.body.getAttribute(lockAttribute)||"0",10);return isFinite(et)?et:0},useLockAttribute=function(){reactExports.useEffect(function(){return document.body.setAttribute(lockAttribute,(getCurrentUseCounter()+1).toString()),function(){var et=getCurrentUseCounter()-1;et<=0?document.body.removeAttribute(lockAttribute):document.body.setAttribute(lockAttribute,et.toString())}},[])},RemoveScrollBar=function(et){var o=et.noRelative,tt=et.noImportant,rt=et.gapMode,nt=rt===void 0?"margin":rt;useLockAttribute();var ot=reactExports.useMemo(function(){return getGapWidth(nt)},[nt]);return reactExports.createElement(Style,{styles:getStyles(ot,!o,nt,tt?"":"!important")})},passiveSupported=!1;if(typeof window<"u")try{var options=Object.defineProperty({},"passive",{get:function(){return passiveSupported=!0,!0}});window.addEventListener("test",options,options),window.removeEventListener("test",options,options)}catch{passiveSupported=!1}var nonPassive=passiveSupported?{passive:!1}:!1,alwaysContainsScroll=function(et){return et.tagName==="TEXTAREA"},elementCanBeScrolled=function(et,o){if(!(et instanceof Element))return!1;var tt=window.getComputedStyle(et);return tt[o]!=="hidden"&&!(tt.overflowY===tt.overflowX&&!alwaysContainsScroll(et)&&tt[o]==="visible")},elementCouldBeVScrolled=function(et){return elementCanBeScrolled(et,"overflowY")},elementCouldBeHScrolled=function(et){return elementCanBeScrolled(et,"overflowX")},locationCouldBeScrolled=function(et,o){var tt=o.ownerDocument,rt=o;do{typeof ShadowRoot<"u"&&rt instanceof ShadowRoot&&(rt=rt.host);var nt=elementCouldBeScrolled(et,rt);if(nt){var ot=getScrollVariables(et,rt),it=ot[1],st=ot[2];if(it>st)return!0}rt=rt.parentNode}while(rt&&rt!==tt.body);return!1},getVScrollVariables=function(et){var o=et.scrollTop,tt=et.scrollHeight,rt=et.clientHeight;return[o,tt,rt]},getHScrollVariables=function(et){var o=et.scrollLeft,tt=et.scrollWidth,rt=et.clientWidth;return[o,tt,rt]},elementCouldBeScrolled=function(et,o){return et==="v"?elementCouldBeVScrolled(o):elementCouldBeHScrolled(o)},getScrollVariables=function(et,o){return et==="v"?getVScrollVariables(o):getHScrollVariables(o)},getDirectionFactor=function(et,o){return et==="h"&&o==="rtl"?-1:1},handleScroll=function(et,o,tt,rt,nt){var ot=getDirectionFactor(et,window.getComputedStyle(o).direction),it=ot*rt,st=tt.target,at=o.contains(st),ct=!1,lt=it>0,dt=0,ht=0;do{var mt=getScrollVariables(et,st),ft=mt[0],pt=mt[1],gt=mt[2],yt=pt-gt-ot*ft;(ft||yt)&&elementCouldBeScrolled(et,st)&&(dt+=yt,ht+=ft),st instanceof ShadowRoot?st=st.host:st=st.parentNode}while(!at&&st!==document.body||at&&(o.contains(st)||o===st));return(lt&&(Math.abs(dt)<1||!nt)||!lt&&(Math.abs(ht)<1||!nt))&&(ct=!0),ct},getTouchXY=function(et){return"changedTouches"in et?[et.changedTouches[0].clientX,et.changedTouches[0].clientY]:[0,0]},getDeltaXY=function(et){return[et.deltaX,et.deltaY]},extractRef=function(et){return et&&"current"in et?et.current:et},deltaCompare=function(et,o){return et[0]===o[0]&&et[1]===o[1]},generateStyle=function(et){return` + .block-interactivity-`.concat(et,` {pointer-events: none;} + .allow-interactivity-`).concat(et,` {pointer-events: all;} +`)},idCounter=0,lockStack=[];function RemoveScrollSideCar(et){var o=reactExports.useRef([]),tt=reactExports.useRef([0,0]),rt=reactExports.useRef(),nt=reactExports.useState(idCounter++)[0],ot=reactExports.useState(styleSingleton)[0],it=reactExports.useRef(et);reactExports.useEffect(function(){it.current=et},[et]),reactExports.useEffect(function(){if(et.inert){document.body.classList.add("block-interactivity-".concat(nt));var pt=__spreadArray([et.lockRef.current],(et.shards||[]).map(extractRef),!0).filter(Boolean);return pt.forEach(function(gt){return gt.classList.add("allow-interactivity-".concat(nt))}),function(){document.body.classList.remove("block-interactivity-".concat(nt)),pt.forEach(function(gt){return gt.classList.remove("allow-interactivity-".concat(nt))})}}},[et.inert,et.lockRef.current,et.shards]);var st=reactExports.useCallback(function(pt,gt){if("touches"in pt&&pt.touches.length===2||pt.type==="wheel"&&pt.ctrlKey)return!it.current.allowPinchZoom;var yt=getTouchXY(pt),bt=tt.current,xt="deltaX"in pt?pt.deltaX:bt[0]-yt[0],vt="deltaY"in pt?pt.deltaY:bt[1]-yt[1],Et,Ct=pt.target,St=Math.abs(xt)>Math.abs(vt)?"h":"v";if("touches"in pt&&St==="h"&&Ct.type==="range")return!1;var At=locationCouldBeScrolled(St,Ct);if(!At)return!0;if(At?Et=St:(Et=St==="v"?"h":"v",At=locationCouldBeScrolled(St,Ct)),!At)return!1;if(!rt.current&&"changedTouches"in pt&&(xt||vt)&&(rt.current=Et),!Et)return!0;var kt=rt.current||Et;return handleScroll(kt,gt,pt,kt==="h"?xt:vt,!0)},[]),at=reactExports.useCallback(function(pt){var gt=pt;if(!(!lockStack.length||lockStack[lockStack.length-1]!==ot)){var yt="deltaY"in gt?getDeltaXY(gt):getTouchXY(gt),bt=o.current.filter(function(Et){return Et.name===gt.type&&(Et.target===gt.target||gt.target===Et.shadowParent)&&deltaCompare(Et.delta,yt)})[0];if(bt&&bt.should){gt.cancelable&>.preventDefault();return}if(!bt){var xt=(it.current.shards||[]).map(extractRef).filter(Boolean).filter(function(Et){return Et.contains(gt.target)}),vt=xt.length>0?st(gt,xt[0]):!it.current.noIsolation;vt&>.cancelable&>.preventDefault()}}},[]),ct=reactExports.useCallback(function(pt,gt,yt,bt){var xt={name:pt,delta:gt,target:yt,should:bt,shadowParent:getOutermostShadowParent(yt)};o.current.push(xt),setTimeout(function(){o.current=o.current.filter(function(vt){return vt!==xt})},1)},[]),lt=reactExports.useCallback(function(pt){tt.current=getTouchXY(pt),rt.current=void 0},[]),dt=reactExports.useCallback(function(pt){ct(pt.type,getDeltaXY(pt),pt.target,st(pt,et.lockRef.current))},[]),ht=reactExports.useCallback(function(pt){ct(pt.type,getTouchXY(pt),pt.target,st(pt,et.lockRef.current))},[]);reactExports.useEffect(function(){return lockStack.push(ot),et.setCallbacks({onScrollCapture:dt,onWheelCapture:dt,onTouchMoveCapture:ht}),document.addEventListener("wheel",at,nonPassive),document.addEventListener("touchmove",at,nonPassive),document.addEventListener("touchstart",lt,nonPassive),function(){lockStack=lockStack.filter(function(pt){return pt!==ot}),document.removeEventListener("wheel",at,nonPassive),document.removeEventListener("touchmove",at,nonPassive),document.removeEventListener("touchstart",lt,nonPassive)}},[]);var mt=et.removeScrollBar,ft=et.inert;return reactExports.createElement(reactExports.Fragment,null,ft?reactExports.createElement(ot,{styles:generateStyle(nt)}):null,mt?reactExports.createElement(RemoveScrollBar,{gapMode:et.gapMode}):null)}function getOutermostShadowParent(et){for(var o=null;et!==null;)et instanceof ShadowRoot&&(o=et.host,et=et.host),et=et.parentNode;return o}const SideCar=exportSidecar(effectCar,RemoveScrollSideCar);var ReactRemoveScroll=reactExports.forwardRef(function(et,o){return reactExports.createElement(RemoveScroll,__assign({},et,{ref:o,sideCar:SideCar}))});ReactRemoveScroll.classNames=RemoveScroll.classNames;var getDefaultParent=function(et){if(typeof document>"u")return null;var o=Array.isArray(et)?et[0]:et;return o.ownerDocument.body},counterMap=new WeakMap,uncontrolledNodes=new WeakMap,markerMap={},lockCount=0,unwrapHost=function(et){return et&&(et.host||unwrapHost(et.parentNode))},correctTargets=function(et,o){return o.map(function(tt){if(et.contains(tt))return tt;var rt=unwrapHost(tt);return rt&&et.contains(rt)?rt:(console.error("aria-hidden",tt,"in not contained inside",et,". Doing nothing"),null)}).filter(function(tt){return!!tt})},applyAttributeToOthers=function(et,o,tt,rt){var nt=correctTargets(o,Array.isArray(et)?et:[et]);markerMap[tt]||(markerMap[tt]=new WeakMap);var ot=markerMap[tt],it=[],st=new Set,at=new Set(nt),ct=function(dt){!dt||st.has(dt)||(st.add(dt),ct(dt.parentNode))};nt.forEach(ct);var lt=function(dt){!dt||at.has(dt)||Array.prototype.forEach.call(dt.children,function(ht){if(st.has(ht))lt(ht);else try{var mt=ht.getAttribute(rt),ft=mt!==null&&mt!=="false",pt=(counterMap.get(ht)||0)+1,gt=(ot.get(ht)||0)+1;counterMap.set(ht,pt),ot.set(ht,gt),it.push(ht),pt===1&&ft&&uncontrolledNodes.set(ht,!0),gt===1&&ht.setAttribute(tt,"true"),ft||ht.setAttribute(rt,"true")}catch(yt){console.error("aria-hidden: cannot operate on ",ht,yt)}})};return lt(o),st.clear(),lockCount++,function(){it.forEach(function(dt){var ht=counterMap.get(dt)-1,mt=ot.get(dt)-1;counterMap.set(dt,ht),ot.set(dt,mt),ht||(uncontrolledNodes.has(dt)||dt.removeAttribute(rt),uncontrolledNodes.delete(dt)),mt||dt.removeAttribute(tt)}),lockCount--,lockCount||(counterMap=new WeakMap,counterMap=new WeakMap,uncontrolledNodes=new WeakMap,markerMap={})}},hideOthers=function(et,o,tt){tt===void 0&&(tt="data-aria-hidden");var rt=Array.from(Array.isArray(et)?et:[et]),nt=getDefaultParent(et);return nt?(rt.push.apply(rt,Array.from(nt.querySelectorAll("[aria-live]"))),applyAttributeToOthers(rt,nt,tt,"aria-hidden")):function(){return null}},DIALOG_NAME="Dialog",[createDialogContext,createDialogScope]=createContextScope(DIALOG_NAME),[DialogProvider,useDialogContext]=createDialogContext(DIALOG_NAME),Dialog$1=et=>{const{__scopeDialog:o,children:tt,open:rt,defaultOpen:nt,onOpenChange:ot,modal:it=!0}=et,st=reactExports.useRef(null),at=reactExports.useRef(null),[ct=!1,lt]=useControllableState({prop:rt,defaultProp:nt,onChange:ot});return jsxRuntimeExports.jsx(DialogProvider,{scope:o,triggerRef:st,contentRef:at,contentId:useId(),titleId:useId(),descriptionId:useId(),open:ct,onOpenChange:lt,onOpenToggle:reactExports.useCallback(()=>lt(dt=>!dt),[lt]),modal:it,children:tt})};Dialog$1.displayName=DIALOG_NAME;var TRIGGER_NAME="DialogTrigger",DialogTrigger$1=reactExports.forwardRef((et,o)=>{const{__scopeDialog:tt,...rt}=et,nt=useDialogContext(TRIGGER_NAME,tt),ot=useComposedRefs(o,nt.triggerRef);return jsxRuntimeExports.jsx(Primitive.button,{type:"button","aria-haspopup":"dialog","aria-expanded":nt.open,"aria-controls":nt.contentId,"data-state":getState(nt.open),...rt,ref:ot,onClick:composeEventHandlers(et.onClick,nt.onOpenToggle)})});DialogTrigger$1.displayName=TRIGGER_NAME;var PORTAL_NAME="DialogPortal",[PortalProvider,usePortalContext]=createDialogContext(PORTAL_NAME,{forceMount:void 0}),DialogPortal$1=et=>{const{__scopeDialog:o,forceMount:tt,children:rt,container:nt}=et,ot=useDialogContext(PORTAL_NAME,o);return jsxRuntimeExports.jsx(PortalProvider,{scope:o,forceMount:tt,children:reactExports.Children.map(rt,it=>jsxRuntimeExports.jsx(Presence,{present:tt||ot.open,children:jsxRuntimeExports.jsx(Portal$1,{asChild:!0,container:nt,children:it})}))})};DialogPortal$1.displayName=PORTAL_NAME;var OVERLAY_NAME="DialogOverlay",DialogOverlay$1=reactExports.forwardRef((et,o)=>{const tt=usePortalContext(OVERLAY_NAME,et.__scopeDialog),{forceMount:rt=tt.forceMount,...nt}=et,ot=useDialogContext(OVERLAY_NAME,et.__scopeDialog);return ot.modal?jsxRuntimeExports.jsx(Presence,{present:rt||ot.open,children:jsxRuntimeExports.jsx(DialogOverlayImpl,{...nt,ref:o})}):null});DialogOverlay$1.displayName=OVERLAY_NAME;var DialogOverlayImpl=reactExports.forwardRef((et,o)=>{const{__scopeDialog:tt,...rt}=et,nt=useDialogContext(OVERLAY_NAME,tt);return jsxRuntimeExports.jsx(ReactRemoveScroll,{as:Slot,allowPinchZoom:!0,shards:[nt.contentRef],children:jsxRuntimeExports.jsx(Primitive.div,{"data-state":getState(nt.open),...rt,ref:o,style:{pointerEvents:"auto",...rt.style}})})}),CONTENT_NAME="DialogContent",DialogContent$1=reactExports.forwardRef((et,o)=>{const tt=usePortalContext(CONTENT_NAME,et.__scopeDialog),{forceMount:rt=tt.forceMount,...nt}=et,ot=useDialogContext(CONTENT_NAME,et.__scopeDialog);return jsxRuntimeExports.jsx(Presence,{present:rt||ot.open,children:ot.modal?jsxRuntimeExports.jsx(DialogContentModal,{...nt,ref:o}):jsxRuntimeExports.jsx(DialogContentNonModal,{...nt,ref:o})})});DialogContent$1.displayName=CONTENT_NAME;var DialogContentModal=reactExports.forwardRef((et,o)=>{const tt=useDialogContext(CONTENT_NAME,et.__scopeDialog),rt=reactExports.useRef(null),nt=useComposedRefs(o,tt.contentRef,rt);return reactExports.useEffect(()=>{const ot=rt.current;if(ot)return hideOthers(ot)},[]),jsxRuntimeExports.jsx(DialogContentImpl,{...et,ref:nt,trapFocus:tt.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:composeEventHandlers(et.onCloseAutoFocus,ot=>{var it;ot.preventDefault(),(it=tt.triggerRef.current)==null||it.focus()}),onPointerDownOutside:composeEventHandlers(et.onPointerDownOutside,ot=>{const it=ot.detail.originalEvent,st=it.button===0&&it.ctrlKey===!0;(it.button===2||st)&&ot.preventDefault()}),onFocusOutside:composeEventHandlers(et.onFocusOutside,ot=>ot.preventDefault())})}),DialogContentNonModal=reactExports.forwardRef((et,o)=>{const tt=useDialogContext(CONTENT_NAME,et.__scopeDialog),rt=reactExports.useRef(!1),nt=reactExports.useRef(!1);return jsxRuntimeExports.jsx(DialogContentImpl,{...et,ref:o,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:ot=>{var it,st;(it=et.onCloseAutoFocus)==null||it.call(et,ot),ot.defaultPrevented||(rt.current||(st=tt.triggerRef.current)==null||st.focus(),ot.preventDefault()),rt.current=!1,nt.current=!1},onInteractOutside:ot=>{var at,ct;(at=et.onInteractOutside)==null||at.call(et,ot),ot.defaultPrevented||(rt.current=!0,ot.detail.originalEvent.type==="pointerdown"&&(nt.current=!0));const it=ot.target;((ct=tt.triggerRef.current)==null?void 0:ct.contains(it))&&ot.preventDefault(),ot.detail.originalEvent.type==="focusin"&&nt.current&&ot.preventDefault()}})}),DialogContentImpl=reactExports.forwardRef((et,o)=>{const{__scopeDialog:tt,trapFocus:rt,onOpenAutoFocus:nt,onCloseAutoFocus:ot,...it}=et,st=useDialogContext(CONTENT_NAME,tt),at=reactExports.useRef(null),ct=useComposedRefs(o,at);return useFocusGuards(),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(FocusScope,{asChild:!0,loop:!0,trapped:rt,onMountAutoFocus:nt,onUnmountAutoFocus:ot,children:jsxRuntimeExports.jsx(DismissableLayer,{role:"dialog",id:st.contentId,"aria-describedby":st.descriptionId,"aria-labelledby":st.titleId,"data-state":getState(st.open),...it,ref:ct,onDismiss:()=>st.onOpenChange(!1)})}),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(TitleWarning,{titleId:st.titleId}),jsxRuntimeExports.jsx(DescriptionWarning,{contentRef:at,descriptionId:st.descriptionId})]})]})}),TITLE_NAME="DialogTitle",DialogTitle$1=reactExports.forwardRef((et,o)=>{const{__scopeDialog:tt,...rt}=et,nt=useDialogContext(TITLE_NAME,tt);return jsxRuntimeExports.jsx(Primitive.h2,{id:nt.titleId,...rt,ref:o})});DialogTitle$1.displayName=TITLE_NAME;var DESCRIPTION_NAME="DialogDescription",DialogDescription$1=reactExports.forwardRef((et,o)=>{const{__scopeDialog:tt,...rt}=et,nt=useDialogContext(DESCRIPTION_NAME,tt);return jsxRuntimeExports.jsx(Primitive.p,{id:nt.descriptionId,...rt,ref:o})});DialogDescription$1.displayName=DESCRIPTION_NAME;var CLOSE_NAME="DialogClose",DialogClose=reactExports.forwardRef((et,o)=>{const{__scopeDialog:tt,...rt}=et,nt=useDialogContext(CLOSE_NAME,tt);return jsxRuntimeExports.jsx(Primitive.button,{type:"button",...rt,ref:o,onClick:composeEventHandlers(et.onClick,()=>nt.onOpenChange(!1))})});DialogClose.displayName=CLOSE_NAME;function getState(et){return et?"open":"closed"}var TITLE_WARNING_NAME="DialogTitleWarning",[WarningProvider,useWarningContext]=createContext2(TITLE_WARNING_NAME,{contentName:CONTENT_NAME,titleName:TITLE_NAME,docsSlug:"dialog"}),TitleWarning=({titleId:et})=>{const o=useWarningContext(TITLE_WARNING_NAME),tt=`\`${o.contentName}\` requires a \`${o.titleName}\` for the component to be accessible for screen reader users. + +If you want to hide the \`${o.titleName}\`, you can wrap it with our VisuallyHidden component. + +For more information, see https://radix-ui.com/primitives/docs/components/${o.docsSlug}`;return reactExports.useEffect(()=>{et&&(document.getElementById(et)||console.error(tt))},[tt,et]),null},DESCRIPTION_WARNING_NAME="DialogDescriptionWarning",DescriptionWarning=({contentRef:et,descriptionId:o})=>{const rt=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${useWarningContext(DESCRIPTION_WARNING_NAME).contentName}}.`;return reactExports.useEffect(()=>{var ot;const nt=(ot=et.current)==null?void 0:ot.getAttribute("aria-describedby");o&&nt&&(document.getElementById(o)||console.warn(rt))},[rt,et,o]),null},Root$2=Dialog$1,Trigger=DialogTrigger$1,Portal=DialogPortal$1,Overlay=DialogOverlay$1,Content=DialogContent$1,Title=DialogTitle$1,Description=DialogDescription$1,Close=DialogClose;function _objectWithoutPropertiesLoose(et,o){if(et==null)return{};var tt={},rt=Object.keys(et),nt,ot;for(ot=0;ot=0)&&(tt[nt]=et[nt]);return tt}var _excluded$1r=["color"],Cross2Icon=reactExports.forwardRef(function(et,o){var tt=et.color,rt=tt===void 0?"currentColor":tt,nt=_objectWithoutPropertiesLoose(et,_excluded$1r);return reactExports.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},nt,{ref:o}),reactExports.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:rt,fillRule:"evenodd",clipRule:"evenodd"}))});const Dialog=Root$2,DialogTrigger=Trigger,DialogPortal=Portal,DialogOverlay=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx(Overlay,{ref:tt,className:cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",et),...o}));DialogOverlay.displayName=Overlay.displayName;const DialogContent=reactExports.forwardRef(({className:et,children:o,...tt},rt)=>jsxRuntimeExports.jsxs(DialogPortal,{children:[jsxRuntimeExports.jsx(DialogOverlay,{}),jsxRuntimeExports.jsxs(Content,{ref:rt,className:cn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",et),...tt,children:[o,jsxRuntimeExports.jsxs(Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[jsxRuntimeExports.jsx(Cross2Icon,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));DialogContent.displayName=Content.displayName;const DialogHeader=({className:et,...o})=>jsxRuntimeExports.jsx("div",{className:cn("flex flex-col space-y-1.5 text-center sm:text-left",et),...o});DialogHeader.displayName="DialogHeader";const DialogFooter=({className:et,...o})=>jsxRuntimeExports.jsx("div",{className:cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",et),...o});DialogFooter.displayName="DialogFooter";const DialogTitle=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx(Title,{ref:tt,className:cn("text-lg font-semibold leading-none tracking-tight",et),...o}));DialogTitle.displayName=Title.displayName;const DialogDescription=reactExports.forwardRef(({className:et,...o},tt)=>jsxRuntimeExports.jsx(Description,{ref:tt,className:cn("text-sm text-muted-foreground",et),...o}));DialogDescription.displayName=Description.displayName;var __defProp=Object.defineProperty,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(et,o,tt)=>o in et?__defProp(et,o,{enumerable:!0,configurable:!0,writable:!0,value:tt}):et[o]=tt,__spreadValues=(et,o)=>{for(var tt in o||(o={}))__hasOwnProp.call(o,tt)&&__defNormalProp(et,tt,o[tt]);if(__getOwnPropSymbols)for(var tt of __getOwnPropSymbols(o))__propIsEnum.call(o,tt)&&__defNormalProp(et,tt,o[tt]);return et},__objRest=(et,o)=>{var tt={};for(var rt in et)__hasOwnProp.call(et,rt)&&o.indexOf(rt)<0&&(tt[rt]=et[rt]);if(et!=null&&__getOwnPropSymbols)for(var rt of __getOwnPropSymbols(et))o.indexOf(rt)<0&&__propIsEnum.call(et,rt)&&(tt[rt]=et[rt]);return tt};/** + * @license QR Code generator library (TypeScript) + * Copyright (c) Project Nayuki. + * SPDX-License-Identifier: MIT + */var qrcodegen;(et=>{const o=class Er{constructor(at,ct,lt,dt){if(this.version=at,this.errorCorrectionLevel=ct,this.modules=[],this.isFunction=[],atEr.MAX_VERSION)throw new RangeError("Version value out of range");if(dt<-1||dt>7)throw new RangeError("Mask value out of range");this.size=at*4+17;let ht=[];for(let ft=0;ft7)throw new RangeError("Invalid value");let ft,pt;for(ft=lt;;ft++){const xt=Er.getNumDataCodewords(ft,ct)*8,vt=it.getTotalBits(at,ft);if(vt<=xt){pt=vt;break}if(ft>=dt)throw new RangeError("Data too long")}for(const xt of[Er.Ecc.MEDIUM,Er.Ecc.QUARTILE,Er.Ecc.HIGH])mt&&pt<=Er.getNumDataCodewords(ft,xt)*8&&(ct=xt);let gt=[];for(const xt of at){tt(xt.mode.modeBits,4,gt),tt(xt.numChars,xt.mode.numCharCountBits(ft),gt);for(const vt of xt.getData())gt.push(vt)}nt(gt.length==pt);const yt=Er.getNumDataCodewords(ft,ct)*8;nt(gt.length<=yt),tt(0,Math.min(4,yt-gt.length),gt),tt(0,(8-gt.length%8)%8,gt),nt(gt.length%8==0);for(let xt=236;gt.lengthbt[vt>>>3]|=xt<<7-(vt&7)),new Er(ft,ct,bt,ht)}getModule(at,ct){return 0<=at&&at>>9)*1335;const dt=(ct<<10|lt)^21522;nt(dt>>>15==0);for(let ht=0;ht<=5;ht++)this.setFunctionModule(8,ht,rt(dt,ht));this.setFunctionModule(8,7,rt(dt,6)),this.setFunctionModule(8,8,rt(dt,7)),this.setFunctionModule(7,8,rt(dt,8));for(let ht=9;ht<15;ht++)this.setFunctionModule(14-ht,8,rt(dt,ht));for(let ht=0;ht<8;ht++)this.setFunctionModule(this.size-1-ht,8,rt(dt,ht));for(let ht=8;ht<15;ht++)this.setFunctionModule(8,this.size-15+ht,rt(dt,ht));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let at=this.version;for(let lt=0;lt<12;lt++)at=at<<1^(at>>>11)*7973;const ct=this.version<<12|at;nt(ct>>>18==0);for(let lt=0;lt<18;lt++){const dt=rt(ct,lt),ht=this.size-11+lt%3,mt=Math.floor(lt/3);this.setFunctionModule(ht,mt,dt),this.setFunctionModule(mt,ht,dt)}}drawFinderPattern(at,ct){for(let lt=-4;lt<=4;lt++)for(let dt=-4;dt<=4;dt++){const ht=Math.max(Math.abs(dt),Math.abs(lt)),mt=at+dt,ft=ct+lt;0<=mt&&mt{(xt!=pt-ht||Et>=ft)&&bt.push(vt[xt])});return nt(bt.length==mt),bt}drawCodewords(at){if(at.length!=Math.floor(Er.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let ct=0;for(let lt=this.size-1;lt>=1;lt-=2){lt==6&&(lt=5);for(let dt=0;dt>>3],7-(ct&7)),ct++)}}nt(ct==at.length*8)}applyMask(at){if(at<0||at>7)throw new RangeError("Mask value out of range");for(let ct=0;ct5&&at++):(this.finderPenaltyAddHistory(ft,pt),mt||(at+=this.finderPenaltyCountPatterns(pt)*Er.PENALTY_N3),mt=this.modules[ht][gt],ft=1);at+=this.finderPenaltyTerminateAndCount(mt,ft,pt)*Er.PENALTY_N3}for(let ht=0;ht5&&at++):(this.finderPenaltyAddHistory(ft,pt),mt||(at+=this.finderPenaltyCountPatterns(pt)*Er.PENALTY_N3),mt=this.modules[gt][ht],ft=1);at+=this.finderPenaltyTerminateAndCount(mt,ft,pt)*Er.PENALTY_N3}for(let ht=0;htmt+(ft?1:0),ct);const lt=this.size*this.size,dt=Math.ceil(Math.abs(ct*20-lt*10)/lt)-1;return nt(0<=dt&&dt<=9),at+=dt*Er.PENALTY_N4,nt(0<=at&&at<=2568888),at}getAlignmentPatternPositions(){if(this.version==1)return[];{const at=Math.floor(this.version/7)+2,ct=this.version==32?26:Math.ceil((this.version*4+4)/(at*2-2))*2;let lt=[6];for(let dt=this.size-7;lt.lengthEr.MAX_VERSION)throw new RangeError("Version number out of range");let ct=(16*at+128)*at+64;if(at>=2){const lt=Math.floor(at/7)+2;ct-=(25*lt-10)*lt-55,at>=7&&(ct-=36)}return nt(208<=ct&&ct<=29648),ct}static getNumDataCodewords(at,ct){return Math.floor(Er.getNumRawDataModules(at)/8)-Er.ECC_CODEWORDS_PER_BLOCK[ct.ordinal][at]*Er.NUM_ERROR_CORRECTION_BLOCKS[ct.ordinal][at]}static reedSolomonComputeDivisor(at){if(at<1||at>255)throw new RangeError("Degree out of range");let ct=[];for(let dt=0;dt0);for(const dt of at){const ht=dt^lt.shift();lt.push(0),ct.forEach((mt,ft)=>lt[ft]^=Er.reedSolomonMultiply(mt,ht))}return lt}static reedSolomonMultiply(at,ct){if(at>>>8||ct>>>8)throw new RangeError("Byte out of range");let lt=0;for(let dt=7;dt>=0;dt--)lt=lt<<1^(lt>>>7)*285,lt^=(ct>>>dt&1)*at;return nt(lt>>>8==0),lt}finderPenaltyCountPatterns(at){const ct=at[1];nt(ct<=this.size*3);const lt=ct>0&&at[2]==ct&&at[3]==ct*3&&at[4]==ct&&at[5]==ct;return(lt&&at[0]>=ct*4&&at[6]>=ct?1:0)+(lt&&at[6]>=ct*4&&at[0]>=ct?1:0)}finderPenaltyTerminateAndCount(at,ct,lt){return at&&(this.finderPenaltyAddHistory(ct,lt),ct=0),ct+=this.size,this.finderPenaltyAddHistory(ct,lt),this.finderPenaltyCountPatterns(lt)}finderPenaltyAddHistory(at,ct){ct[0]==0&&(at+=this.size),ct.pop(),ct.unshift(at)}};o.MIN_VERSION=1,o.MAX_VERSION=40,o.PENALTY_N1=3,o.PENALTY_N2=3,o.PENALTY_N3=40,o.PENALTY_N4=10,o.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],o.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],et.QrCode=o;function tt(st,at,ct){if(at<0||at>31||st>>>at)throw new RangeError("Value out of range");for(let lt=at-1;lt>=0;lt--)ct.push(st>>>lt&1)}function rt(st,at){return(st>>>at&1)!=0}function nt(st){if(!st)throw new Error("Assertion error")}const ot=class Tr{constructor(at,ct,lt){if(this.mode=at,this.numChars=ct,this.bitData=lt,ct<0)throw new RangeError("Invalid argument");this.bitData=lt.slice()}static makeBytes(at){let ct=[];for(const lt of at)tt(lt,8,ct);return new Tr(Tr.Mode.BYTE,at.length,ct)}static makeNumeric(at){if(!Tr.isNumeric(at))throw new RangeError("String contains non-numeric characters");let ct=[];for(let lt=0;lt=1<{(o=>{const tt=class{constructor(nt,ot){this.ordinal=nt,this.formatBits=ot}};tt.LOW=new tt(0,1),tt.MEDIUM=new tt(1,0),tt.QUARTILE=new tt(2,3),tt.HIGH=new tt(3,2),o.Ecc=tt})(et.QrCode||(et.QrCode={}))})(qrcodegen||(qrcodegen={}));(et=>{(o=>{const tt=class{constructor(nt,ot){this.modeBits=nt,this.numBitsCharCount=ot}numCharCountBits(nt){return this.numBitsCharCount[Math.floor((nt+7)/17)]}};tt.NUMERIC=new tt(1,[10,12,14]),tt.ALPHANUMERIC=new tt(2,[9,11,13]),tt.BYTE=new tt(4,[8,16,16]),tt.KANJI=new tt(8,[8,10,12]),tt.ECI=new tt(7,[0,0,0]),o.Mode=tt})(et.QrSegment||(et.QrSegment={}))})(qrcodegen||(qrcodegen={}));var qrcodegen_default=qrcodegen;/** + * @license qrcode.react + * Copyright (c) Paul O'Shannessy + * SPDX-License-Identifier: ISC + */var ERROR_LEVEL_MAP={L:qrcodegen_default.QrCode.Ecc.LOW,M:qrcodegen_default.QrCode.Ecc.MEDIUM,Q:qrcodegen_default.QrCode.Ecc.QUARTILE,H:qrcodegen_default.QrCode.Ecc.HIGH},DEFAULT_SIZE=128,DEFAULT_LEVEL="L",DEFAULT_BGCOLOR="#FFFFFF",DEFAULT_FGCOLOR="#000000",DEFAULT_INCLUDEMARGIN=!1,DEFAULT_MINVERSION=1,SPEC_MARGIN_SIZE=4,DEFAULT_MARGIN_SIZE=0,DEFAULT_IMG_SCALE=.1;function generatePath(et,o=0){const tt=[];return et.forEach(function(rt,nt){let ot=null;rt.forEach(function(it,st){if(!it&&ot!==null){tt.push(`M${ot+o} ${nt+o}h${st-ot}v1H${ot+o}z`),ot=null;return}if(st===rt.length-1){if(!it)return;ot===null?tt.push(`M${st+o},${nt+o} h1v1H${st+o}z`):tt.push(`M${ot+o},${nt+o} h${st+1-ot}v1H${ot+o}z`);return}it&&ot===null&&(ot=st)})}),tt.join("")}function excavateModules(et,o){return et.slice().map((tt,rt)=>rt=o.y+o.h?tt:tt.map((nt,ot)=>ot=o.x+o.w?nt:!1))}function getImageSettings(et,o,tt,rt){if(rt==null)return null;const nt=et.length+tt*2,ot=Math.floor(o*DEFAULT_IMG_SCALE),it=nt/o,st=(rt.width||ot)*it,at=(rt.height||ot)*it,ct=rt.x==null?et.length/2-st/2:rt.x*it,lt=rt.y==null?et.length/2-at/2:rt.y*it,dt=rt.opacity==null?1:rt.opacity;let ht=null;if(rt.excavate){let ft=Math.floor(ct),pt=Math.floor(lt),gt=Math.ceil(st+ct-ft),yt=Math.ceil(at+lt-pt);ht={x:ft,y:pt,w:gt,h:yt}}const mt=rt.crossOrigin;return{x:ct,y:lt,h:at,w:st,excavation:ht,opacity:dt,crossOrigin:mt}}function getMarginSize(et,o){return o!=null?Math.max(Math.floor(o),0):et?SPEC_MARGIN_SIZE:DEFAULT_MARGIN_SIZE}function useQRCode({value:et,level:o,minVersion:tt,includeMargin:rt,marginSize:nt,imageSettings:ot,size:it}){let st=React.useMemo(()=>{const ht=qrcodegen_default.QrSegment.makeSegments(et);return qrcodegen_default.QrCode.encodeSegments(ht,ERROR_LEVEL_MAP[o],tt)},[et,o,tt]);const{cells:at,margin:ct,numCells:lt,calculatedImageSettings:dt}=React.useMemo(()=>{let ht=st.getModules();const mt=getMarginSize(rt,nt),ft=ht.length+mt*2,pt=getImageSettings(ht,it,mt,ot);return{cells:ht,margin:mt,numCells:ft,calculatedImageSettings:pt}},[st,it,ot,rt,nt]);return{qrcode:st,margin:ct,cells:at,numCells:lt,calculatedImageSettings:dt}}var SUPPORTS_PATH2D=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),QRCodeCanvas=React.forwardRef(function(o,tt){const rt=o,{value:nt,size:ot=DEFAULT_SIZE,level:it=DEFAULT_LEVEL,bgColor:st=DEFAULT_BGCOLOR,fgColor:at=DEFAULT_FGCOLOR,includeMargin:ct=DEFAULT_INCLUDEMARGIN,minVersion:lt=DEFAULT_MINVERSION,marginSize:dt,imageSettings:ht}=rt,ft=__objRest(rt,["value","size","level","bgColor","fgColor","includeMargin","minVersion","marginSize","imageSettings"]),{style:pt}=ft,gt=__objRest(ft,["style"]),yt=ht==null?void 0:ht.src,bt=React.useRef(null),xt=React.useRef(null),vt=React.useCallback(Yt=>{bt.current=Yt,typeof tt=="function"?tt(Yt):tt&&(tt.current=Yt)},[tt]),[Et,Ct]=React.useState(!1),{margin:St,cells:At,numCells:kt,calculatedImageSettings:It}=useQRCode({value:nt,level:it,minVersion:lt,includeMargin:ct,marginSize:dt,imageSettings:ht,size:ot});React.useEffect(()=>{if(bt.current!=null){const Yt=bt.current,Ft=Yt.getContext("2d");if(!Ft)return;let Ht=At;const Qt=xt.current,Vt=It!=null&&Qt!==null&&Qt.complete&&Qt.naturalHeight!==0&&Qt.naturalWidth!==0;Vt&&It.excavation!=null&&(Ht=excavateModules(At,It.excavation));const Bt=window.devicePixelRatio||1;Yt.height=Yt.width=ot*Bt;const Wt=ot/kt*Bt;Ft.scale(Wt,Wt),Ft.fillStyle=st,Ft.fillRect(0,0,kt,kt),Ft.fillStyle=at,SUPPORTS_PATH2D?Ft.fill(new Path2D(generatePath(Ht,St))):At.forEach(function(jt,Xt){jt.forEach(function(Kt,Pt){Kt&&Ft.fillRect(Pt+St,Xt+St,1,1)})}),It&&(Ft.globalAlpha=It.opacity),Vt&&Ft.drawImage(Qt,It.x+St,It.y+St,It.w,It.h)}}),React.useEffect(()=>{Ct(!1)},[yt]);const Ot=__spreadValues({height:ot,width:ot},pt);let Nt=null;return yt!=null&&(Nt=React.createElement("img",{src:yt,key:yt,style:{display:"none"},onLoad:()=>{Ct(!0)},ref:xt,crossOrigin:It==null?void 0:It.crossOrigin})),React.createElement(React.Fragment,null,React.createElement("canvas",__spreadValues({style:Ot,height:ot,width:ot,ref:vt,role:"img"},gt)),Nt)});QRCodeCanvas.displayName="QRCodeCanvas";var QRCodeSVG=React.forwardRef(function(o,tt){const rt=o,{value:nt,size:ot=DEFAULT_SIZE,level:it=DEFAULT_LEVEL,bgColor:st=DEFAULT_BGCOLOR,fgColor:at=DEFAULT_FGCOLOR,includeMargin:ct=DEFAULT_INCLUDEMARGIN,minVersion:lt=DEFAULT_MINVERSION,title:dt,marginSize:ht,imageSettings:mt}=rt,ft=__objRest(rt,["value","size","level","bgColor","fgColor","includeMargin","minVersion","title","marginSize","imageSettings"]),{margin:pt,cells:gt,numCells:yt,calculatedImageSettings:bt}=useQRCode({value:nt,level:it,minVersion:lt,includeMargin:ct,marginSize:ht,imageSettings:mt,size:ot});let xt=gt,vt=null;mt!=null&&bt!=null&&(bt.excavation!=null&&(xt=excavateModules(gt,bt.excavation)),vt=React.createElement("image",{href:mt.src,height:bt.h,width:bt.w,x:bt.x+pt,y:bt.y+pt,preserveAspectRatio:"none",opacity:bt.opacity,crossOrigin:bt.crossOrigin}));const Et=generatePath(xt,pt);return React.createElement("svg",__spreadValues({height:ot,width:ot,viewBox:`0 0 ${yt} ${yt}`,ref:tt,role:"img"},ft),!!dt&&React.createElement("title",null,dt),React.createElement("path",{fill:st,d:`M0,0 h${yt}v${yt}H0z`,shapeRendering:"crispEdges"}),React.createElement("path",{fill:at,d:Et,shapeRendering:"crispEdges"}),vt)});QRCodeSVG.displayName="QRCodeSVG";const QRCode=({text:et,width:o=256,height:tt=256})=>{const[rt,nt]=reactExports.useState(!1),ot=async()=>{await navigator.clipboard.writeText(et),nt(!0),setTimeout(()=>nt(!1),2e3)};return jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[jsxRuntimeExports.jsx(QRCodeSVG,{value:et,size:Math.min(o,tt)}),jsxRuntimeExports.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntimeExports.jsx("input",{type:"text",value:et,readOnly:!0,className:"flex-1 px-3 py-2 text-sm border rounded-md bg-muted"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"icon",onClick:ot,children:rt?jsxRuntimeExports.jsx(Check,{className:"h-4 w-4"}):jsxRuntimeExports.jsx(Copy,{className:"h-4 w-4"})})]})]})};var byteToHex=[];for(var i=0;i<256;++i)byteToHex.push((i+256).toString(16).slice(1));function unsafeStringify(et,o=0){return(byteToHex[et[o+0]]+byteToHex[et[o+1]]+byteToHex[et[o+2]]+byteToHex[et[o+3]]+"-"+byteToHex[et[o+4]]+byteToHex[et[o+5]]+"-"+byteToHex[et[o+6]]+byteToHex[et[o+7]]+"-"+byteToHex[et[o+8]]+byteToHex[et[o+9]]+"-"+byteToHex[et[o+10]]+byteToHex[et[o+11]]+byteToHex[et[o+12]]+byteToHex[et[o+13]]+byteToHex[et[o+14]]+byteToHex[et[o+15]]).toLowerCase()}var getRandomValues,rnds8=new Uint8Array(16);function rng(){if(!getRandomValues&&(getRandomValues=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!getRandomValues))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}var randomUUID=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const native={randomUUID};function v4(et,o,tt){if(native.randomUUID&&!o&&!et)return native.randomUUID();et=et||{};var rt=et.random||(et.rng||rng)();return rt[6]=rt[6]&15|64,rt[8]=rt[8]&63|128,unsafeStringify(rt)}var src={exports:{}},indexLight={exports:{}},indexMinimal={},minimal={},aspromise=asPromise$1;function asPromise$1(et,o){for(var tt=new Array(arguments.length-1),rt=0,nt=2,ot=!0;nt1&&st.charAt(at)==="=";)++ct;return Math.ceil(st.length*3)/4-ct};for(var tt=new Array(64),rt=new Array(123),nt=0;nt<64;)rt[tt[nt]=nt<26?nt+65:nt<52?nt+71:nt<62?nt-4:nt-59|43]=nt++;o.encode=function(st,at,ct){for(var lt=null,dt=[],ht=0,mt=0,ft;at>2],ft=(pt&3)<<4,mt=1;break;case 1:dt[ht++]=tt[ft|pt>>4],ft=(pt&15)<<2,mt=2;break;case 2:dt[ht++]=tt[ft|pt>>6],dt[ht++]=tt[pt&63],mt=0;break}ht>8191&&((lt||(lt=[])).push(String.fromCharCode.apply(String,dt)),ht=0)}return mt&&(dt[ht++]=tt[ft],dt[ht++]=61,mt===1&&(dt[ht++]=61)),lt?(ht&<.push(String.fromCharCode.apply(String,dt.slice(0,ht))),lt.join("")):String.fromCharCode.apply(String,dt.slice(0,ht))};var ot="invalid encoding";o.decode=function(st,at,ct){for(var lt=ct,dt=0,ht,mt=0;mt1)break;if((ft=rt[ft])===void 0)throw Error(ot);switch(dt){case 0:ht=ft,dt=1;break;case 1:at[ct++]=ht<<2|(ft&48)>>4,ht=ft,dt=2;break;case 2:at[ct++]=(ht&15)<<4|(ft&60)>>2,ht=ft,dt=3;break;case 3:at[ct++]=(ht&3)<<6|ft,dt=0;break}}if(dt===1)throw Error(ot);return ct-lt},o.test=function(st){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(st)}})(base64$1);var eventemitter=EventEmitter;function EventEmitter(){this._listeners={}}EventEmitter.prototype.on=function(o,tt,rt){return(this._listeners[o]||(this._listeners[o]=[])).push({fn:tt,ctx:rt||this}),this};EventEmitter.prototype.off=function(o,tt){if(o===void 0)this._listeners={};else if(tt===void 0)this._listeners[o]=[];else for(var rt=this._listeners[o],nt=0;nt0?0:2147483648,ot,it);else if(isNaN(nt))rt(2143289344,ot,it);else if(nt>34028234663852886e22)rt((st<<31|2139095040)>>>0,ot,it);else if(nt<11754943508222875e-54)rt((st<<31|Math.round(nt/1401298464324817e-60))>>>0,ot,it);else{var at=Math.floor(Math.log(nt)/Math.LN2),ct=Math.round(nt*Math.pow(2,-at)*8388608)&8388607;rt((st<<31|at+127<<23|ct)>>>0,ot,it)}}et.writeFloatLE=o.bind(null,writeUintLE),et.writeFloatBE=o.bind(null,writeUintBE);function tt(rt,nt,ot){var it=rt(nt,ot),st=(it>>31)*2+1,at=it>>>23&255,ct=it&8388607;return at===255?ct?NaN:st*(1/0):at===0?st*1401298464324817e-60*ct:st*Math.pow(2,at-150)*(ct+8388608)}et.readFloatLE=tt.bind(null,readUintLE),et.readFloatBE=tt.bind(null,readUintBE)}(),typeof Float64Array<"u"?function(){var o=new Float64Array([-0]),tt=new Uint8Array(o.buffer),rt=tt[7]===128;function nt(at,ct,lt){o[0]=at,ct[lt]=tt[0],ct[lt+1]=tt[1],ct[lt+2]=tt[2],ct[lt+3]=tt[3],ct[lt+4]=tt[4],ct[lt+5]=tt[5],ct[lt+6]=tt[6],ct[lt+7]=tt[7]}function ot(at,ct,lt){o[0]=at,ct[lt]=tt[7],ct[lt+1]=tt[6],ct[lt+2]=tt[5],ct[lt+3]=tt[4],ct[lt+4]=tt[3],ct[lt+5]=tt[2],ct[lt+6]=tt[1],ct[lt+7]=tt[0]}et.writeDoubleLE=rt?nt:ot,et.writeDoubleBE=rt?ot:nt;function it(at,ct){return tt[0]=at[ct],tt[1]=at[ct+1],tt[2]=at[ct+2],tt[3]=at[ct+3],tt[4]=at[ct+4],tt[5]=at[ct+5],tt[6]=at[ct+6],tt[7]=at[ct+7],o[0]}function st(at,ct){return tt[7]=at[ct],tt[6]=at[ct+1],tt[5]=at[ct+2],tt[4]=at[ct+3],tt[3]=at[ct+4],tt[2]=at[ct+5],tt[1]=at[ct+6],tt[0]=at[ct+7],o[0]}et.readDoubleLE=rt?it:st,et.readDoubleBE=rt?st:it}():function(){function o(rt,nt,ot,it,st,at){var ct=it<0?1:0;if(ct&&(it=-it),it===0)rt(0,st,at+nt),rt(1/it>0?0:2147483648,st,at+ot);else if(isNaN(it))rt(0,st,at+nt),rt(2146959360,st,at+ot);else if(it>17976931348623157e292)rt(0,st,at+nt),rt((ct<<31|2146435072)>>>0,st,at+ot);else{var lt;if(it<22250738585072014e-324)lt=it/5e-324,rt(lt>>>0,st,at+nt),rt((ct<<31|lt/4294967296)>>>0,st,at+ot);else{var dt=Math.floor(Math.log(it)/Math.LN2);dt===1024&&(dt=1023),lt=it*Math.pow(2,-dt),rt(lt*4503599627370496>>>0,st,at+nt),rt((ct<<31|dt+1023<<20|lt*1048576&1048575)>>>0,st,at+ot)}}}et.writeDoubleLE=o.bind(null,writeUintLE,0,4),et.writeDoubleBE=o.bind(null,writeUintBE,4,0);function tt(rt,nt,ot,it,st){var at=rt(it,st+nt),ct=rt(it,st+ot),lt=(ct>>31)*2+1,dt=ct>>>20&2047,ht=4294967296*(ct&1048575)+at;return dt===2047?ht?NaN:lt*(1/0):dt===0?lt*5e-324*ht:lt*Math.pow(2,dt-1075)*(ht+4503599627370496)}et.readDoubleLE=tt.bind(null,readUintLE,0,4),et.readDoubleBE=tt.bind(null,readUintBE,4,0)}(),et}function writeUintLE(et,o,tt){o[tt]=et&255,o[tt+1]=et>>>8&255,o[tt+2]=et>>>16&255,o[tt+3]=et>>>24}function writeUintBE(et,o,tt){o[tt]=et>>>24,o[tt+1]=et>>>16&255,o[tt+2]=et>>>8&255,o[tt+3]=et&255}function readUintLE(et,o){return(et[o]|et[o+1]<<8|et[o+2]<<16|et[o+3]<<24)>>>0}function readUintBE(et,o){return(et[o]<<24|et[o+1]<<16|et[o+2]<<8|et[o+3])>>>0}var inquire_1=inquire$1;function inquire$1(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(et){}return null}var utf8$2={};(function(et){var o=et;o.length=function(rt){for(var nt=0,ot=0,it=0;it191&<<224?at[ct++]=(lt&31)<<6|rt[nt++]&63:lt>239&<<365?(lt=((lt&7)<<18|(rt[nt++]&63)<<12|(rt[nt++]&63)<<6|rt[nt++]&63)-65536,at[ct++]=55296+(lt>>10),at[ct++]=56320+(lt&1023)):at[ct++]=(lt&15)<<12|(rt[nt++]&63)<<6|rt[nt++]&63,ct>8191&&((st||(st=[])).push(String.fromCharCode.apply(String,at)),ct=0);return st?(ct&&st.push(String.fromCharCode.apply(String,at.slice(0,ct))),st.join("")):String.fromCharCode.apply(String,at.slice(0,ct))},o.write=function(rt,nt,ot){for(var it=ot,st,at,ct=0;ct>6|192,nt[ot++]=st&63|128):(st&64512)===55296&&((at=rt.charCodeAt(ct+1))&64512)===56320?(st=65536+((st&1023)<<10)+(at&1023),++ct,nt[ot++]=st>>18|240,nt[ot++]=st>>12&63|128,nt[ot++]=st>>6&63|128,nt[ot++]=st&63|128):(nt[ot++]=st>>12|224,nt[ot++]=st>>6&63|128,nt[ot++]=st&63|128);return ot-it}})(utf8$2);var pool_1=pool;function pool(et,o,tt){var rt=tt||8192,nt=rt>>>1,ot=null,it=rt;return function(at){if(at<1||at>nt)return et(at);it+at>rt&&(ot=et(rt),it=0);var ct=o.call(ot,it,it+=at);return it&7&&(it=(it|7)+1),ct}}var longbits,hasRequiredLongbits;function requireLongbits(){if(hasRequiredLongbits)return longbits;hasRequiredLongbits=1,longbits=o;var et=requireMinimal();function o(ot,it){this.lo=ot>>>0,this.hi=it>>>0}var tt=o.zero=new o(0,0);tt.toNumber=function(){return 0},tt.zzEncode=tt.zzDecode=function(){return this},tt.length=function(){return 1};var rt=o.zeroHash="\0\0\0\0\0\0\0\0";o.fromNumber=function(it){if(it===0)return tt;var st=it<0;st&&(it=-it);var at=it>>>0,ct=(it-at)/4294967296>>>0;return st&&(ct=~ct>>>0,at=~at>>>0,++at>4294967295&&(at=0,++ct>4294967295&&(ct=0))),new o(at,ct)},o.from=function(it){if(typeof it=="number")return o.fromNumber(it);if(et.isString(it))if(et.Long)it=et.Long.fromString(it);else return o.fromNumber(parseInt(it,10));return it.low||it.high?new o(it.low>>>0,it.high>>>0):tt},o.prototype.toNumber=function(it){if(!it&&this.hi>>>31){var st=~this.lo+1>>>0,at=~this.hi>>>0;return st||(at=at+1>>>0),-(st+at*4294967296)}return this.lo+this.hi*4294967296},o.prototype.toLong=function(it){return et.Long?new et.Long(this.lo|0,this.hi|0,!!it):{low:this.lo|0,high:this.hi|0,unsigned:!!it}};var nt=String.prototype.charCodeAt;return o.fromHash=function(it){return it===rt?tt:new o((nt.call(it,0)|nt.call(it,1)<<8|nt.call(it,2)<<16|nt.call(it,3)<<24)>>>0,(nt.call(it,4)|nt.call(it,5)<<8|nt.call(it,6)<<16|nt.call(it,7)<<24)>>>0)},o.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},o.prototype.zzEncode=function(){var it=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^it)>>>0,this.lo=(this.lo<<1^it)>>>0,this},o.prototype.zzDecode=function(){var it=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^it)>>>0,this.hi=(this.hi>>>1^it)>>>0,this},o.prototype.length=function(){var it=this.lo,st=(this.lo>>>28|this.hi<<4)>>>0,at=this.hi>>>24;return at===0?st===0?it<16384?it<128?1:2:it<2097152?3:4:st<16384?st<128?5:6:st<2097152?7:8:at<128?9:10},longbits}var hasRequiredMinimal;function requireMinimal(){return hasRequiredMinimal||(hasRequiredMinimal=1,function(et){var o=et;o.asPromise=aspromise,o.base64=base64$1,o.EventEmitter=eventemitter,o.float=float,o.inquire=inquire_1,o.utf8=utf8$2,o.pool=pool_1,o.LongBits=requireLongbits(),o.isNode=!!(typeof commonjsGlobal<"u"&&commonjsGlobal&&commonjsGlobal.process&&commonjsGlobal.process.versions&&commonjsGlobal.process.versions.node),o.global=o.isNode&&commonjsGlobal||typeof window<"u"&&window||typeof self<"u"&&self||commonjsGlobal,o.emptyArray=Object.freeze?Object.freeze([]):[],o.emptyObject=Object.freeze?Object.freeze({}):{},o.isInteger=Number.isInteger||function(ot){return typeof ot=="number"&&isFinite(ot)&&Math.floor(ot)===ot},o.isString=function(ot){return typeof ot=="string"||ot instanceof String},o.isObject=function(ot){return ot&&typeof ot=="object"},o.isset=o.isSet=function(ot,it){var st=ot[it];return st!=null&&ot.hasOwnProperty(it)?typeof st!="object"||(Array.isArray(st)?st.length:Object.keys(st).length)>0:!1},o.Buffer=function(){try{var nt=o.inquire("buffer").Buffer;return nt.prototype.utf8Write?nt:null}catch{return null}}(),o._Buffer_from=null,o._Buffer_allocUnsafe=null,o.newBuffer=function(ot){return typeof ot=="number"?o.Buffer?o._Buffer_allocUnsafe(ot):new o.Array(ot):o.Buffer?o._Buffer_from(ot):typeof Uint8Array>"u"?ot:new Uint8Array(ot)},o.Array=typeof Uint8Array<"u"?Uint8Array:Array,o.Long=o.global.dcodeIO&&o.global.dcodeIO.Long||o.global.Long||o.inquire("long"),o.key2Re=/^true|false|0|1$/,o.key32Re=/^-?(?:0|[1-9][0-9]*)$/,o.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,o.longToHash=function(ot){return ot?o.LongBits.from(ot).toHash():o.LongBits.zeroHash},o.longFromHash=function(ot,it){var st=o.LongBits.fromHash(ot);return o.Long?o.Long.fromBits(st.lo,st.hi,it):st.toNumber(!!it)};function tt(nt,ot,it){for(var st=Object.keys(ot),at=0;at-1;--ct)if(it[at[ct]]===1&&this[at[ct]]!==void 0&&this[at[ct]]!==null)return at[ct]}},o.oneOfSetter=function(ot){return function(it){for(var st=0;st127;)o[tt++]=et&127|128,et>>>=7;o[tt]=et}function VarintOp(et,o){this.len=et,this.next=void 0,this.val=o}VarintOp.prototype=Object.create(Op.prototype);VarintOp.prototype.fn=writeVarint32;Writer$1.prototype.uint32=function et(o){return this.len+=(this.tail=this.tail.next=new VarintOp((o=o>>>0)<128?1:o<16384?2:o<2097152?3:o<268435456?4:5,o)).len,this};Writer$1.prototype.int32=function et(o){return o<0?this._push(writeVarint64,10,LongBits$1.fromNumber(o)):this.uint32(o)};Writer$1.prototype.sint32=function et(o){return this.uint32((o<<1^o>>31)>>>0)};function writeVarint64(et,o,tt){for(;et.hi;)o[tt++]=et.lo&127|128,et.lo=(et.lo>>>7|et.hi<<25)>>>0,et.hi>>>=7;for(;et.lo>127;)o[tt++]=et.lo&127|128,et.lo=et.lo>>>7;o[tt++]=et.lo}Writer$1.prototype.uint64=function et(o){var tt=LongBits$1.from(o);return this._push(writeVarint64,tt.length(),tt)};Writer$1.prototype.int64=Writer$1.prototype.uint64;Writer$1.prototype.sint64=function et(o){var tt=LongBits$1.from(o).zzEncode();return this._push(writeVarint64,tt.length(),tt)};Writer$1.prototype.bool=function et(o){return this._push(writeByte,1,o?1:0)};function writeFixed32(et,o,tt){o[tt]=et&255,o[tt+1]=et>>>8&255,o[tt+2]=et>>>16&255,o[tt+3]=et>>>24}Writer$1.prototype.fixed32=function et(o){return this._push(writeFixed32,4,o>>>0)};Writer$1.prototype.sfixed32=Writer$1.prototype.fixed32;Writer$1.prototype.fixed64=function et(o){var tt=LongBits$1.from(o);return this._push(writeFixed32,4,tt.lo)._push(writeFixed32,4,tt.hi)};Writer$1.prototype.sfixed64=Writer$1.prototype.fixed64;Writer$1.prototype.float=function et(o){return this._push(util$8.float.writeFloatLE,4,o)};Writer$1.prototype.double=function et(o){return this._push(util$8.float.writeDoubleLE,8,o)};var writeBytes=util$8.Array.prototype.set?function et(o,tt,rt){tt.set(o,rt)}:function et(o,tt,rt){for(var nt=0;nt>>0;if(!tt)return this._push(writeByte,1,0);if(util$8.isString(o)){var rt=Writer$1.alloc(tt=base64.length(o));base64.decode(o,rt,0),o=rt}return this.uint32(tt)._push(writeBytes,tt,o)};Writer$1.prototype.string=function et(o){var tt=utf8$1.length(o);return tt?this.uint32(tt)._push(utf8$1.write,tt,o):this._push(writeByte,1,0)};Writer$1.prototype.fork=function et(){return this.states=new State(this),this.head=this.tail=new Op(noop,0,0),this.len=0,this};Writer$1.prototype.reset=function et(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op(noop,0,0),this.len=0),this};Writer$1.prototype.ldelim=function et(){var o=this.head,tt=this.tail,rt=this.len;return this.reset().uint32(rt),rt&&(this.tail.next=o.next,this.tail=tt,this.len+=rt),this};Writer$1.prototype.finish=function et(){for(var o=this.head.next,tt=this.constructor.alloc(this.len),rt=0;o;)o.fn(o.val,tt,rt),rt+=o.len,o=o.next;return tt};Writer$1._configure=function(et){BufferWriter$1=et,Writer$1.create=create$2(),BufferWriter$1._configure()};var writer_buffer=BufferWriter,Writer=writer;(BufferWriter.prototype=Object.create(Writer.prototype)).constructor=BufferWriter;var util$7=requireMinimal();function BufferWriter(){Writer.call(this)}BufferWriter._configure=function(){BufferWriter.alloc=util$7._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=util$7.Buffer&&util$7.Buffer.prototype instanceof Uint8Array&&util$7.Buffer.prototype.set.name==="set"?function(o,tt,rt){tt.set(o,rt)}:function(o,tt,rt){if(o.copy)o.copy(tt,rt,0,o.length);else for(var nt=0;nt>>0;return this.uint32(tt),tt&&this._push(BufferWriter.writeBytesBuffer,tt,o),this};function writeStringBuffer(et,o,tt){et.length<40?util$7.utf8.write(et,o,tt):o.utf8Write?o.utf8Write(et,tt):o.write(et,tt)}BufferWriter.prototype.string=function et(o){var tt=util$7.Buffer.byteLength(o);return this.uint32(tt),tt&&this._push(writeStringBuffer,tt,o),this};BufferWriter._configure();var reader=Reader$1,util$6=requireMinimal(),BufferReader$1,LongBits=util$6.LongBits,utf8=util$6.utf8;function indexOutOfRange(et,o){return RangeError("index out of range: "+et.pos+" + "+(o||1)+" > "+et.len)}function Reader$1(et){this.buf=et,this.pos=0,this.len=et.length}var create_array=typeof Uint8Array<"u"?function et(o){if(o instanceof Uint8Array||Array.isArray(o))return new Reader$1(o);throw Error("illegal buffer")}:function et(o){if(Array.isArray(o))return new Reader$1(o);throw Error("illegal buffer")},create$1=function et(){return util$6.Buffer?function(tt){return(Reader$1.create=function(nt){return util$6.Buffer.isBuffer(nt)?new BufferReader$1(nt):create_array(nt)})(tt)}:create_array};Reader$1.create=create$1();Reader$1.prototype._slice=util$6.Array.prototype.subarray||util$6.Array.prototype.slice;Reader$1.prototype.uint32=function et(){var o=4294967295;return function(){if(o=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(o=(o|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(o=(o|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(o=(o|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(o=(o|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return o;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return o}}();Reader$1.prototype.int32=function et(){return this.uint32()|0};Reader$1.prototype.sint32=function et(){var o=this.uint32();return o>>>1^-(o&1)|0};function readLongVarint(){var et=new LongBits(0,0),o=0;if(this.len-this.pos>4){for(;o<4;++o)if(et.lo=(et.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return et;if(et.lo=(et.lo|(this.buf[this.pos]&127)<<28)>>>0,et.hi=(et.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return et;o=0}else{for(;o<3;++o){if(this.pos>=this.len)throw indexOutOfRange(this);if(et.lo=(et.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return et}return et.lo=(et.lo|(this.buf[this.pos++]&127)<>>0,et}if(this.len-this.pos>4){for(;o<5;++o)if(et.hi=(et.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return et}else for(;o<5;++o){if(this.pos>=this.len)throw indexOutOfRange(this);if(et.hi=(et.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return et}throw Error("invalid varint encoding")}Reader$1.prototype.bool=function et(){return this.uint32()!==0};function readFixed32_end(et,o){return(et[o-4]|et[o-3]<<8|et[o-2]<<16|et[o-1]<<24)>>>0}Reader$1.prototype.fixed32=function et(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)};Reader$1.prototype.sfixed32=function et(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)|0};function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.prototype.float=function et(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var o=util$6.float.readFloatLE(this.buf,this.pos);return this.pos+=4,o};Reader$1.prototype.double=function et(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var o=util$6.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,o};Reader$1.prototype.bytes=function et(){var o=this.uint32(),tt=this.pos,rt=this.pos+o;if(rt>this.len)throw indexOutOfRange(this,o);if(this.pos+=o,Array.isArray(this.buf))return this.buf.slice(tt,rt);if(tt===rt){var nt=util$6.Buffer;return nt?nt.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,tt,rt)};Reader$1.prototype.string=function et(){var o=this.bytes();return utf8.read(o,0,o.length)};Reader$1.prototype.skip=function et(o){if(typeof o=="number"){if(this.pos+o>this.len)throw indexOutOfRange(this,o);this.pos+=o}else do if(this.pos>=this.len)throw indexOutOfRange(this);while(this.buf[this.pos++]&128);return this};Reader$1.prototype.skipType=function(et){switch(et){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(et=this.uint32()&7)!==4;)this.skipType(et);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+et+" at offset "+this.pos)}return this};Reader$1._configure=function(et){BufferReader$1=et,Reader$1.create=create$1(),BufferReader$1._configure();var o=util$6.Long?"toLong":"toNumber";util$6.merge(Reader$1.prototype,{int64:function(){return readLongVarint.call(this)[o](!1)},uint64:function(){return readLongVarint.call(this)[o](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[o](!1)},fixed64:function(){return readFixed64.call(this)[o](!0)},sfixed64:function(){return readFixed64.call(this)[o](!1)}})};var reader_buffer=BufferReader,Reader=reader;(BufferReader.prototype=Object.create(Reader.prototype)).constructor=BufferReader;var util$5=requireMinimal();function BufferReader(et){Reader.call(this,et)}BufferReader._configure=function(){util$5.Buffer&&(BufferReader.prototype._slice=util$5.Buffer.prototype.slice)};BufferReader.prototype.string=function et(){var o=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+o,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+o,this.len))};BufferReader._configure();var rpc={},service$1=Service$1,util$4=requireMinimal();(Service$1.prototype=Object.create(util$4.EventEmitter.prototype)).constructor=Service$1;function Service$1(et,o,tt){if(typeof et!="function")throw TypeError("rpcImpl must be a function");util$4.EventEmitter.call(this),this.rpcImpl=et,this.requestDelimited=!!o,this.responseDelimited=!!tt}Service$1.prototype.rpcCall=function et(o,tt,rt,nt,ot){if(!nt)throw TypeError("request must be specified");var it=this;if(!ot)return util$4.asPromise(et,it,o,tt,rt,nt);if(!it.rpcImpl){setTimeout(function(){ot(Error("already ended"))},0);return}try{return it.rpcImpl(o,tt[it.requestDelimited?"encodeDelimited":"encode"](nt).finish(),function(at,ct){if(at)return it.emit("error",at,o),ot(at);if(ct===null){it.end(!0);return}if(!(ct instanceof rt))try{ct=rt[it.responseDelimited?"decodeDelimited":"decode"](ct)}catch(lt){return it.emit("error",lt,o),ot(lt)}return it.emit("data",ct,o),ot(null,ct)})}catch(st){it.emit("error",st,o),setTimeout(function(){ot(st)},0);return}};Service$1.prototype.end=function et(o){return this.rpcImpl&&(o||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this};(function(et){var o=et;o.Service=service$1})(rpc);var roots={};(function(et){var o=et;o.build="minimal",o.Writer=writer,o.BufferWriter=writer_buffer,o.Reader=reader,o.BufferReader=reader_buffer,o.util=requireMinimal(),o.rpc=rpc,o.roots=roots,o.configure=tt;function tt(){o.util._configure(),o.Writer._configure(o.BufferWriter),o.Reader._configure(o.BufferReader)}tt()})(indexMinimal);var util$3={exports:{}},codegen_1=codegen;function codegen(et,o){typeof et=="string"&&(o=et,et=void 0);var tt=[];function rt(ot){if(typeof ot!="string"){var it=nt();if(codegen.verbose&&console.log("codegen: "+it),it="return "+it,ot){for(var st=Object.keys(ot),at=new Array(st.length+1),ct=new Array(st.length),lt=0;lt0&&it[ct-1]!==".."?it.splice(--ct,2):st?it.splice(ct,1):++ct:it[ct]==="."?it.splice(ct,1):++ct;return at+it.join("/")};o.resolve=function(ot,it,st){return st||(it=rt(it)),tt(it)?it:(st||(ot=rt(ot)),(ot=ot.replace(/(?:\/|^)[^/]+$/,"")).length?rt(ot+"/"+it):it)}})(path);var types$2={},hasRequiredTypes;function requireTypes(){return hasRequiredTypes||(hasRequiredTypes=1,function(et){var o=et,tt=requireUtil(),rt=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function nt(ot,it){var st=0,at={};for(it|=0;st-1&&this.oneof.splice(st,1),it.partOf=null,this},rt.prototype.onAdd=function(it){et.prototype.onAdd.call(this,it);for(var st=this,at=0;atht)return!0}return!1},at.isReservedName=function(dt,ht){if(dt){for(var mt=0;mt0;){var ft=dt.shift();if(mt.nested&&mt.nested[ft]){if(mt=mt.nested[ft],!(mt instanceof at))throw Error("path conflicts with non-namespace objects")}else mt.add(mt=new at(ft))}return ht&&mt.addJSON(ht),mt},at.prototype.resolveAll=function(){for(var dt=this.nestedArray,ht=0;ht-1)return ft}else if(ft instanceof at&&(ft=ft.lookup(dt.slice(1),ht,!0)))return ft}else for(var pt=0;pt>>3){");for(var st=0;st>>3){")("case 1: k=r.%s(); break",at.keyType)("case 2:"),o.basic[ct]===void 0?it("value=types[%i].decode(r,r.uint32())",st):it("value=r.%s()",ct),it("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),o.long[at.keyType]!==void 0?it('%s[typeof k==="object"?util.longToHash(k):k]=value',lt):it("%s[k]=value",lt)):at.repeated?(it("if(!(%s&&%s.length))",lt,lt)("%s=[]",lt),o.packed[ct]!==void 0&&it("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos>>0",ct,ct);break;case"int32":case"sint32":case"sfixed32":it("m%s=d%s|0",ct,ct);break;case"uint64":ft=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":it("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",ct,ct,ft)('else if(typeof d%s==="string")',ct)("m%s=parseInt(d%s,10)",ct,ct)('else if(typeof d%s==="number")',ct)("m%s=d%s",ct,ct)('else if(typeof d%s==="object")',ct)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",ct,ct,ct,ft?"true":"");break;case"bytes":it('if(typeof d%s==="string")',ct)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",ct,ct,ct)("else if(d%s.length >= 0)",ct)("m%s=d%s",ct,ct);break;case"string":it("m%s=String(d%s)",ct,ct);break;case"bool":it("m%s=Boolean(d%s)",ct,ct);break}}return it}o.fromObject=function(st){var at=st.fieldsArray,ct=rt.codegen(["d"],st.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!at.length)return ct("return new this.ctor");ct("var m=new this.ctor");for(var lt=0;lt>>0,m%s.high>>>0).toNumber(%s):m%s",ct,ct,ct,ct,lt?"true":"",ct);break;case"bytes":it("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",ct,ct,ct,ct,ct);break;default:it("d%s=m%s",ct,ct);break}}return it}o.toObject=function(st){var at=st.fieldsArray.slice().sort(rt.compareFieldsById);if(!at.length)return rt.codegen()("return {}");for(var ct=rt.codegen(["m","o"],st.name+"$toObject")("if(!o)")("o={}")("var d={}"),lt=[],dt=[],ht=[],mt=0;mt-1){var Ot=kt.substring(It);if(Ot in st)return Ot}return null}function vt(kt,It){try{if(nt.isString(It)&&It.charAt(0)==="{"&&(It=JSON.parse(It)),!nt.isString(It))gt.setOptions(It.options).addJSON(It.nested);else{it.filename=kt;var Ot=it(It,gt,ft),Nt,Yt=0;if(Ot.imports)for(;Yt-1)){if(gt.files.push(kt),kt in st){yt?vt(kt,st[kt]):(++Ct,setTimeout(function(){--Ct,vt(kt,st[kt])}));return}if(yt){var Ot;try{Ot=nt.fs.readFileSync(kt).toString("utf8")}catch(Nt){It||bt(Nt);return}vt(kt,Ot)}else++Ct,gt.fetch(kt,function(Nt,Yt){if(--Ct,!!pt){if(Nt){It?Ct||bt(null,gt):bt(Nt);return}vt(kt,Yt)}})}}var Ct=0;nt.isString(mt)&&(mt=[mt]);for(var St=0,At;St-1&&this.deferred.splice(ft,1)}}else if(mt instanceof tt)lt.test(mt.name)&&delete mt.parent[mt.name];else if(mt instanceof et){for(var pt=0;pt0)mt[gt]=ht(mt[gt]||{},ft,pt);else{var yt=mt[gt];yt&&(pt=[].concat(yt).concat(pt)),mt[gt]=pt}return mt}if(typeof ct!="object")throw TypeError("dst must be an object");if(!lt)throw TypeError("path must be specified");return lt=lt.split("."),ht(ct,lt,dt)},Object.defineProperty(et,"decorateRoot",{get:function(){return o.decorated||(o.decorated=new(requireRoot()))}}),util$3.exports}var object,hasRequiredObject;function requireObject(){if(hasRequiredObject)return object;hasRequiredObject=1,object=tt,tt.className="ReflectionObject";var et=requireUtil(),o;function tt(rt,nt){if(!et.isString(rt))throw TypeError("name must be a string");if(nt&&!et.isObject(nt))throw TypeError("options must be an object");this.options=nt,this.parsedOptions=null,this.name=rt,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}return Object.defineProperties(tt.prototype,{root:{get:function(){for(var rt=this;rt.parent!==null;)rt=rt.parent;return rt}},fullName:{get:function(){for(var rt=[this.name],nt=this.parent;nt;)rt.unshift(nt.name),nt=nt.parent;return rt.join(".")}}}),tt.prototype.toJSON=function(){throw Error()},tt.prototype.onAdd=function(nt){this.parent&&this.parent!==nt&&this.parent.remove(this),this.parent=nt,this.resolved=!1;var ot=nt.root;ot instanceof o&&ot._handleAdd(this)},tt.prototype.onRemove=function(nt){var ot=nt.root;ot instanceof o&&ot._handleRemove(this),this.parent=null,this.resolved=!1},tt.prototype.resolve=function(){return this.resolved?this:(this.root instanceof o&&(this.resolved=!0),this)},tt.prototype.getOption=function(nt){if(this.options)return this.options[nt]},tt.prototype.setOption=function(nt,ot,it){return(!it||!this.options||this.options[nt]===void 0)&&((this.options||(this.options={}))[nt]=ot),this},tt.prototype.setParsedOption=function(nt,ot,it){this.parsedOptions||(this.parsedOptions=[]);var st=this.parsedOptions;if(it){var at=st.find(function(dt){return Object.prototype.hasOwnProperty.call(dt,nt)});if(at){var ct=at[nt];et.setProperty(ct,it,ot)}else at={},at[nt]=et.setProperty({},it,ot),st.push(at)}else{var lt={};lt[nt]=ot,st.push(lt)}return this},tt.prototype.setOptions=function(nt,ot){if(nt)for(var it=Object.keys(nt),st=0;st>>0,(it.id<<3|4)>>>0):ot("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",st,at,(it.id<<3|2)>>>0)}function nt(ot){for(var it=tt.codegen(["m","w"],ot.name+"$encode")("if(!w)")("w=Writer.create()"),st,at,ct=ot.fieldsArray.slice().sort(tt.compareFieldsById),st=0;st>>0,8|o.mapKey[lt.keyType],lt.keyType),mt===void 0?it("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",dt,at):it(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|mt,ht,at),it("}")("}")):lt.repeated?(it("if(%s!=null&&%s.length){",at,at),lt.packed&&o.packed[ht]!==void 0?it("w.uint32(%i).fork()",(lt.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",at)("w.%s(%s[i])",ht,at)("w.ldelim()"):(it("for(var i=0;i<%s.length;++i)",at),mt===void 0?rt(it,lt,dt,at+"[i]"):it("w.uint32(%i).%s(%s[i])",(lt.id<<3|mt)>>>0,ht,at)),it("}")):(lt.optional&&it("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",at,lt.name),mt===void 0?rt(it,lt,dt,at):it("w.uint32(%i).%s(%s)",(lt.id<<3|mt)>>>0,ht,at))}return it("return w")}return encoder_1}var protobuf$2=indexLight.exports=indexMinimal;protobuf$2.build="light";function load(et,o,tt){return typeof o=="function"?(tt=o,o=new protobuf$2.Root):o||(o=new protobuf$2.Root),o.load(et,tt)}protobuf$2.load=load;function loadSync(et,o){return o||(o=new protobuf$2.Root),o.loadSync(et)}protobuf$2.loadSync=loadSync;protobuf$2.encoder=requireEncoder();protobuf$2.decoder=requireDecoder();protobuf$2.verifier=requireVerifier();protobuf$2.converter=requireConverter();protobuf$2.ReflectionObject=requireObject();protobuf$2.Namespace=requireNamespace();protobuf$2.Root=requireRoot();protobuf$2.Enum=require_enum();protobuf$2.Type=requireType();protobuf$2.Field=requireField();protobuf$2.OneOf=requireOneof();protobuf$2.MapField=requireMapfield();protobuf$2.Service=requireService();protobuf$2.Method=requireMethod();protobuf$2.Message=message;protobuf$2.wrappers=wrappers;protobuf$2.types=requireTypes();protobuf$2.util=requireUtil();protobuf$2.ReflectionObject._configure(protobuf$2.Root);protobuf$2.Namespace._configure(protobuf$2.Type,protobuf$2.Service,protobuf$2.Enum);protobuf$2.Root._configure(protobuf$2.Type);protobuf$2.Field._configure(protobuf$2.Type);var indexLightExports=indexLight.exports,tokenize_1=tokenize$1,delimRe=/[\s{}=;:[\],'"()<>]/g,stringDoubleRe=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,stringSingleRe=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,setCommentRe=/^ *[*/]+ */,setCommentAltRe=/^\s*\*?\/*/,setCommentSplitRe=/\n/g,whitespaceRe=/\s/,unescapeRe=/\\(.?)/g,unescapeMap={0:"\0",r:"\r",n:` +`,t:" "};function unescape$1(et){return et.replace(unescapeRe,function(o,tt){switch(tt){case"\\":case"":return tt;default:return unescapeMap[tt]||""}})}tokenize$1.unescape=unescape$1;function tokenize$1(et,o){et=et.toString();var tt=0,rt=et.length,nt=1,ot=0,it={},st=[],at=null;function ct(vt){return Error("illegal "+vt+" (line "+nt+")")}function lt(){var vt=at==="'"?stringSingleRe:stringDoubleRe;vt.lastIndex=tt-1;var Et=vt.exec(et);if(!Et)throw ct("string");return tt=vt.lastIndex,gt(at),at=null,unescape$1(Et[1])}function dt(vt){return et.charAt(vt)}function ht(vt,Et,Ct){var St={type:et.charAt(vt++),lineEmpty:!1,leading:Ct},At;o?At=2:At=3;var kt=vt-At,It;do if(--kt<0||(It=et.charAt(kt))===` +`){St.lineEmpty=!0;break}while(It===" "||It===" ");for(var Ot=et.substring(vt,Et).split(setCommentSplitRe),Nt=0;Nt0)return st.shift();if(at)return lt();var vt,Et,Ct,St,At,kt=tt===0;do{if(tt===rt)return null;for(vt=!1;whitespaceRe.test(Ct=dt(tt));)if(Ct===` +`&&(kt=!0,++nt),++tt===rt)return null;if(dt(tt)==="/"){if(++tt===rt)throw ct("comment");if(dt(tt)==="/")if(o){if(St=tt,At=!1,mt(tt-1)){At=!0;do if(tt=ft(tt),tt===rt||(tt++,!kt))break;while(mt(tt))}else tt=Math.min(rt,ft(tt)+1);At&&(ht(St,tt,kt),kt=!0),nt++,vt=!0}else{for(At=dt(St=tt+1)==="/";dt(++tt)!==` +`;)if(tt===rt)return null;++tt,At&&(ht(St,tt-1,kt),kt=!0),++nt,vt=!0}else if((Ct=dt(tt))==="*"){St=tt+1,At=o||dt(St)==="*";do{if(Ct===` +`&&++nt,++tt===rt)throw ct("comment");Et=Ct,Ct=dt(tt)}while(Et!=="*"||Ct!=="/");++tt,At&&(ht(St,tt-2,kt),kt=!0),vt=!0}else return"/"}}while(vt);var It=tt;delimRe.lastIndex=0;var Ot=delimRe.test(dt(It++));if(!Ot)for(;It");var Ut=ot();if(!nameRe$1.test(Ut))throw bt(Ut,"name");at("=");var Zt=new MapField(yt(Ut),St(ot()),Rt,Mt);Nt(Zt,function(ar){if(ar==="option")jt(Zt,ar),at(";");else throw bt(ar)},function(){Gt(Zt)}),Jt.add(Zt)}function Vt(Jt,Rt){if(!nameRe$1.test(Rt=ot()))throw bt(Rt,"name");var Mt=new OneOf(yt(Rt));Nt(Mt,function(Zt){Zt==="option"?(jt(Mt,Zt),at(";")):(it(Zt),Ft(Mt,"optional"))}),Jt.add(Mt)}function Bt(Jt,Rt){if(!nameRe$1.test(Rt=ot()))throw bt(Rt,"name");var Mt=new Enum(Rt);Nt(Mt,function(Zt){switch(Zt){case"option":jt(Mt,Zt),at(";");break;case"reserved":Et(Mt.reserved||(Mt.reserved=[]),!0);break;default:Wt(Mt,Zt)}}),Jt.add(Mt)}function Wt(Jt,Rt){if(!nameRe$1.test(Rt))throw bt(Rt,"name");at("=");var Mt=St(ot(),!0),Ut={options:void 0};Ut.setOption=function(Zt,nr){this.options===void 0&&(this.options={}),this.options[Zt]=nr},Nt(Ut,function(nr){if(nr==="option")jt(Ut,nr),at(";");else throw bt(nr)},function(){Gt(Ut)}),Jt.add(Rt,Mt,Ut.comment,Ut.options)}function jt(Jt,Rt){var Mt=at("(",!0);if(!typeRefRe.test(Rt=ot()))throw bt(Rt,"name");var Ut=Rt,Zt=Ut,nr;Mt&&(at(")"),Ut="("+Ut+")",Zt=Ut,Rt=st(),fqTypeRefRe.test(Rt)&&(nr=Rt.slice(1),Ut+=Rt,ot())),at("=");var ar=Xt(Jt,Ut);Pt(Jt,Zt,ar,nr)}function Xt(Jt,Rt){if(at("{",!0)){for(var Mt={};!at("}",!0);){if(!nameRe$1.test(rr=ot()))throw bt(rr,"name");if(rr===null)throw bt(rr,"end of input");var Ut,Zt=rr;if(at(":",!0),st()==="{")Ut=Xt(Jt,Rt+"."+rr);else if(st()==="["){Ut=[];var nr;if(at("[",!0)){do nr=vt(),Ut.push(nr);while(at(",",!0));at("]"),typeof nr<"u"&&Kt(Jt,Rt+"."+rr,nr)}}else Ut=vt(),Kt(Jt,Rt+"."+rr,Ut);var ar=Mt[Zt];ar&&(Ut=[].concat(ar).concat(Ut)),Mt[Zt]=Ut,at(",",!0),at(";",!0)}return Mt}var dr=vt();return Kt(Jt,Rt,dr),dr}function Kt(Jt,Rt,Mt){Jt.setOption&&Jt.setOption(Rt,Mt)}function Pt(Jt,Rt,Mt,Ut){Jt.setParsedOption&&Jt.setParsedOption(Rt,Mt,Ut)}function Gt(Jt){if(at("[",!0)){do jt(Jt,"option");while(at(",",!0));at("]")}return Jt}function tr(Jt,Rt){if(!nameRe$1.test(Rt=ot()))throw bt(Rt,"service name");var Mt=new Service(Rt);Nt(Mt,function(Zt){if(!Ot(Mt,Zt))if(Zt==="rpc")zt(Mt,Zt);else throw bt(Zt)}),Jt.add(Mt)}function zt(Jt,Rt){var Mt=ct(),Ut=Rt;if(!nameRe$1.test(Rt=ot()))throw bt(Rt,"name");var Zt=Rt,nr,ar,dr,cr;if(at("("),at("stream",!0)&&(ar=!0),!typeRefRe.test(Rt=ot())||(nr=Rt,at(")"),at("returns"),at("("),at("stream",!0)&&(cr=!0),!typeRefRe.test(Rt=ot())))throw bt(Rt);dr=Rt,at(")");var yr=new Method(Zt,Ut,nr,dr,ar,cr);yr.comment=Mt,Nt(yr,function(gr){if(gr==="option")jt(yr,gr),at(";");else throw bt(gr)}),Jt.add(yr)}function lr(Jt,Rt){if(!typeRefRe.test(Rt=ot()))throw bt(Rt,"reference");var Mt=Rt;Nt(null,function(Zt){switch(Zt){case"required":case"repeated":Ft(Jt,Zt,Mt);break;case"optional":pt?Ft(Jt,"proto3_optional",Mt):Ft(Jt,"optional",Mt);break;default:if(!pt||!typeRefRe.test(Zt))throw bt(Zt);it(Zt),Ft(Jt,"optional",Mt);break}})}for(var rr;(rr=ot())!==null;)switch(rr){case"package":if(!lt)throw bt(rr);At();break;case"import":if(!lt)throw bt(rr);kt();break;case"syntax":if(!lt)throw bt(rr);It();break;case"option":jt(gt,rr),at(";");break;default:if(Ot(gt,rr)){lt=!1;continue}throw bt(rr)}return parse$1.filename=null,{package:dt,imports:ht,weakImports:mt,syntax:ft,root:o}}var common_1=common,commonRe=/\/|\./;function common(et,o){commonRe.test(et)||(et="google/protobuf/"+et+".proto",o={nested:{google:{nested:{protobuf:{nested:o}}}}}),common[et]=o}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});common("timestamp",{Timestamp:timeType});common("empty",{Empty:{fields:{}}});common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});common.get=function et(o){return common[o]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full";protobuf$1.tokenize=tokenize_1;protobuf$1.parse=parse_1;protobuf$1.common=common_1;protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs(protobufjs),WAKU_NODE_OPTIONS={defaultBootstrap:!0,nodeToUse:{store:"/dns4/store-02.ac-cn-hongkong-c.status.staging.status.im/tcp/443/wss/p2p/16Uiu2HAmU7xtcwytXpGpeDrfyhJkiFvTkQbLB9upL5MXPLGceG9K"}},contentTopic="/buddybook-dogfood/1/chain/proto",encoder=createEncoder({contentTopic,ephemeral:!1}),decoder=createDecoder(contentTopic),block=new protobuf.Type("block").add(new protobuf.Field("chainUUID",1,"string")).add(new protobuf.Field("blockUUID",2,"string")).add(new protobuf.Field("title",3,"string")).add(new protobuf.Field("description",4,"string")).add(new protobuf.Field("signedMessage",5,"string")).add(new protobuf.Field("timestamp",6,"uint64")).add(new protobuf.Field("signatures",7,"string","repeated")).add(new protobuf.Field("parentBlockUUID",8,"string"));function createMessage({chainUUID:et,blockUUID:o,title:tt,description:rt,signedMessage:nt,timestamp:ot,signatures:it,parentBlockUUID:st}){const at=block.create({chainUUID:et,blockUUID:o,title:tt,description:rt,signedMessage:nt,timestamp:ot,signatures:it.map(lt=>JSON.stringify(lt)),parentBlockUUID:st});return{payload:block.encode(at).finish()}}async function*getMessagesFromStore(et){console.time("getMessagesFromStore");for await(const o of et.store.queryGenerator([decoder])){const tt=await Promise.all(o);for(const rt of tt){if(console.log(rt),!(rt!=null&&rt.payload))continue;const nt=block.decode(rt.payload);nt.signatures=nt.signatures.map(ot=>JSON.parse(ot)),yield nt}}console.timeEnd("getMessagesFromStore")}async function subscribeToFilter(et,o){const{error:tt,subscription:rt,results:nt}=await et.filter.subscribe([decoder],ot=>{if(console.log("message received from filter",ot),ot.payload){const it=block.decode(ot.payload);it.signatures=it.signatures.map(st=>JSON.parse(st)),o(it)}},{forceUseAllPeers:!0});if(console.log("results",nt),tt&&console.log("Error subscribing to filter",tt),!rt||tt||nt.successes.length===0||nt.failures.length>0)throw new Error("Failed to subscribe to filter")}function useWalletPrompt(){const{isConnected:et}=useAccount(),{connect:o,connectors:tt}=useConnect$1();return{ensureWalletConnected:()=>{if(!et){const nt=tt[0];return nt&&o({connector:nt}),!1}return!0}}}const DEFAULT_FORM_DATA={title:"Devcon24 DeFi Dynamo",description:"A revolutionary blockchain for Devcon 24, focusing on scalable DeFi solutions and cross-chain interoperability.",uuid:v4()},ChainCreationForm=()=>{const[et,o]=reactExports.useState(DEFAULT_FORM_DATA),[tt,rt]=reactExports.useState({}),[nt,ot]=reactExports.useState(!1),[it,st]=reactExports.useState(!1),[at,ct]=reactExports.useState(!1),[lt,dt]=reactExports.useState(null),[ht,mt]=reactExports.useState(null),[ft,pt]=reactExports.useState(null),{node:gt}=useWaku(),{address:yt}=useAccount(),{signMessage:bt}=useSignMessage({mutation:{async onSuccess(kt){if(!yt||!gt)return;mt(kt);const It=v4();pt(It);const Ot=createMessage({chainUUID:et.uuid,blockUUID:It,title:et.title,description:et.description,signedMessage:kt,timestamp:Date.now(),signatures:[{address:yt,signature:kt}],parentBlockUUID:null});await(gt==null?void 0:gt.lightPush.send(encoder,Ot)),ct(!0),st(!1)},onError(kt){console.error("Error signing message:",kt),st(!1),dt("Error signing message. Please try again.")}}}),{ensureWalletConnected:xt}=useWalletPrompt(),vt=kt=>{const{name:It,value:Ot}=kt.target;o(Nt=>({...Nt,[It]:Ot})),tt[It]&&rt(Nt=>({...Nt,[It]:void 0}))},Et=()=>{const kt={};return et.title.trim()||(kt.title="Title is required"),et.description.trim()||(kt.description="Description is required"),rt(kt),Object.keys(kt).length===0},Ct=kt=>{kt.preventDefault(),xt()&&Et()&&ot(!0)},St=async()=>{st(!0),dt(null);const kt=`Create Chain: + Chain UUID: ${et.uuid} + Title: ${et.title} + Description: ${et.description} + Timestamp: ${new Date().getTime()} + Signed by: ${yt}`;bt({message:kt})},At=()=>{ot(!1),ct(!1),st(!1),dt(null),pt(null)};return jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-2xl mx-auto",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{children:"Create a New Chain"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("form",{onSubmit:Ct,className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"title",children:"Chain Title"}),jsxRuntimeExports.jsx(Input,{type:"text",id:"title",name:"title",value:et.title,onChange:vt,maxLength:50}),tt.title&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:tt.title})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"description",children:"Chain Description"}),jsxRuntimeExports.jsx(Textarea,{id:"description",name:"description",value:et.description,onChange:vt,maxLength:500}),tt.description&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:tt.description})]}),jsxRuntimeExports.jsx(Button,{type:"submit",className:"w-full",children:"Create Chain"})]})}),jsxRuntimeExports.jsx(Dialog,{open:nt,onOpenChange:At,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsx(DialogHeader,{children:jsxRuntimeExports.jsx(DialogTitle,{children:at?"Chain Created":"Chain Preview"})}),at?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:ht&&ft&&jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[jsxRuntimeExports.jsx(QRCode,{text:`${window.location.origin}/sign/${et.uuid}/${ft}`,width:200,height:200}),jsxRuntimeExports.jsx("p",{className:"text-sm text-center break-all",children:`${window.location.origin}/sign/${et.uuid}/${ft}`}),jsxRuntimeExports.jsx(Button,{onClick:()=>navigator.clipboard.writeText(`${window.location.origin}/sign/${et.uuid}/${ft}`),variant:"outline",children:"Copy Link"})]})})}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("h4",{className:"text-xl font-semibold",children:et.title}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:et.description}),lt&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:lt})]}),jsxRuntimeExports.jsxs(DialogFooter,{className:"sm:justify-start",children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"secondary",onClick:At,children:"Edit"}),jsxRuntimeExports.jsx(Button,{type:"button",onClick:St,disabled:it,children:it?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Signing..."]}):"Sign"})]})]})]})})]})},SignChain=({block:et,chainsData:o,onSuccess:tt})=>{const[rt,nt]=reactExports.useState(!1),[ot,it]=reactExports.useState(!1),[st,at]=reactExports.useState(null),[ct,lt]=reactExports.useState(!1),{address:dt}=useAccount(),{data:ht}=useEnsName({address:dt}),{node:mt}=useWaku(),{ensureWalletConnected:ft}=useWalletPrompt();reactExports.useEffect(()=>{if(dt){const yt=xt=>{if(xt.signatures.some(Ct=>Ct.address.toLowerCase()===dt.toLowerCase()))return!0;const vt=o.find(Ct=>Ct.blockUUID===xt.parentBlockUUID);return vt&&yt(vt)?!0:o.filter(Ct=>Ct.parentBlockUUID===xt.blockUUID).some(Ct=>yt(Ct))},bt=yt(et);lt(bt)}},[dt,et,o]);const{signMessage:pt}=useSignMessage({mutation:{async onSuccess(yt){if(!dt||!mt)return;if(et.signatures.some(xt=>xt.address.toLowerCase()===dt.toLowerCase())){at("You have already signed this chain."),it(!1);return}const bt={chainUUID:et.chainUUID,blockUUID:v4(),title:et.title,description:et.description,signedMessage:yt,timestamp:Date.now(),signatures:[{address:dt,signature:yt}],parentBlockUUID:et.blockUUID};try{const xt=createMessage(bt),{failures:vt,successes:Et}=await mt.lightPush.send(encoder,xt);if(vt.length>0||Et.length===0)throw new Error("Failed to send message to Waku network");tt(bt),nt(!1)}catch(xt){console.error("Error creating new block:",xt),at("Failed to create new block. Please try again.")}finally{it(!1)}},onError(yt){console.error("Error signing message:",yt),at("Error signing message. Please try again."),it(!1)}}}),gt=()=>{if(!ft())return;if(ct){at("You have already signed this chain.");return}it(!0),at(null);const yt=`Sign Block: + Chain UUID: ${et.chainUUID} + Block UUID: ${et.blockUUID} + Title: ${et.title} + Description: ${et.description} + Timestamp: ${new Date().getTime()} + Parent Block UUID: ${et.parentBlockUUID} + Signed by: ${ht||dt}`;pt({message:yt})};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Button,{onClick:()=>nt(!0),disabled:ct,children:ct?"Already Signed":"Sign Chain"}),jsxRuntimeExports.jsx(Dialog,{open:rt,onOpenChange:nt,children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-md",children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Sign Chain"}),jsxRuntimeExports.jsx(DialogDescription,{children:ct?"You have already signed this chain.":"Review the block details and sign to add your signature to the chain."})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("h4",{className:"font-medium",children:"Block Details"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:et.title}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:et.description})]}),jsxRuntimeExports.jsx(QRCode,{text:`${window.location.origin}/sign/${et.chainUUID}/${et.blockUUID}`})]}),st&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:st}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"secondary",onClick:()=>nt(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:gt,disabled:ot||ct,children:ot?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Signing..."]}):ct?"Already Signed":"Sign"})]})]})})]})},ChainList=({chainsData:et,onChainUpdate:o,isLoading:tt})=>{const rt=it=>{o(it)},nt=(it,st=0)=>{const at=et.filter(dt=>dt.parentBlockUUID===it.blockUUID),ct=it.signatures.length+at.reduce((dt,ht)=>dt+ht.signatures.length,0),lt=`${window.location.origin}/sign/${it.chainUUID??it.blockUUID}/${it.blockUUID}`;return jsxRuntimeExports.jsxs("li",{className:"mb-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start",children:[jsxRuntimeExports.jsx("div",{className:"mr-4 mt-2",children:st>0&&jsxRuntimeExports.jsx("div",{className:"w-6 h-6 border-l-2 border-b-2 border-gray-300"})}),st===0?jsxRuntimeExports.jsxs(Card,{className:"flex-grow",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{children:it.title})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsx("p",{children:it.description}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Created at: ",new Date(it.timestamp).toLocaleString()]}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Total Signatures: ",ct]}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Block UUID: ",it.blockUUID]}),jsxRuntimeExports.jsxs("div",{className:"mt-2 space-x-2",children:[jsxRuntimeExports.jsx(SignChain,{block:it,chainsData:et,onSuccess:rt}),jsxRuntimeExports.jsxs(Dialog,{children:[jsxRuntimeExports.jsx(DialogTrigger,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"outline",children:"Share"})}),jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-md",children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Share this Chain"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Share this chain with others to collect their signatures."})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[jsxRuntimeExports.jsx(QRCode,{text:lt,width:200,height:200}),jsxRuntimeExports.jsx("p",{className:"text-sm text-center break-all",children:lt}),jsxRuntimeExports.jsx(Button,{onClick:()=>navigator.clipboard.writeText(lt),variant:"outline",children:"Copy Link"})]})]})]})]})]})]}):jsxRuntimeExports.jsx("div",{className:"flex-grow",children:jsxRuntimeExports.jsx(SignerName,{address:it.signatures[0].address})})]}),at.length>0&&jsxRuntimeExports.jsx("ul",{className:"ml-8 mt-2",children:at.map(dt=>nt(dt,st+1))})]},`${it.blockUUID}-${st}`)},ot=et.filter(it=>!it.parentBlockUUID);return jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-4xl mx-auto",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{children:["Existing Chains",tt&&jsxRuntimeExports.jsxs("span",{className:"ml-2 inline-flex items-center text-muted-foreground text-sm font-normal",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin mr-2"}),"Loading more chains..."]})]})}),jsxRuntimeExports.jsx(CardContent,{children:ot.length===0&&!tt?jsxRuntimeExports.jsx("p",{children:"No chains found."}):jsxRuntimeExports.jsx("ul",{className:"space-y-4",children:ot.map(it=>nt(it,0))})})]})},SignerName=({address:et})=>{const{data:o}=useEnsName({address:et});return jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Signed by: ",o||`${et.slice(0,6)}...${et.slice(-4)}`]})};var DirectionContext=reactExports.createContext(void 0);function useDirection(et){const o=reactExports.useContext(DirectionContext);return et||o||"ltr"}function clamp(et,[o,tt]){return Math.min(tt,Math.max(o,et))}function useStateMachine(et,o){return reactExports.useReducer((tt,rt)=>o[tt][rt]??tt,et)}var SCROLL_AREA_NAME="ScrollArea",[createScrollAreaContext,createScrollAreaScope]=createContextScope(SCROLL_AREA_NAME),[ScrollAreaProvider,useScrollAreaContext]=createScrollAreaContext(SCROLL_AREA_NAME),ScrollArea$1=reactExports.forwardRef((et,o)=>{const{__scopeScrollArea:tt,type:rt="hover",dir:nt,scrollHideDelay:ot=600,...it}=et,[st,at]=reactExports.useState(null),[ct,lt]=reactExports.useState(null),[dt,ht]=reactExports.useState(null),[mt,ft]=reactExports.useState(null),[pt,gt]=reactExports.useState(null),[yt,bt]=reactExports.useState(0),[xt,vt]=reactExports.useState(0),[Et,Ct]=reactExports.useState(!1),[St,At]=reactExports.useState(!1),kt=useComposedRefs(o,Ot=>at(Ot)),It=useDirection(nt);return jsxRuntimeExports.jsx(ScrollAreaProvider,{scope:tt,type:rt,dir:It,scrollHideDelay:ot,scrollArea:st,viewport:ct,onViewportChange:lt,content:dt,onContentChange:ht,scrollbarX:mt,onScrollbarXChange:ft,scrollbarXEnabled:Et,onScrollbarXEnabledChange:Ct,scrollbarY:pt,onScrollbarYChange:gt,scrollbarYEnabled:St,onScrollbarYEnabledChange:At,onCornerWidthChange:bt,onCornerHeightChange:vt,children:jsxRuntimeExports.jsx(Primitive.div,{dir:It,...it,ref:kt,style:{position:"relative","--radix-scroll-area-corner-width":yt+"px","--radix-scroll-area-corner-height":xt+"px",...et.style}})})});ScrollArea$1.displayName=SCROLL_AREA_NAME;var VIEWPORT_NAME="ScrollAreaViewport",ScrollAreaViewport=reactExports.forwardRef((et,o)=>{const{__scopeScrollArea:tt,children:rt,asChild:nt,nonce:ot,...it}=et,st=useScrollAreaContext(VIEWPORT_NAME,tt),at=reactExports.useRef(null),ct=useComposedRefs(o,at,st.onViewportChange);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("style",{dangerouslySetInnerHTML:{__html:` +[data-radix-scroll-area-viewport] { + scrollbar-width: none; + -ms-overflow-style: none; + -webkit-overflow-scrolling: touch; +} +[data-radix-scroll-area-viewport]::-webkit-scrollbar { + display: none; +} +:where([data-radix-scroll-area-viewport]) { + display: flex; + flex-direction: column; + align-items: stretch; +} +:where([data-radix-scroll-area-content]) { + flex-grow: 1; +} +`},nonce:ot}),jsxRuntimeExports.jsx(Primitive.div,{"data-radix-scroll-area-viewport":"",...it,asChild:nt,ref:ct,style:{overflowX:st.scrollbarXEnabled?"scroll":"hidden",overflowY:st.scrollbarYEnabled?"scroll":"hidden",...et.style},children:getSubtree({asChild:nt,children:rt},lt=>jsxRuntimeExports.jsx("div",{"data-radix-scroll-area-content":"",ref:st.onContentChange,style:{minWidth:st.scrollbarXEnabled?"fit-content":void 0},children:lt}))})]})});ScrollAreaViewport.displayName=VIEWPORT_NAME;var SCROLLBAR_NAME="ScrollAreaScrollbar",ScrollAreaScrollbar=reactExports.forwardRef((et,o)=>{const{forceMount:tt,...rt}=et,nt=useScrollAreaContext(SCROLLBAR_NAME,et.__scopeScrollArea),{onScrollbarXEnabledChange:ot,onScrollbarYEnabledChange:it}=nt,st=et.orientation==="horizontal";return reactExports.useEffect(()=>(st?ot(!0):it(!0),()=>{st?ot(!1):it(!1)}),[st,ot,it]),nt.type==="hover"?jsxRuntimeExports.jsx(ScrollAreaScrollbarHover,{...rt,ref:o,forceMount:tt}):nt.type==="scroll"?jsxRuntimeExports.jsx(ScrollAreaScrollbarScroll,{...rt,ref:o,forceMount:tt}):nt.type==="auto"?jsxRuntimeExports.jsx(ScrollAreaScrollbarAuto,{...rt,ref:o,forceMount:tt}):nt.type==="always"?jsxRuntimeExports.jsx(ScrollAreaScrollbarVisible,{...rt,ref:o}):null});ScrollAreaScrollbar.displayName=SCROLLBAR_NAME;var ScrollAreaScrollbarHover=reactExports.forwardRef((et,o)=>{const{forceMount:tt,...rt}=et,nt=useScrollAreaContext(SCROLLBAR_NAME,et.__scopeScrollArea),[ot,it]=reactExports.useState(!1);return reactExports.useEffect(()=>{const st=nt.scrollArea;let at=0;if(st){const ct=()=>{window.clearTimeout(at),it(!0)},lt=()=>{at=window.setTimeout(()=>it(!1),nt.scrollHideDelay)};return st.addEventListener("pointerenter",ct),st.addEventListener("pointerleave",lt),()=>{window.clearTimeout(at),st.removeEventListener("pointerenter",ct),st.removeEventListener("pointerleave",lt)}}},[nt.scrollArea,nt.scrollHideDelay]),jsxRuntimeExports.jsx(Presence,{present:tt||ot,children:jsxRuntimeExports.jsx(ScrollAreaScrollbarAuto,{"data-state":ot?"visible":"hidden",...rt,ref:o})})}),ScrollAreaScrollbarScroll=reactExports.forwardRef((et,o)=>{const{forceMount:tt,...rt}=et,nt=useScrollAreaContext(SCROLLBAR_NAME,et.__scopeScrollArea),ot=et.orientation==="horizontal",it=useDebounceCallback(()=>at("SCROLL_END"),100),[st,at]=useStateMachine("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return reactExports.useEffect(()=>{if(st==="idle"){const ct=window.setTimeout(()=>at("HIDE"),nt.scrollHideDelay);return()=>window.clearTimeout(ct)}},[st,nt.scrollHideDelay,at]),reactExports.useEffect(()=>{const ct=nt.viewport,lt=ot?"scrollLeft":"scrollTop";if(ct){let dt=ct[lt];const ht=()=>{const mt=ct[lt];dt!==mt&&(at("SCROLL"),it()),dt=mt};return ct.addEventListener("scroll",ht),()=>ct.removeEventListener("scroll",ht)}},[nt.viewport,ot,at,it]),jsxRuntimeExports.jsx(Presence,{present:tt||st!=="hidden",children:jsxRuntimeExports.jsx(ScrollAreaScrollbarVisible,{"data-state":st==="hidden"?"hidden":"visible",...rt,ref:o,onPointerEnter:composeEventHandlers(et.onPointerEnter,()=>at("POINTER_ENTER")),onPointerLeave:composeEventHandlers(et.onPointerLeave,()=>at("POINTER_LEAVE"))})})}),ScrollAreaScrollbarAuto=reactExports.forwardRef((et,o)=>{const tt=useScrollAreaContext(SCROLLBAR_NAME,et.__scopeScrollArea),{forceMount:rt,...nt}=et,[ot,it]=reactExports.useState(!1),st=et.orientation==="horizontal",at=useDebounceCallback(()=>{if(tt.viewport){const ct=tt.viewport.offsetWidth{const{orientation:tt="vertical",...rt}=et,nt=useScrollAreaContext(SCROLLBAR_NAME,et.__scopeScrollArea),ot=reactExports.useRef(null),it=reactExports.useRef(0),[st,at]=reactExports.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),ct=getThumbRatio(st.viewport,st.content),lt={...rt,sizes:st,onSizesChange:at,hasThumb:ct>0&&ct<1,onThumbChange:ht=>ot.current=ht,onThumbPointerUp:()=>it.current=0,onThumbPointerDown:ht=>it.current=ht};function dt(ht,mt){return getScrollPositionFromPointer(ht,it.current,st,mt)}return tt==="horizontal"?jsxRuntimeExports.jsx(ScrollAreaScrollbarX,{...lt,ref:o,onThumbPositionChange:()=>{if(nt.viewport&&ot.current){const ht=nt.viewport.scrollLeft,mt=getThumbOffsetFromScroll(ht,st,nt.dir);ot.current.style.transform=`translate3d(${mt}px, 0, 0)`}},onWheelScroll:ht=>{nt.viewport&&(nt.viewport.scrollLeft=ht)},onDragScroll:ht=>{nt.viewport&&(nt.viewport.scrollLeft=dt(ht,nt.dir))}}):tt==="vertical"?jsxRuntimeExports.jsx(ScrollAreaScrollbarY,{...lt,ref:o,onThumbPositionChange:()=>{if(nt.viewport&&ot.current){const ht=nt.viewport.scrollTop,mt=getThumbOffsetFromScroll(ht,st);ot.current.style.transform=`translate3d(0, ${mt}px, 0)`}},onWheelScroll:ht=>{nt.viewport&&(nt.viewport.scrollTop=ht)},onDragScroll:ht=>{nt.viewport&&(nt.viewport.scrollTop=dt(ht))}}):null}),ScrollAreaScrollbarX=reactExports.forwardRef((et,o)=>{const{sizes:tt,onSizesChange:rt,...nt}=et,ot=useScrollAreaContext(SCROLLBAR_NAME,et.__scopeScrollArea),[it,st]=reactExports.useState(),at=reactExports.useRef(null),ct=useComposedRefs(o,at,ot.onScrollbarXChange);return reactExports.useEffect(()=>{at.current&&st(getComputedStyle(at.current))},[at]),jsxRuntimeExports.jsx(ScrollAreaScrollbarImpl,{"data-orientation":"horizontal",...nt,ref:ct,sizes:tt,style:{bottom:0,left:ot.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:ot.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":getThumbSize(tt)+"px",...et.style},onThumbPointerDown:lt=>et.onThumbPointerDown(lt.x),onDragScroll:lt=>et.onDragScroll(lt.x),onWheelScroll:(lt,dt)=>{if(ot.viewport){const ht=ot.viewport.scrollLeft+lt.deltaX;et.onWheelScroll(ht),isScrollingWithinScrollbarBounds(ht,dt)&<.preventDefault()}},onResize:()=>{at.current&&ot.viewport&&it&&rt({content:ot.viewport.scrollWidth,viewport:ot.viewport.offsetWidth,scrollbar:{size:at.current.clientWidth,paddingStart:toInt(it.paddingLeft),paddingEnd:toInt(it.paddingRight)}})}})}),ScrollAreaScrollbarY=reactExports.forwardRef((et,o)=>{const{sizes:tt,onSizesChange:rt,...nt}=et,ot=useScrollAreaContext(SCROLLBAR_NAME,et.__scopeScrollArea),[it,st]=reactExports.useState(),at=reactExports.useRef(null),ct=useComposedRefs(o,at,ot.onScrollbarYChange);return reactExports.useEffect(()=>{at.current&&st(getComputedStyle(at.current))},[at]),jsxRuntimeExports.jsx(ScrollAreaScrollbarImpl,{"data-orientation":"vertical",...nt,ref:ct,sizes:tt,style:{top:0,right:ot.dir==="ltr"?0:void 0,left:ot.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":getThumbSize(tt)+"px",...et.style},onThumbPointerDown:lt=>et.onThumbPointerDown(lt.y),onDragScroll:lt=>et.onDragScroll(lt.y),onWheelScroll:(lt,dt)=>{if(ot.viewport){const ht=ot.viewport.scrollTop+lt.deltaY;et.onWheelScroll(ht),isScrollingWithinScrollbarBounds(ht,dt)&<.preventDefault()}},onResize:()=>{at.current&&ot.viewport&&it&&rt({content:ot.viewport.scrollHeight,viewport:ot.viewport.offsetHeight,scrollbar:{size:at.current.clientHeight,paddingStart:toInt(it.paddingTop),paddingEnd:toInt(it.paddingBottom)}})}})}),[ScrollbarProvider,useScrollbarContext]=createScrollAreaContext(SCROLLBAR_NAME),ScrollAreaScrollbarImpl=reactExports.forwardRef((et,o)=>{const{__scopeScrollArea:tt,sizes:rt,hasThumb:nt,onThumbChange:ot,onThumbPointerUp:it,onThumbPointerDown:st,onThumbPositionChange:at,onDragScroll:ct,onWheelScroll:lt,onResize:dt,...ht}=et,mt=useScrollAreaContext(SCROLLBAR_NAME,tt),[ft,pt]=reactExports.useState(null),gt=useComposedRefs(o,kt=>pt(kt)),yt=reactExports.useRef(null),bt=reactExports.useRef(""),xt=mt.viewport,vt=rt.content-rt.viewport,Et=useCallbackRef$1(lt),Ct=useCallbackRef$1(at),St=useDebounceCallback(dt,10);function At(kt){if(yt.current){const It=kt.clientX-yt.current.left,Ot=kt.clientY-yt.current.top;ct({x:It,y:Ot})}}return reactExports.useEffect(()=>{const kt=It=>{const Ot=It.target;(ft==null?void 0:ft.contains(Ot))&&Et(It,vt)};return document.addEventListener("wheel",kt,{passive:!1}),()=>document.removeEventListener("wheel",kt,{passive:!1})},[xt,ft,vt,Et]),reactExports.useEffect(Ct,[rt,Ct]),useResizeObserver(ft,St),useResizeObserver(mt.content,St),jsxRuntimeExports.jsx(ScrollbarProvider,{scope:tt,scrollbar:ft,hasThumb:nt,onThumbChange:useCallbackRef$1(ot),onThumbPointerUp:useCallbackRef$1(it),onThumbPositionChange:Ct,onThumbPointerDown:useCallbackRef$1(st),children:jsxRuntimeExports.jsx(Primitive.div,{...ht,ref:gt,style:{position:"absolute",...ht.style},onPointerDown:composeEventHandlers(et.onPointerDown,kt=>{kt.button===0&&(kt.target.setPointerCapture(kt.pointerId),yt.current=ft.getBoundingClientRect(),bt.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",mt.viewport&&(mt.viewport.style.scrollBehavior="auto"),At(kt))}),onPointerMove:composeEventHandlers(et.onPointerMove,At),onPointerUp:composeEventHandlers(et.onPointerUp,kt=>{const It=kt.target;It.hasPointerCapture(kt.pointerId)&&It.releasePointerCapture(kt.pointerId),document.body.style.webkitUserSelect=bt.current,mt.viewport&&(mt.viewport.style.scrollBehavior=""),yt.current=null})})})}),THUMB_NAME="ScrollAreaThumb",ScrollAreaThumb=reactExports.forwardRef((et,o)=>{const{forceMount:tt,...rt}=et,nt=useScrollbarContext(THUMB_NAME,et.__scopeScrollArea);return jsxRuntimeExports.jsx(Presence,{present:tt||nt.hasThumb,children:jsxRuntimeExports.jsx(ScrollAreaThumbImpl,{ref:o,...rt})})}),ScrollAreaThumbImpl=reactExports.forwardRef((et,o)=>{const{__scopeScrollArea:tt,style:rt,...nt}=et,ot=useScrollAreaContext(THUMB_NAME,tt),it=useScrollbarContext(THUMB_NAME,tt),{onThumbPositionChange:st}=it,at=useComposedRefs(o,dt=>it.onThumbChange(dt)),ct=reactExports.useRef(),lt=useDebounceCallback(()=>{ct.current&&(ct.current(),ct.current=void 0)},100);return reactExports.useEffect(()=>{const dt=ot.viewport;if(dt){const ht=()=>{if(lt(),!ct.current){const mt=addUnlinkedScrollListener(dt,st);ct.current=mt,st()}};return st(),dt.addEventListener("scroll",ht),()=>dt.removeEventListener("scroll",ht)}},[ot.viewport,lt,st]),jsxRuntimeExports.jsx(Primitive.div,{"data-state":it.hasThumb?"visible":"hidden",...nt,ref:at,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...rt},onPointerDownCapture:composeEventHandlers(et.onPointerDownCapture,dt=>{const mt=dt.target.getBoundingClientRect(),ft=dt.clientX-mt.left,pt=dt.clientY-mt.top;it.onThumbPointerDown({x:ft,y:pt})}),onPointerUp:composeEventHandlers(et.onPointerUp,it.onThumbPointerUp)})});ScrollAreaThumb.displayName=THUMB_NAME;var CORNER_NAME="ScrollAreaCorner",ScrollAreaCorner=reactExports.forwardRef((et,o)=>{const tt=useScrollAreaContext(CORNER_NAME,et.__scopeScrollArea),rt=!!(tt.scrollbarX&&tt.scrollbarY);return tt.type!=="scroll"&&rt?jsxRuntimeExports.jsx(ScrollAreaCornerImpl,{...et,ref:o}):null});ScrollAreaCorner.displayName=CORNER_NAME;var ScrollAreaCornerImpl=reactExports.forwardRef((et,o)=>{const{__scopeScrollArea:tt,...rt}=et,nt=useScrollAreaContext(CORNER_NAME,tt),[ot,it]=reactExports.useState(0),[st,at]=reactExports.useState(0),ct=!!(ot&&st);return useResizeObserver(nt.scrollbarX,()=>{var dt;const lt=((dt=nt.scrollbarX)==null?void 0:dt.offsetHeight)||0;nt.onCornerHeightChange(lt),at(lt)}),useResizeObserver(nt.scrollbarY,()=>{var dt;const lt=((dt=nt.scrollbarY)==null?void 0:dt.offsetWidth)||0;nt.onCornerWidthChange(lt),it(lt)}),ct?jsxRuntimeExports.jsx(Primitive.div,{...rt,ref:o,style:{width:ot,height:st,position:"absolute",right:nt.dir==="ltr"?0:void 0,left:nt.dir==="rtl"?0:void 0,bottom:0,...et.style}}):null});function toInt(et){return et?parseInt(et,10):0}function getThumbRatio(et,o){const tt=et/o;return isNaN(tt)?0:tt}function getThumbSize(et){const o=getThumbRatio(et.viewport,et.content),tt=et.scrollbar.paddingStart+et.scrollbar.paddingEnd,rt=(et.scrollbar.size-tt)*o;return Math.max(rt,18)}function getScrollPositionFromPointer(et,o,tt,rt="ltr"){const nt=getThumbSize(tt),ot=nt/2,it=o||ot,st=nt-it,at=tt.scrollbar.paddingStart+it,ct=tt.scrollbar.size-tt.scrollbar.paddingEnd-st,lt=tt.content-tt.viewport,dt=rt==="ltr"?[0,lt]:[lt*-1,0];return linearScale([at,ct],dt)(et)}function getThumbOffsetFromScroll(et,o,tt="ltr"){const rt=getThumbSize(o),nt=o.scrollbar.paddingStart+o.scrollbar.paddingEnd,ot=o.scrollbar.size-nt,it=o.content-o.viewport,st=ot-rt,at=tt==="ltr"?[0,it]:[it*-1,0],ct=clamp(et,at);return linearScale([0,it],[0,st])(ct)}function linearScale(et,o){return tt=>{if(et[0]===et[1]||o[0]===o[1])return o[0];const rt=(o[1]-o[0])/(et[1]-et[0]);return o[0]+rt*(tt-et[0])}}function isScrollingWithinScrollbarBounds(et,o){return et>0&&et{})=>{let tt={left:et.scrollLeft,top:et.scrollTop},rt=0;return function nt(){const ot={left:et.scrollLeft,top:et.scrollTop},it=tt.left!==ot.left,st=tt.top!==ot.top;(it||st)&&o(),tt=ot,rt=window.requestAnimationFrame(nt)}(),()=>window.cancelAnimationFrame(rt)};function useDebounceCallback(et,o){const tt=useCallbackRef$1(et),rt=reactExports.useRef(0);return reactExports.useEffect(()=>()=>window.clearTimeout(rt.current),[]),reactExports.useCallback(()=>{window.clearTimeout(rt.current),rt.current=window.setTimeout(tt,o)},[tt,o])}function useResizeObserver(et,o){const tt=useCallbackRef$1(o);useLayoutEffect2(()=>{let rt=0;if(et){const nt=new ResizeObserver(()=>{cancelAnimationFrame(rt),rt=window.requestAnimationFrame(tt)});return nt.observe(et),()=>{window.cancelAnimationFrame(rt),nt.unobserve(et)}}},[et,tt])}function getSubtree(et,o){const{asChild:tt,children:rt}=et;if(!tt)return typeof o=="function"?o(rt):o;const nt=reactExports.Children.only(rt);return reactExports.cloneElement(nt,{children:typeof o=="function"?o(nt.props.children):o})}var Root=ScrollArea$1,Viewport=ScrollAreaViewport,Corner=ScrollAreaCorner;const ScrollArea=reactExports.forwardRef(({className:et,children:o,...tt},rt)=>jsxRuntimeExports.jsxs(Root,{ref:rt,className:cn("relative overflow-hidden",et),...tt,children:[jsxRuntimeExports.jsx(Viewport,{className:"h-full w-full rounded-[inherit]",children:o}),jsxRuntimeExports.jsx(ScrollBar,{}),jsxRuntimeExports.jsx(Corner,{})]}));ScrollArea.displayName=Root.displayName;const ScrollBar=reactExports.forwardRef(({className:et,orientation:o="vertical",...tt},rt)=>jsxRuntimeExports.jsx(ScrollAreaScrollbar,{ref:rt,orientation:o,className:cn("flex touch-none select-none transition-colors",o==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",o==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",et),...tt,children:jsxRuntimeExports.jsx(ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));ScrollBar.displayName=ScrollAreaScrollbar.displayName;const privacyPolicy=` +# Waku - Dogfooding Website + +*Last updated: 22 August 2024* + +This Privacy Policy is intended to inform users of our approach to privacy in respect of this website ("Website"). In this regard, if you are visiting or interacting with our Website, this Privacy Policy applies to you. + +This Website has been set-up by us for the purposes of gathering telemetry data from users of the Website about the reliability protocols utilised by Waku (such activity and related activity, being referred to as "Dogfooding"). + +Waku is a family of robust, censorship-resistant communication protocols designed to enable privacy-focused messaging for web3 apps. You can read more about Waku here: https://waku.org/. + +## Who we are + +For the purposes of this Privacy Policy and the collection and processing of personal data as a controller, the relevant entity is the Logos Collective Association, which has its registered office in Zug and its legal domicile address at + +Logos Collective Association +c/o PST Consulting GmbH +Baarerstrasse 10 +6300 Zug +Switzerland + +Whenever we refer to "Logos", "we" or other similar references, we are referring to the Logos Collective Association. + +## We limit the collection and processing of personal data from your use of the Website and for "Dogfooding" purposes + +We aim to limit the collection and processing of personal data from users of the Website and your participation in Dogfooding. We only collect and process certain personal data for specific purposes and where we have the legal basis to do so under applicable privacy legislation. We will not collect or process any personal data that we don't need and where we do store any personal data, we will only store it for the least amount of time needed for the indicated purpose and in any event no longer than thirty (30) days. + +In this regard, we collect and process the following personal data from your use of the Website and your participation in Dogfooding: + +**IP address**: As part of such use of the Website, we briefly process your IP address. We however have a legitimate interest in processing such IP addresses to ensure the technical functionality and enhance the security measures of the Website. This IP address is not stored by us over time. + +**Telemetry data**: We collect certain technical information (also referred to as telemetry data) to primarily determine the reliability (including, the performance and usage patterns) of the Waku reliability protocols for light clients. This information is only collected once you have accepted the prompt on the Website to participate in Dogfooding. Once you've accepted this prompt, a Waku node will start operating on your browser and then the technical information will start being collected by us. + +The information collected includes: + +- timestamps of receiving and sending messages; +- size of message packets; +- content topics/pubsub topics of the messages; +- code logs of errors and warnings; and +- a randomly generated temporary peer ID that represents your Waku node. + +The temporary peer ID is a seeded identifier used for the duration of your participation in Dogfooding and allows us to correlate the obtained technical information with a particular session and with the additional information collected, could be potentially considered personal data. We process such data based on our legitimate interest to improve our software and the user's experience in respect of Waku. + +If you do not agree to this data collection and processing, please do not interact with the Website or proceed with your participation in Dogfooding. + +## Personal data sharing with third party service providers + +We may share personal data with third party service providers in order for us to fulfil the above purposes. Such third party service providers act as data processors on our behalf and are only permitted to process personal data in accordance with our instructions and for the purposes specified above. + +## Security measures we take in respect of the Website + +As a general approach, we take data security seriously and we have implemented a variety of security measures on the Website that are reasonably designed to maintain the safety of your personal data when you submit such information to us. + +In addition to the security measures of the Website, personal data is also protected by Waku (protocol) itself. You can read more about the security features implemented by the Waku protocol here. + +## Exporting data outside the European Union and Switzerland + +We are obliged to protect the privacy of personal data that you may have submitted in the unlikely event that we export your personal data to places outside the European Union or Switzerland. This means that personal data will only be processed in countries or by parties that provide an adequate level of protection as deemed by Switzerland or the European Commission. Otherwise, we will use other forms of protections, such as specific forms of contractual clauses to ensure such personal data is provided the same protection as required in Switzerland or Europe. In any event, the transmission of personal data outside the European Union and Switzerland will always occur in conformity with applicable privacy legislation. + +## Your choices and rights + +As explained in this Privacy Policy, we limit our collection and processing of your personal data wherever possible. Nonetheless, you still have certain choices and rights in respect of the personal data which we do collect and process. As laid out in relevant privacy legislation, you have the right to: + +- Ask us to correct or update your personal data (where reasonably possible); +- Ask us to remove your personal data from our systems; +- Ask us for a copy of your personal data, which may also be transferred to another data controller at your request; +- Withdraw your consent to process your personal data (only if consent was asked for a processing activity), which only affects processing activities that are based on your consent and doesn't affect the validity of such processing activities before you have withdrawn your consent; +- Object to the processing of your personal data; and +- File a complaint with the Federal Data Protection and Information Commissioner (FDPIC), if you believe that your personal data has been processed unlawfully. + +## Third party links + +On this Website, you may come across links to third party websites. These third party sites have separate and independent privacy policies. We therefore have no responsibility or liability for the content and activities of these third party websites. + +## This Privacy Policy might change + +We may modify or replace any part of this Privacy Policy at any time and without notice. Please check the Website periodically for any changes. The new Privacy Policy will be effective immediately upon its posting on our Website. + +## Contact information + +To the extent that you have any questions about the Privacy Policy, please contact us at legal@free.technology. + +This document is licensed under CC-BY-SA. +`;function ok$1(){}function unreachable(){}function stringify$1(et,o){const tt={};return(et[et.length-1]===""?[...et,""]:et).join((tt.padRight?" ":"")+","+(tt.padLeft===!1?"":" ")).trim()}const nameRe=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,nameReJsx=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,emptyOptions$2={};function name(et,o){return(emptyOptions$2.jsx?nameReJsx:nameRe).test(et)}const re=/[ \t\n\f\r]/g;function whitespace(et){return typeof et=="object"?et.type==="text"?empty$1(et.value):!1:empty$1(et)}function empty$1(et){return et.replace(re,"")===""}class Schema{constructor(o,tt,rt){this.property=o,this.normal=tt,rt&&(this.space=rt)}}Schema.prototype.property={};Schema.prototype.normal={};Schema.prototype.space=null;function merge(et,o){const tt={},rt={};let nt=-1;for(;++nt4&&tt.slice(0,4)==="data"&&valid.test(o)){if(o.charAt(4)==="-"){const ot=o.slice(5).replace(dash,camelcase);rt="data"+ot.charAt(0).toUpperCase()+ot.slice(1)}else{const ot=o.slice(4);if(!dash.test(ot)){let it=ot.replace(cap$1,kebab);it.charAt(0)!=="-"&&(it="-"+it),o="data"+it}}nt=DefinedInfo}return new nt(rt,o)}function kebab(et){return"-"+et.toLowerCase()}function camelcase(et){return et.charAt(1).toUpperCase()}const hastToReact={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},html$1=merge([xml,xlink,xmlns,aria,html$2],"html"),svg=merge([xml,xlink,xmlns,aria,svg$1],"svg");function stringify(et){return et.join(" ").trim()}var cjs={},COMMENT_REGEX=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,NEWLINE_REGEX=/\n/g,WHITESPACE_REGEX=/^\s*/,PROPERTY_REGEX=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,COLON_REGEX=/^:\s*/,VALUE_REGEX=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,SEMICOLON_REGEX=/^[;\s]*/,TRIM_REGEX=/^\s+|\s+$/g,NEWLINE=` +`,FORWARD_SLASH="/",ASTERISK="*",EMPTY_STRING="",TYPE_COMMENT="comment",TYPE_DECLARATION="declaration",inlineStyleParser=function(et,o){if(typeof et!="string")throw new TypeError("First argument must be a string");if(!et)return[];o=o||{};var tt=1,rt=1;function nt(ft){var pt=ft.match(NEWLINE_REGEX);pt&&(tt+=pt.length);var gt=ft.lastIndexOf(NEWLINE);rt=~gt?ft.length-gt:rt+ft.length}function ot(){var ft={line:tt,column:rt};return function(pt){return pt.position=new it(ft),ct(),pt}}function it(ft){this.start=ft,this.end={line:tt,column:rt},this.source=o.source}it.prototype.content=et;function st(ft){var pt=new Error(o.source+":"+tt+":"+rt+": "+ft);if(pt.reason=ft,pt.filename=o.source,pt.line=tt,pt.column=rt,pt.source=et,!o.silent)throw pt}function at(ft){var pt=ft.exec(et);if(pt){var gt=pt[0];return nt(gt),et=et.slice(gt.length),pt}}function ct(){at(WHITESPACE_REGEX)}function lt(ft){var pt;for(ft=ft||[];pt=dt();)pt!==!1&&ft.push(pt);return ft}function dt(){var ft=ot();if(!(FORWARD_SLASH!=et.charAt(0)||ASTERISK!=et.charAt(1))){for(var pt=2;EMPTY_STRING!=et.charAt(pt)&&(ASTERISK!=et.charAt(pt)||FORWARD_SLASH!=et.charAt(pt+1));)++pt;if(pt+=2,EMPTY_STRING===et.charAt(pt-1))return st("End of comment missing");var gt=et.slice(2,pt-2);return rt+=2,nt(gt),et=et.slice(pt),rt+=2,ft({type:TYPE_COMMENT,comment:gt})}}function ht(){var ft=ot(),pt=at(PROPERTY_REGEX);if(pt){if(dt(),!at(COLON_REGEX))return st("property missing ':'");var gt=at(VALUE_REGEX),yt=ft({type:TYPE_DECLARATION,property:trim(pt[0].replace(COMMENT_REGEX,EMPTY_STRING)),value:gt?trim(gt[0].replace(COMMENT_REGEX,EMPTY_STRING)):EMPTY_STRING});return at(SEMICOLON_REGEX),yt}}function mt(){var ft=[];lt(ft);for(var pt;pt=ht();)pt!==!1&&(ft.push(pt),lt(ft));return ft}return ct(),mt()};function trim(et){return et?et.replace(TRIM_REGEX,EMPTY_STRING):EMPTY_STRING}var __importDefault=commonjsGlobal&&commonjsGlobal.__importDefault||function(et){return et&&et.__esModule?et:{default:et}};Object.defineProperty(cjs,"__esModule",{value:!0});var _default=cjs.default=StyleToObject,inline_style_parser_1=__importDefault(inlineStyleParser);function StyleToObject(et,o){var tt=null;if(!et||typeof et!="string")return tt;var rt=(0,inline_style_parser_1.default)(et),nt=typeof o=="function";return rt.forEach(function(ot){if(ot.type==="declaration"){var it=ot.property,st=ot.value;nt?o(it,st,ot):st&&(tt=tt||{},tt[it]=st)}}),tt}const styleToObject=_default.default||_default,pointEnd=point$2("end"),pointStart=point$2("start");function point$2(et){return o;function o(tt){const rt=tt&&tt.position&&tt.position[et]||{};if(typeof rt.line=="number"&&rt.line>0&&typeof rt.column=="number"&&rt.column>0)return{line:rt.line,column:rt.column,offset:typeof rt.offset=="number"&&rt.offset>-1?rt.offset:void 0}}}function position$1(et){const o=pointStart(et),tt=pointEnd(et);if(o&&tt)return{start:o,end:tt}}function stringifyPosition(et){return!et||typeof et!="object"?"":"position"in et||"type"in et?position(et.position):"start"in et||"end"in et?position(et):"line"in et||"column"in et?point$1(et):""}function point$1(et){return index(et&&et.line)+":"+index(et&&et.column)}function position(et){return point$1(et&&et.start)+"-"+point$1(et&&et.end)}function index(et){return et&&typeof et=="number"?et:1}class VFileMessage extends Error{constructor(o,tt,rt){super(),typeof tt=="string"&&(rt=tt,tt=void 0);let nt="",ot={},it=!1;if(tt&&("line"in tt&&"column"in tt?ot={place:tt}:"start"in tt&&"end"in tt?ot={place:tt}:"type"in tt?ot={ancestors:[tt],place:tt.position}:ot={...tt}),typeof o=="string"?nt=o:!ot.cause&&o&&(it=!0,nt=o.message,ot.cause=o),!ot.ruleId&&!ot.source&&typeof rt=="string"){const at=rt.indexOf(":");at===-1?ot.ruleId=rt:(ot.source=rt.slice(0,at),ot.ruleId=rt.slice(at+1))}if(!ot.place&&ot.ancestors&&ot.ancestors){const at=ot.ancestors[ot.ancestors.length-1];at&&(ot.place=at.position)}const st=ot.place&&"start"in ot.place?ot.place.start:ot.place;this.ancestors=ot.ancestors||void 0,this.cause=ot.cause||void 0,this.column=st?st.column:void 0,this.fatal=void 0,this.file,this.message=nt,this.line=st?st.line:void 0,this.name=stringifyPosition(ot.place)||"1:1",this.place=ot.place||void 0,this.reason=this.message,this.ruleId=ot.ruleId||void 0,this.source=ot.source||void 0,this.stack=it&&ot.cause&&typeof ot.cause.stack=="string"?ot.cause.stack:"",this.actual,this.expected,this.note,this.url}}VFileMessage.prototype.file="";VFileMessage.prototype.name="";VFileMessage.prototype.reason="";VFileMessage.prototype.message="";VFileMessage.prototype.stack="";VFileMessage.prototype.column=void 0;VFileMessage.prototype.line=void 0;VFileMessage.prototype.ancestors=void 0;VFileMessage.prototype.cause=void 0;VFileMessage.prototype.fatal=void 0;VFileMessage.prototype.place=void 0;VFileMessage.prototype.ruleId=void 0;VFileMessage.prototype.source=void 0;const own$3={}.hasOwnProperty,emptyMap=new Map,cap=/[A-Z]/g,dashSomething=/-([a-z])/g,tableElements=new Set(["table","tbody","thead","tfoot","tr"]),tableCellElement=new Set(["td","th"]),docs="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function toJsxRuntime(et,o){if(!o||o.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const tt=o.filePath||void 0;let rt;if(o.development){if(typeof o.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");rt=developmentCreate(tt,o.jsxDEV)}else{if(typeof o.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof o.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");rt=productionCreate(tt,o.jsx,o.jsxs)}const nt={Fragment:o.Fragment,ancestors:[],components:o.components||{},create:rt,elementAttributeNameCase:o.elementAttributeNameCase||"react",evaluater:o.createEvaluater?o.createEvaluater():void 0,filePath:tt,ignoreInvalidStyle:o.ignoreInvalidStyle||!1,passKeys:o.passKeys!==!1,passNode:o.passNode||!1,schema:o.space==="svg"?svg:html$1,stylePropertyNameCase:o.stylePropertyNameCase||"dom",tableCellAlignToStyle:o.tableCellAlignToStyle!==!1},ot=one$1(nt,et,void 0);return ot&&typeof ot!="string"?ot:nt.create(et,nt.Fragment,{children:ot||void 0},void 0)}function one$1(et,o,tt){if(o.type==="element")return element$1(et,o,tt);if(o.type==="mdxFlowExpression"||o.type==="mdxTextExpression")return mdxExpression(et,o);if(o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement")return mdxJsxElement(et,o,tt);if(o.type==="mdxjsEsm")return mdxEsm(et,o);if(o.type==="root")return root$1(et,o,tt);if(o.type==="text")return text$3(et,o)}function element$1(et,o,tt){const rt=et.schema;let nt=rt;o.tagName.toLowerCase()==="svg"&&rt.space==="html"&&(nt=svg,et.schema=nt),et.ancestors.push(o);const ot=findComponentFromName(et,o.tagName,!1),it=createElementProps(et,o);let st=createChildren(et,o);return tableElements.has(o.tagName)&&(st=st.filter(function(at){return typeof at=="string"?!whitespace(at):!0})),addNode(et,it,ot,o),addChildren(it,st),et.ancestors.pop(),et.schema=rt,et.create(o,ot,it,tt)}function mdxExpression(et,o){if(o.data&&o.data.estree&&et.evaluater){const rt=o.data.estree.body[0];return rt.type,et.evaluater.evaluateExpression(rt.expression)}crashEstree(et,o.position)}function mdxEsm(et,o){if(o.data&&o.data.estree&&et.evaluater)return et.evaluater.evaluateProgram(o.data.estree);crashEstree(et,o.position)}function mdxJsxElement(et,o,tt){const rt=et.schema;let nt=rt;o.name==="svg"&&rt.space==="html"&&(nt=svg,et.schema=nt),et.ancestors.push(o);const ot=o.name===null?et.Fragment:findComponentFromName(et,o.name,!0),it=createJsxElementProps(et,o),st=createChildren(et,o);return addNode(et,it,ot,o),addChildren(it,st),et.ancestors.pop(),et.schema=rt,et.create(o,ot,it,tt)}function root$1(et,o,tt){const rt={};return addChildren(rt,createChildren(et,o)),et.create(o,et.Fragment,rt,tt)}function text$3(et,o){return o.value}function addNode(et,o,tt,rt){typeof tt!="string"&&tt!==et.Fragment&&et.passNode&&(o.node=rt)}function addChildren(et,o){if(o.length>0){const tt=o.length>1?o:o[0];tt&&(et.children=tt)}}function productionCreate(et,o,tt){return rt;function rt(nt,ot,it,st){const ct=Array.isArray(it.children)?tt:o;return st?ct(ot,it,st):ct(ot,it)}}function developmentCreate(et,o){return tt;function tt(rt,nt,ot,it){const st=Array.isArray(ot.children),at=pointStart(rt);return o(nt,ot,it,st,{columnNumber:at?at.column-1:void 0,fileName:et,lineNumber:at?at.line:void 0},void 0)}}function createElementProps(et,o){const tt={};let rt,nt;for(nt in o.properties)if(nt!=="children"&&own$3.call(o.properties,nt)){const ot=createProperty(et,nt,o.properties[nt]);if(ot){const[it,st]=ot;et.tableCellAlignToStyle&&it==="align"&&typeof st=="string"&&tableCellElement.has(o.tagName)?rt=st:tt[it]=st}}if(rt){const ot=tt.style||(tt.style={});ot[et.stylePropertyNameCase==="css"?"text-align":"textAlign"]=rt}return tt}function createJsxElementProps(et,o){const tt={};for(const rt of o.attributes)if(rt.type==="mdxJsxExpressionAttribute")if(rt.data&&rt.data.estree&&et.evaluater){const ot=rt.data.estree.body[0];ot.type;const it=ot.expression;it.type;const st=it.properties[0];st.type,Object.assign(tt,et.evaluater.evaluateExpression(st.argument))}else crashEstree(et,o.position);else{const nt=rt.name;let ot;if(rt.value&&typeof rt.value=="object")if(rt.value.data&&rt.value.data.estree&&et.evaluater){const st=rt.value.data.estree.body[0];st.type,ot=et.evaluater.evaluateExpression(st.expression)}else crashEstree(et,o.position);else ot=rt.value===null?!0:rt.value;tt[nt]=ot}return tt}function createChildren(et,o){const tt=[];let rt=-1;const nt=et.passKeys?new Map:emptyMap;for(;++rtnt?0:nt+o:o=o>nt?nt:o,tt=tt>0?tt:0,rt.length<1e4)it=Array.from(rt),it.unshift(o,tt),et.splice(...it);else for(tt&&et.splice(o,tt);ot0?(splice(et,et.length,0,o),et):o}const hasOwnProperty={}.hasOwnProperty;function combineExtensions(et){const o={};let tt=-1;for(;++tt13&&tt<32||tt>126&&tt<160||tt>55295&&tt<57344||tt>64975&&tt<65008||(tt&65535)===65535||(tt&65535)===65534||tt>1114111?"�":String.fromCodePoint(tt)}function normalizeIdentifier(et){return et.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const asciiAlpha=regexCheck(/[A-Za-z]/),asciiAlphanumeric=regexCheck(/[\dA-Za-z]/),asciiAtext=regexCheck(/[#-'*+\--9=?A-Z^-~]/);function asciiControl(et){return et!==null&&(et<32||et===127)}const asciiDigit=regexCheck(/\d/),asciiHexDigit=regexCheck(/[\dA-Fa-f]/),asciiPunctuation=regexCheck(/[!-/:-@[-`{-~]/);function markdownLineEnding(et){return et!==null&&et<-2}function markdownLineEndingOrSpace(et){return et!==null&&(et<0||et===32)}function markdownSpace(et){return et===-2||et===-1||et===32}const unicodePunctuation=regexCheck(new RegExp("\\p{P}|\\p{S}","u")),unicodeWhitespace=regexCheck(/\s/);function regexCheck(et){return o;function o(tt){return tt!==null&&tt>-1&&et.test(String.fromCharCode(tt))}}function normalizeUri(et){const o=[];let tt=-1,rt=0,nt=0;for(;++tt55295&&ot<57344){const st=et.charCodeAt(tt+1);ot<56320&&st>56319&&st<57344?(it=String.fromCharCode(ot,st),nt=1):it="�"}else it=String.fromCharCode(ot);it&&(o.push(et.slice(rt,tt),encodeURIComponent(it)),rt=tt+nt+1,it=""),nt&&(tt+=nt,nt=0)}return o.join("")+et.slice(rt)}function factorySpace(et,o,tt,rt){const nt=rt?rt-1:Number.POSITIVE_INFINITY;let ot=0;return it;function it(at){return markdownSpace(at)?(et.enter(tt),st(at)):o(at)}function st(at){return markdownSpace(at)&&ot++it))return;const St=o.events.length;let At=St,kt,It;for(;At--;)if(o.events[At][0]==="exit"&&o.events[At][1].type==="chunkFlow"){if(kt){It=o.events[At][1].end;break}kt=!0}for(yt(rt),Ct=St;Ctxt;){const Et=tt[vt];o.containerState=Et[1],Et[0].exit.call(o,et)}tt.length=xt}function bt(){nt.write([null]),ot=void 0,nt=void 0,o.containerState._closeFlow=void 0}}function tokenizeContainer(et,o,tt){return factorySpace(et,et.attempt(this.parser.constructs.document,o,tt),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function classifyCharacter(et){if(et===null||markdownLineEndingOrSpace(et)||unicodeWhitespace(et))return 1;if(unicodePunctuation(et))return 2}function resolveAll(et,o,tt){const rt=[];let nt=-1;for(;++nt1&&et[tt][1].end.offset-et[tt][1].start.offset>1?2:1;const dt=Object.assign({},et[rt][1].end),ht=Object.assign({},et[tt][1].start);movePoint(dt,-at),movePoint(ht,at),it={type:at>1?"strongSequence":"emphasisSequence",start:dt,end:Object.assign({},et[rt][1].end)},st={type:at>1?"strongSequence":"emphasisSequence",start:Object.assign({},et[tt][1].start),end:ht},ot={type:at>1?"strongText":"emphasisText",start:Object.assign({},et[rt][1].end),end:Object.assign({},et[tt][1].start)},nt={type:at>1?"strong":"emphasis",start:Object.assign({},it.start),end:Object.assign({},st.end)},et[rt][1].end=Object.assign({},it.start),et[tt][1].start=Object.assign({},st.end),ct=[],et[rt][1].end.offset-et[rt][1].start.offset&&(ct=push(ct,[["enter",et[rt][1],o],["exit",et[rt][1],o]])),ct=push(ct,[["enter",nt,o],["enter",it,o],["exit",it,o],["enter",ot,o]]),ct=push(ct,resolveAll(o.parser.constructs.insideSpan.null,et.slice(rt+1,tt),o)),ct=push(ct,[["exit",ot,o],["enter",st,o],["exit",st,o],["exit",nt,o]]),et[tt][1].end.offset-et[tt][1].start.offset?(lt=2,ct=push(ct,[["enter",et[tt][1],o],["exit",et[tt][1],o]])):lt=0,splice(et,rt-1,tt-rt+3,ct),tt=rt+ct.length-lt-2;break}}for(tt=-1;++tt0&&markdownSpace(Ct)?factorySpace(et,bt,"linePrefix",ot+1)(Ct):bt(Ct)}function bt(Ct){return Ct===null||markdownLineEnding(Ct)?et.check(nonLazyContinuation,pt,vt)(Ct):(et.enter("codeFlowValue"),xt(Ct))}function xt(Ct){return Ct===null||markdownLineEnding(Ct)?(et.exit("codeFlowValue"),bt(Ct)):(et.consume(Ct),xt)}function vt(Ct){return et.exit("codeFenced"),o(Ct)}function Et(Ct,St,At){let kt=0;return It;function It(Ht){return Ct.enter("lineEnding"),Ct.consume(Ht),Ct.exit("lineEnding"),Ot}function Ot(Ht){return Ct.enter("codeFencedFence"),markdownSpace(Ht)?factorySpace(Ct,Nt,"linePrefix",rt.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(Ht):Nt(Ht)}function Nt(Ht){return Ht===st?(Ct.enter("codeFencedFenceSequence"),Yt(Ht)):At(Ht)}function Yt(Ht){return Ht===st?(kt++,Ct.consume(Ht),Yt):kt>=it?(Ct.exit("codeFencedFenceSequence"),markdownSpace(Ht)?factorySpace(Ct,Ft,"whitespace")(Ht):Ft(Ht)):At(Ht)}function Ft(Ht){return Ht===null||markdownLineEnding(Ht)?(Ct.exit("codeFencedFence"),St(Ht)):At(Ht)}}}function tokenizeNonLazyContinuation(et,o,tt){const rt=this;return nt;function nt(it){return it===null?tt(it):(et.enter("lineEnding"),et.consume(it),et.exit("lineEnding"),ot)}function ot(it){return rt.parser.lazy[rt.now().line]?tt(it):o(it)}}const codeIndented={name:"codeIndented",tokenize:tokenizeCodeIndented},furtherStart={tokenize:tokenizeFurtherStart,partial:!0};function tokenizeCodeIndented(et,o,tt){const rt=this;return nt;function nt(ct){return et.enter("codeIndented"),factorySpace(et,ot,"linePrefix",5)(ct)}function ot(ct){const lt=rt.events[rt.events.length-1];return lt&<[1].type==="linePrefix"&<[2].sliceSerialize(lt[1],!0).length>=4?it(ct):tt(ct)}function it(ct){return ct===null?at(ct):markdownLineEnding(ct)?et.attempt(furtherStart,it,at)(ct):(et.enter("codeFlowValue"),st(ct))}function st(ct){return ct===null||markdownLineEnding(ct)?(et.exit("codeFlowValue"),it(ct)):(et.consume(ct),st)}function at(ct){return et.exit("codeIndented"),o(ct)}}function tokenizeFurtherStart(et,o,tt){const rt=this;return nt;function nt(it){return rt.parser.lazy[rt.now().line]?tt(it):markdownLineEnding(it)?(et.enter("lineEnding"),et.consume(it),et.exit("lineEnding"),nt):factorySpace(et,ot,"linePrefix",5)(it)}function ot(it){const st=rt.events[rt.events.length-1];return st&&st[1].type==="linePrefix"&&st[2].sliceSerialize(st[1],!0).length>=4?o(it):markdownLineEnding(it)?nt(it):tt(it)}}const codeText={name:"codeText",tokenize:tokenizeCodeText,resolve:resolveCodeText,previous};function resolveCodeText(et){let o=et.length-4,tt=3,rt,nt;if((et[tt][1].type==="lineEnding"||et[tt][1].type==="space")&&(et[o][1].type==="lineEnding"||et[o][1].type==="space")){for(rt=tt;++rt=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+o+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return othis.left.length?this.right.slice(this.right.length-rt+this.left.length,this.right.length-o+this.left.length).reverse():this.left.slice(o).concat(this.right.slice(this.right.length-rt+this.left.length).reverse())}splice(o,tt,rt){const nt=tt||0;this.setCursor(Math.trunc(o));const ot=this.right.splice(this.right.length-nt,Number.POSITIVE_INFINITY);return rt&&chunkedPush(this.left,rt),ot.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(o){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(o)}pushMany(o){this.setCursor(Number.POSITIVE_INFINITY),chunkedPush(this.left,o)}unshift(o){this.setCursor(0),this.right.push(o)}unshiftMany(o){this.setCursor(0),chunkedPush(this.right,o.reverse())}setCursor(o){if(!(o===this.left.length||o>this.left.length&&this.right.length===0||o<0&&this.left.length===0))if(o=4?o(it):et.interrupt(rt.parser.constructs.flow,tt,o)(it)}}function factoryDestination(et,o,tt,rt,nt,ot,it,st,at){const ct=at||Number.POSITIVE_INFINITY;let lt=0;return dt;function dt(yt){return yt===60?(et.enter(rt),et.enter(nt),et.enter(ot),et.consume(yt),et.exit(ot),ht):yt===null||yt===32||yt===41||asciiControl(yt)?tt(yt):(et.enter(rt),et.enter(it),et.enter(st),et.enter("chunkString",{contentType:"string"}),pt(yt))}function ht(yt){return yt===62?(et.enter(ot),et.consume(yt),et.exit(ot),et.exit(nt),et.exit(rt),o):(et.enter(st),et.enter("chunkString",{contentType:"string"}),mt(yt))}function mt(yt){return yt===62?(et.exit("chunkString"),et.exit(st),ht(yt)):yt===null||yt===60||markdownLineEnding(yt)?tt(yt):(et.consume(yt),yt===92?ft:mt)}function ft(yt){return yt===60||yt===62||yt===92?(et.consume(yt),mt):mt(yt)}function pt(yt){return!lt&&(yt===null||yt===41||markdownLineEndingOrSpace(yt))?(et.exit("chunkString"),et.exit(st),et.exit(it),et.exit(rt),o(yt)):lt999||mt===null||mt===91||mt===93&&!at||mt===94&&!st&&"_hiddenFootnoteSupport"in it.parser.constructs?tt(mt):mt===93?(et.exit(ot),et.enter(nt),et.consume(mt),et.exit(nt),et.exit(rt),o):markdownLineEnding(mt)?(et.enter("lineEnding"),et.consume(mt),et.exit("lineEnding"),lt):(et.enter("chunkString",{contentType:"string"}),dt(mt))}function dt(mt){return mt===null||mt===91||mt===93||markdownLineEnding(mt)||st++>999?(et.exit("chunkString"),lt(mt)):(et.consume(mt),at||(at=!markdownSpace(mt)),mt===92?ht:dt)}function ht(mt){return mt===91||mt===92||mt===93?(et.consume(mt),st++,dt):dt(mt)}}function factoryTitle(et,o,tt,rt,nt,ot){let it;return st;function st(ht){return ht===34||ht===39||ht===40?(et.enter(rt),et.enter(nt),et.consume(ht),et.exit(nt),it=ht===40?41:ht,at):tt(ht)}function at(ht){return ht===it?(et.enter(nt),et.consume(ht),et.exit(nt),et.exit(rt),o):(et.enter(ot),ct(ht))}function ct(ht){return ht===it?(et.exit(ot),at(it)):ht===null?tt(ht):markdownLineEnding(ht)?(et.enter("lineEnding"),et.consume(ht),et.exit("lineEnding"),factorySpace(et,ct,"linePrefix")):(et.enter("chunkString",{contentType:"string"}),lt(ht))}function lt(ht){return ht===it||ht===null||markdownLineEnding(ht)?(et.exit("chunkString"),ct(ht)):(et.consume(ht),ht===92?dt:lt)}function dt(ht){return ht===it||ht===92?(et.consume(ht),lt):lt(ht)}}function factoryWhitespace(et,o){let tt;return rt;function rt(nt){return markdownLineEnding(nt)?(et.enter("lineEnding"),et.consume(nt),et.exit("lineEnding"),tt=!0,rt):markdownSpace(nt)?factorySpace(et,rt,tt?"linePrefix":"lineSuffix")(nt):o(nt)}}const definition={name:"definition",tokenize:tokenizeDefinition},titleBefore={tokenize:tokenizeTitleBefore,partial:!0};function tokenizeDefinition(et,o,tt){const rt=this;let nt;return ot;function ot(mt){return et.enter("definition"),it(mt)}function it(mt){return factoryLabel.call(rt,et,st,tt,"definitionLabel","definitionLabelMarker","definitionLabelString")(mt)}function st(mt){return nt=normalizeIdentifier(rt.sliceSerialize(rt.events[rt.events.length-1][1]).slice(1,-1)),mt===58?(et.enter("definitionMarker"),et.consume(mt),et.exit("definitionMarker"),at):tt(mt)}function at(mt){return markdownLineEndingOrSpace(mt)?factoryWhitespace(et,ct)(mt):ct(mt)}function ct(mt){return factoryDestination(et,lt,tt,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(mt)}function lt(mt){return et.attempt(titleBefore,dt,dt)(mt)}function dt(mt){return markdownSpace(mt)?factorySpace(et,ht,"whitespace")(mt):ht(mt)}function ht(mt){return mt===null||markdownLineEnding(mt)?(et.exit("definition"),rt.parser.defined.push(nt),o(mt)):tt(mt)}}function tokenizeTitleBefore(et,o,tt){return rt;function rt(st){return markdownLineEndingOrSpace(st)?factoryWhitespace(et,nt)(st):tt(st)}function nt(st){return factoryTitle(et,ot,tt,"definitionTitle","definitionTitleMarker","definitionTitleString")(st)}function ot(st){return markdownSpace(st)?factorySpace(et,it,"whitespace")(st):it(st)}function it(st){return st===null||markdownLineEnding(st)?o(st):tt(st)}}const hardBreakEscape={name:"hardBreakEscape",tokenize:tokenizeHardBreakEscape};function tokenizeHardBreakEscape(et,o,tt){return rt;function rt(ot){return et.enter("hardBreakEscape"),et.consume(ot),nt}function nt(ot){return markdownLineEnding(ot)?(et.exit("hardBreakEscape"),o(ot)):tt(ot)}}const headingAtx={name:"headingAtx",tokenize:tokenizeHeadingAtx,resolve:resolveHeadingAtx};function resolveHeadingAtx(et,o){let tt=et.length-2,rt=3,nt,ot;return et[rt][1].type==="whitespace"&&(rt+=2),tt-2>rt&&et[tt][1].type==="whitespace"&&(tt-=2),et[tt][1].type==="atxHeadingSequence"&&(rt===tt-1||tt-4>rt&&et[tt-2][1].type==="whitespace")&&(tt-=rt+1===tt?2:4),tt>rt&&(nt={type:"atxHeadingText",start:et[rt][1].start,end:et[tt][1].end},ot={type:"chunkText",start:et[rt][1].start,end:et[tt][1].end,contentType:"text"},splice(et,rt,tt-rt+1,[["enter",nt,o],["enter",ot,o],["exit",ot,o],["exit",nt,o]])),et}function tokenizeHeadingAtx(et,o,tt){let rt=0;return nt;function nt(lt){return et.enter("atxHeading"),ot(lt)}function ot(lt){return et.enter("atxHeadingSequence"),it(lt)}function it(lt){return lt===35&&rt++<6?(et.consume(lt),it):lt===null||markdownLineEndingOrSpace(lt)?(et.exit("atxHeadingSequence"),st(lt)):tt(lt)}function st(lt){return lt===35?(et.enter("atxHeadingSequence"),at(lt)):lt===null||markdownLineEnding(lt)?(et.exit("atxHeading"),o(lt)):markdownSpace(lt)?factorySpace(et,st,"whitespace")(lt):(et.enter("atxHeadingText"),ct(lt))}function at(lt){return lt===35?(et.consume(lt),at):(et.exit("atxHeadingSequence"),st(lt))}function ct(lt){return lt===null||lt===35||markdownLineEndingOrSpace(lt)?(et.exit("atxHeadingText"),st(lt)):(et.consume(lt),ct)}}const htmlBlockNames=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],htmlRawNames=["pre","script","style","textarea"],htmlFlow={name:"htmlFlow",tokenize:tokenizeHtmlFlow,resolveTo:resolveToHtmlFlow,concrete:!0},blankLineBefore={tokenize:tokenizeBlankLineBefore,partial:!0},nonLazyContinuationStart={tokenize:tokenizeNonLazyContinuationStart,partial:!0};function resolveToHtmlFlow(et){let o=et.length;for(;o--&&!(et[o][0]==="enter"&&et[o][1].type==="htmlFlow"););return o>1&&et[o-2][1].type==="linePrefix"&&(et[o][1].start=et[o-2][1].start,et[o+1][1].start=et[o-2][1].start,et.splice(o-2,2)),et}function tokenizeHtmlFlow(et,o,tt){const rt=this;let nt,ot,it,st,at;return ct;function ct(Pt){return lt(Pt)}function lt(Pt){return et.enter("htmlFlow"),et.enter("htmlFlowData"),et.consume(Pt),dt}function dt(Pt){return Pt===33?(et.consume(Pt),ht):Pt===47?(et.consume(Pt),ot=!0,pt):Pt===63?(et.consume(Pt),nt=3,rt.interrupt?o:jt):asciiAlpha(Pt)?(et.consume(Pt),it=String.fromCharCode(Pt),gt):tt(Pt)}function ht(Pt){return Pt===45?(et.consume(Pt),nt=2,mt):Pt===91?(et.consume(Pt),nt=5,st=0,ft):asciiAlpha(Pt)?(et.consume(Pt),nt=4,rt.interrupt?o:jt):tt(Pt)}function mt(Pt){return Pt===45?(et.consume(Pt),rt.interrupt?o:jt):tt(Pt)}function ft(Pt){const Gt="CDATA[";return Pt===Gt.charCodeAt(st++)?(et.consume(Pt),st===Gt.length?rt.interrupt?o:Nt:ft):tt(Pt)}function pt(Pt){return asciiAlpha(Pt)?(et.consume(Pt),it=String.fromCharCode(Pt),gt):tt(Pt)}function gt(Pt){if(Pt===null||Pt===47||Pt===62||markdownLineEndingOrSpace(Pt)){const Gt=Pt===47,tr=it.toLowerCase();return!Gt&&!ot&&htmlRawNames.includes(tr)?(nt=1,rt.interrupt?o(Pt):Nt(Pt)):htmlBlockNames.includes(it.toLowerCase())?(nt=6,Gt?(et.consume(Pt),yt):rt.interrupt?o(Pt):Nt(Pt)):(nt=7,rt.interrupt&&!rt.parser.lazy[rt.now().line]?tt(Pt):ot?bt(Pt):xt(Pt))}return Pt===45||asciiAlphanumeric(Pt)?(et.consume(Pt),it+=String.fromCharCode(Pt),gt):tt(Pt)}function yt(Pt){return Pt===62?(et.consume(Pt),rt.interrupt?o:Nt):tt(Pt)}function bt(Pt){return markdownSpace(Pt)?(et.consume(Pt),bt):It(Pt)}function xt(Pt){return Pt===47?(et.consume(Pt),It):Pt===58||Pt===95||asciiAlpha(Pt)?(et.consume(Pt),vt):markdownSpace(Pt)?(et.consume(Pt),xt):It(Pt)}function vt(Pt){return Pt===45||Pt===46||Pt===58||Pt===95||asciiAlphanumeric(Pt)?(et.consume(Pt),vt):Et(Pt)}function Et(Pt){return Pt===61?(et.consume(Pt),Ct):markdownSpace(Pt)?(et.consume(Pt),Et):xt(Pt)}function Ct(Pt){return Pt===null||Pt===60||Pt===61||Pt===62||Pt===96?tt(Pt):Pt===34||Pt===39?(et.consume(Pt),at=Pt,St):markdownSpace(Pt)?(et.consume(Pt),Ct):At(Pt)}function St(Pt){return Pt===at?(et.consume(Pt),at=null,kt):Pt===null||markdownLineEnding(Pt)?tt(Pt):(et.consume(Pt),St)}function At(Pt){return Pt===null||Pt===34||Pt===39||Pt===47||Pt===60||Pt===61||Pt===62||Pt===96||markdownLineEndingOrSpace(Pt)?Et(Pt):(et.consume(Pt),At)}function kt(Pt){return Pt===47||Pt===62||markdownSpace(Pt)?xt(Pt):tt(Pt)}function It(Pt){return Pt===62?(et.consume(Pt),Ot):tt(Pt)}function Ot(Pt){return Pt===null||markdownLineEnding(Pt)?Nt(Pt):markdownSpace(Pt)?(et.consume(Pt),Ot):tt(Pt)}function Nt(Pt){return Pt===45&&nt===2?(et.consume(Pt),Qt):Pt===60&&nt===1?(et.consume(Pt),Vt):Pt===62&&nt===4?(et.consume(Pt),Xt):Pt===63&&nt===3?(et.consume(Pt),jt):Pt===93&&nt===5?(et.consume(Pt),Wt):markdownLineEnding(Pt)&&(nt===6||nt===7)?(et.exit("htmlFlowData"),et.check(blankLineBefore,Kt,Yt)(Pt)):Pt===null||markdownLineEnding(Pt)?(et.exit("htmlFlowData"),Yt(Pt)):(et.consume(Pt),Nt)}function Yt(Pt){return et.check(nonLazyContinuationStart,Ft,Kt)(Pt)}function Ft(Pt){return et.enter("lineEnding"),et.consume(Pt),et.exit("lineEnding"),Ht}function Ht(Pt){return Pt===null||markdownLineEnding(Pt)?Yt(Pt):(et.enter("htmlFlowData"),Nt(Pt))}function Qt(Pt){return Pt===45?(et.consume(Pt),jt):Nt(Pt)}function Vt(Pt){return Pt===47?(et.consume(Pt),it="",Bt):Nt(Pt)}function Bt(Pt){if(Pt===62){const Gt=it.toLowerCase();return htmlRawNames.includes(Gt)?(et.consume(Pt),Xt):Nt(Pt)}return asciiAlpha(Pt)&&it.length<8?(et.consume(Pt),it+=String.fromCharCode(Pt),Bt):Nt(Pt)}function Wt(Pt){return Pt===93?(et.consume(Pt),jt):Nt(Pt)}function jt(Pt){return Pt===62?(et.consume(Pt),Xt):Pt===45&&nt===2?(et.consume(Pt),jt):Nt(Pt)}function Xt(Pt){return Pt===null||markdownLineEnding(Pt)?(et.exit("htmlFlowData"),Kt(Pt)):(et.consume(Pt),Xt)}function Kt(Pt){return et.exit("htmlFlow"),o(Pt)}}function tokenizeNonLazyContinuationStart(et,o,tt){const rt=this;return nt;function nt(it){return markdownLineEnding(it)?(et.enter("lineEnding"),et.consume(it),et.exit("lineEnding"),ot):tt(it)}function ot(it){return rt.parser.lazy[rt.now().line]?tt(it):o(it)}}function tokenizeBlankLineBefore(et,o,tt){return rt;function rt(nt){return et.enter("lineEnding"),et.consume(nt),et.exit("lineEnding"),et.attempt(blankLine,o,tt)}}const htmlText={name:"htmlText",tokenize:tokenizeHtmlText};function tokenizeHtmlText(et,o,tt){const rt=this;let nt,ot,it;return st;function st(jt){return et.enter("htmlText"),et.enter("htmlTextData"),et.consume(jt),at}function at(jt){return jt===33?(et.consume(jt),ct):jt===47?(et.consume(jt),Et):jt===63?(et.consume(jt),xt):asciiAlpha(jt)?(et.consume(jt),At):tt(jt)}function ct(jt){return jt===45?(et.consume(jt),lt):jt===91?(et.consume(jt),ot=0,ft):asciiAlpha(jt)?(et.consume(jt),bt):tt(jt)}function lt(jt){return jt===45?(et.consume(jt),mt):tt(jt)}function dt(jt){return jt===null?tt(jt):jt===45?(et.consume(jt),ht):markdownLineEnding(jt)?(it=dt,Vt(jt)):(et.consume(jt),dt)}function ht(jt){return jt===45?(et.consume(jt),mt):dt(jt)}function mt(jt){return jt===62?Qt(jt):jt===45?ht(jt):dt(jt)}function ft(jt){const Xt="CDATA[";return jt===Xt.charCodeAt(ot++)?(et.consume(jt),ot===Xt.length?pt:ft):tt(jt)}function pt(jt){return jt===null?tt(jt):jt===93?(et.consume(jt),gt):markdownLineEnding(jt)?(it=pt,Vt(jt)):(et.consume(jt),pt)}function gt(jt){return jt===93?(et.consume(jt),yt):pt(jt)}function yt(jt){return jt===62?Qt(jt):jt===93?(et.consume(jt),yt):pt(jt)}function bt(jt){return jt===null||jt===62?Qt(jt):markdownLineEnding(jt)?(it=bt,Vt(jt)):(et.consume(jt),bt)}function xt(jt){return jt===null?tt(jt):jt===63?(et.consume(jt),vt):markdownLineEnding(jt)?(it=xt,Vt(jt)):(et.consume(jt),xt)}function vt(jt){return jt===62?Qt(jt):xt(jt)}function Et(jt){return asciiAlpha(jt)?(et.consume(jt),Ct):tt(jt)}function Ct(jt){return jt===45||asciiAlphanumeric(jt)?(et.consume(jt),Ct):St(jt)}function St(jt){return markdownLineEnding(jt)?(it=St,Vt(jt)):markdownSpace(jt)?(et.consume(jt),St):Qt(jt)}function At(jt){return jt===45||asciiAlphanumeric(jt)?(et.consume(jt),At):jt===47||jt===62||markdownLineEndingOrSpace(jt)?kt(jt):tt(jt)}function kt(jt){return jt===47?(et.consume(jt),Qt):jt===58||jt===95||asciiAlpha(jt)?(et.consume(jt),It):markdownLineEnding(jt)?(it=kt,Vt(jt)):markdownSpace(jt)?(et.consume(jt),kt):Qt(jt)}function It(jt){return jt===45||jt===46||jt===58||jt===95||asciiAlphanumeric(jt)?(et.consume(jt),It):Ot(jt)}function Ot(jt){return jt===61?(et.consume(jt),Nt):markdownLineEnding(jt)?(it=Ot,Vt(jt)):markdownSpace(jt)?(et.consume(jt),Ot):kt(jt)}function Nt(jt){return jt===null||jt===60||jt===61||jt===62||jt===96?tt(jt):jt===34||jt===39?(et.consume(jt),nt=jt,Yt):markdownLineEnding(jt)?(it=Nt,Vt(jt)):markdownSpace(jt)?(et.consume(jt),Nt):(et.consume(jt),Ft)}function Yt(jt){return jt===nt?(et.consume(jt),nt=void 0,Ht):jt===null?tt(jt):markdownLineEnding(jt)?(it=Yt,Vt(jt)):(et.consume(jt),Yt)}function Ft(jt){return jt===null||jt===34||jt===39||jt===60||jt===61||jt===96?tt(jt):jt===47||jt===62||markdownLineEndingOrSpace(jt)?kt(jt):(et.consume(jt),Ft)}function Ht(jt){return jt===47||jt===62||markdownLineEndingOrSpace(jt)?kt(jt):tt(jt)}function Qt(jt){return jt===62?(et.consume(jt),et.exit("htmlTextData"),et.exit("htmlText"),o):tt(jt)}function Vt(jt){return et.exit("htmlTextData"),et.enter("lineEnding"),et.consume(jt),et.exit("lineEnding"),Bt}function Bt(jt){return markdownSpace(jt)?factorySpace(et,Wt,"linePrefix",rt.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(jt):Wt(jt)}function Wt(jt){return et.enter("htmlTextData"),it(jt)}}const labelEnd={name:"labelEnd",tokenize:tokenizeLabelEnd,resolveTo:resolveToLabelEnd,resolveAll:resolveAllLabelEnd},resourceConstruct={tokenize:tokenizeResource},referenceFullConstruct={tokenize:tokenizeReferenceFull},referenceCollapsedConstruct={tokenize:tokenizeReferenceCollapsed};function resolveAllLabelEnd(et){let o=-1;for(;++o=3&&(ct===null||markdownLineEnding(ct))?(et.exit("thematicBreak"),o(ct)):tt(ct)}function at(ct){return ct===nt?(et.consume(ct),rt++,at):(et.exit("thematicBreakSequence"),markdownSpace(ct)?factorySpace(et,st,"whitespace")(ct):st(ct))}}const list$1={name:"list",tokenize:tokenizeListStart,continuation:{tokenize:tokenizeListContinuation},exit:tokenizeListEnd},listItemPrefixWhitespaceConstruct={tokenize:tokenizeListItemPrefixWhitespace,partial:!0},indentConstruct={tokenize:tokenizeIndent,partial:!0};function tokenizeListStart(et,o,tt){const rt=this,nt=rt.events[rt.events.length-1];let ot=nt&&nt[1].type==="linePrefix"?nt[2].sliceSerialize(nt[1],!0).length:0,it=0;return st;function st(mt){const ft=rt.containerState.type||(mt===42||mt===43||mt===45?"listUnordered":"listOrdered");if(ft==="listUnordered"?!rt.containerState.marker||mt===rt.containerState.marker:asciiDigit(mt)){if(rt.containerState.type||(rt.containerState.type=ft,et.enter(ft,{_container:!0})),ft==="listUnordered")return et.enter("listItemPrefix"),mt===42||mt===45?et.check(thematicBreak$1,tt,ct)(mt):ct(mt);if(!rt.interrupt||mt===49)return et.enter("listItemPrefix"),et.enter("listItemValue"),at(mt)}return tt(mt)}function at(mt){return asciiDigit(mt)&&++it<10?(et.consume(mt),at):(!rt.interrupt||it<2)&&(rt.containerState.marker?mt===rt.containerState.marker:mt===41||mt===46)?(et.exit("listItemValue"),ct(mt)):tt(mt)}function ct(mt){return et.enter("listItemMarker"),et.consume(mt),et.exit("listItemMarker"),rt.containerState.marker=rt.containerState.marker||mt,et.check(blankLine,rt.interrupt?tt:lt,et.attempt(listItemPrefixWhitespaceConstruct,ht,dt))}function lt(mt){return rt.containerState.initialBlankLine=!0,ot++,ht(mt)}function dt(mt){return markdownSpace(mt)?(et.enter("listItemPrefixWhitespace"),et.consume(mt),et.exit("listItemPrefixWhitespace"),ht):tt(mt)}function ht(mt){return rt.containerState.size=ot+rt.sliceSerialize(et.exit("listItemPrefix"),!0).length,o(mt)}}function tokenizeListContinuation(et,o,tt){const rt=this;return rt.containerState._closeFlow=void 0,et.check(blankLine,nt,ot);function nt(st){return rt.containerState.furtherBlankLines=rt.containerState.furtherBlankLines||rt.containerState.initialBlankLine,factorySpace(et,o,"listItemIndent",rt.containerState.size+1)(st)}function ot(st){return rt.containerState.furtherBlankLines||!markdownSpace(st)?(rt.containerState.furtherBlankLines=void 0,rt.containerState.initialBlankLine=void 0,it(st)):(rt.containerState.furtherBlankLines=void 0,rt.containerState.initialBlankLine=void 0,et.attempt(indentConstruct,o,it)(st))}function it(st){return rt.containerState._closeFlow=!0,rt.interrupt=void 0,factorySpace(et,et.attempt(list$1,o,tt),"linePrefix",rt.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(st)}}function tokenizeIndent(et,o,tt){const rt=this;return factorySpace(et,nt,"listItemIndent",rt.containerState.size+1);function nt(ot){const it=rt.events[rt.events.length-1];return it&&it[1].type==="listItemIndent"&&it[2].sliceSerialize(it[1],!0).length===rt.containerState.size?o(ot):tt(ot)}}function tokenizeListEnd(et){et.exit(this.containerState.type)}function tokenizeListItemPrefixWhitespace(et,o,tt){const rt=this;return factorySpace(et,nt,"listItemPrefixWhitespace",rt.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function nt(ot){const it=rt.events[rt.events.length-1];return!markdownSpace(ot)&&it&&it[1].type==="listItemPrefixWhitespace"?o(ot):tt(ot)}}const setextUnderline={name:"setextUnderline",tokenize:tokenizeSetextUnderline,resolveTo:resolveToSetextUnderline};function resolveToSetextUnderline(et,o){let tt=et.length,rt,nt,ot;for(;tt--;)if(et[tt][0]==="enter"){if(et[tt][1].type==="content"){rt=tt;break}et[tt][1].type==="paragraph"&&(nt=tt)}else et[tt][1].type==="content"&&et.splice(tt,1),!ot&&et[tt][1].type==="definition"&&(ot=tt);const it={type:"setextHeading",start:Object.assign({},et[nt][1].start),end:Object.assign({},et[et.length-1][1].end)};return et[nt][1].type="setextHeadingText",ot?(et.splice(nt,0,["enter",it,o]),et.splice(ot+1,0,["exit",et[rt][1],o]),et[rt][1].end=Object.assign({},et[ot][1].end)):et[rt][1]=it,et.push(["exit",it,o]),et}function tokenizeSetextUnderline(et,o,tt){const rt=this;let nt;return ot;function ot(ct){let lt=rt.events.length,dt;for(;lt--;)if(rt.events[lt][1].type!=="lineEnding"&&rt.events[lt][1].type!=="linePrefix"&&rt.events[lt][1].type!=="content"){dt=rt.events[lt][1].type==="paragraph";break}return!rt.parser.lazy[rt.now().line]&&(rt.interrupt||dt)?(et.enter("setextHeadingLine"),nt=ct,it(ct)):tt(ct)}function it(ct){return et.enter("setextHeadingLineSequence"),st(ct)}function st(ct){return ct===nt?(et.consume(ct),st):(et.exit("setextHeadingLineSequence"),markdownSpace(ct)?factorySpace(et,at,"lineSuffix")(ct):at(ct))}function at(ct){return ct===null||markdownLineEnding(ct)?(et.exit("setextHeadingLine"),o(ct)):tt(ct)}}const flow$1={tokenize:initializeFlow};function initializeFlow(et){const o=this,tt=et.attempt(blankLine,rt,et.attempt(this.parser.constructs.flowInitial,nt,factorySpace(et,et.attempt(this.parser.constructs.flow,nt,et.attempt(content,nt)),"linePrefix")));return tt;function rt(ot){if(ot===null){et.consume(ot);return}return et.enter("lineEndingBlank"),et.consume(ot),et.exit("lineEndingBlank"),o.currentConstruct=void 0,tt}function nt(ot){if(ot===null){et.consume(ot);return}return et.enter("lineEnding"),et.consume(ot),et.exit("lineEnding"),o.currentConstruct=void 0,tt}}const resolver={resolveAll:createResolver()},string$1=initializeFactory("string"),text$2=initializeFactory("text");function initializeFactory(et){return{tokenize:o,resolveAll:createResolver(et==="text"?resolveAllLineSuffixes:void 0)};function o(tt){const rt=this,nt=this.parser.constructs[et],ot=tt.attempt(nt,it,st);return it;function it(lt){return ct(lt)?ot(lt):st(lt)}function st(lt){if(lt===null){tt.consume(lt);return}return tt.enter("data"),tt.consume(lt),at}function at(lt){return ct(lt)?(tt.exit("data"),ot(lt)):(tt.consume(lt),at)}function ct(lt){if(lt===null)return!0;const dt=nt[lt];let ht=-1;if(dt)for(;++ht-1){const st=it[0];typeof st=="string"?it[0]=st.slice(rt):it.shift()}ot>0&&it.push(et[nt].slice(0,ot))}return it}function serializeChunks(et,o){let tt=-1;const rt=[];let nt;for(;++tt0){const qt=$t.tokenStack[$t.tokenStack.length-1];(qt[1]||defaultOnError).call($t,void 0,qt[0])}for(Tt.position={start:point(ir.length>0?ir[0][1].start:{line:1,column:1,offset:0}),end:point(ir.length>0?ir[ir.length-2][1].end:{line:1,column:1,offset:0})},Dt=-1;++Dt1?"-"+st:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(it)}]};et.patch(o,at);const ct={type:"element",tagName:"sup",properties:{},children:[at]};return et.patch(o,ct),et.applyData(o,ct)}function heading(et,o){const tt={type:"element",tagName:"h"+o.depth,properties:{},children:et.all(o)};return et.patch(o,tt),et.applyData(o,tt)}function html(et,o){if(et.options.allowDangerousHtml){const tt={type:"raw",value:o.value};return et.patch(o,tt),et.applyData(o,tt)}}function revert(et,o){const tt=o.referenceType;let rt="]";if(tt==="collapsed"?rt+="[]":tt==="full"&&(rt+="["+(o.label||o.identifier)+"]"),o.type==="imageReference")return[{type:"text",value:"!["+o.alt+rt}];const nt=et.all(o),ot=nt[0];ot&&ot.type==="text"?ot.value="["+ot.value:nt.unshift({type:"text",value:"["});const it=nt[nt.length-1];return it&&it.type==="text"?it.value+=rt:nt.push({type:"text",value:rt}),nt}function imageReference(et,o){const tt=String(o.identifier).toUpperCase(),rt=et.definitionById.get(tt);if(!rt)return revert(et,o);const nt={src:normalizeUri(rt.url||""),alt:o.alt};rt.title!==null&&rt.title!==void 0&&(nt.title=rt.title);const ot={type:"element",tagName:"img",properties:nt,children:[]};return et.patch(o,ot),et.applyData(o,ot)}function image(et,o){const tt={src:normalizeUri(o.url)};o.alt!==null&&o.alt!==void 0&&(tt.alt=o.alt),o.title!==null&&o.title!==void 0&&(tt.title=o.title);const rt={type:"element",tagName:"img",properties:tt,children:[]};return et.patch(o,rt),et.applyData(o,rt)}function inlineCode(et,o){const tt={type:"text",value:o.value.replace(/\r?\n|\r/g," ")};et.patch(o,tt);const rt={type:"element",tagName:"code",properties:{},children:[tt]};return et.patch(o,rt),et.applyData(o,rt)}function linkReference(et,o){const tt=String(o.identifier).toUpperCase(),rt=et.definitionById.get(tt);if(!rt)return revert(et,o);const nt={href:normalizeUri(rt.url||"")};rt.title!==null&&rt.title!==void 0&&(nt.title=rt.title);const ot={type:"element",tagName:"a",properties:nt,children:et.all(o)};return et.patch(o,ot),et.applyData(o,ot)}function link(et,o){const tt={href:normalizeUri(o.url)};o.title!==null&&o.title!==void 0&&(tt.title=o.title);const rt={type:"element",tagName:"a",properties:tt,children:et.all(o)};return et.patch(o,rt),et.applyData(o,rt)}function listItem(et,o,tt){const rt=et.all(o),nt=tt?listLoose(tt):listItemLoose(o),ot={},it=[];if(typeof o.checked=="boolean"){const lt=rt[0];let dt;lt&<.type==="element"&<.tagName==="p"?dt=lt:(dt={type:"element",tagName:"p",properties:{},children:[]},rt.unshift(dt)),dt.children.length>0&&dt.children.unshift({type:"text",value:" "}),dt.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:o.checked,disabled:!0},children:[]}),ot.className=["task-list-item"]}let st=-1;for(;++st1}function list(et,o){const tt={},rt=et.all(o);let nt=-1;for(typeof o.start=="number"&&o.start!==1&&(tt.start=o.start);++nt0){const it={type:"element",tagName:"tbody",properties:{},children:et.wrap(tt,!0)},st=pointStart(o.children[1]),at=pointEnd(o.children[o.children.length-1]);st&&at&&(it.position={start:st,end:at}),nt.push(it)}const ot={type:"element",tagName:"table",properties:{},children:et.wrap(nt,!0)};return et.patch(o,ot),et.applyData(o,ot)}function tableRow(et,o,tt){const rt=tt?tt.children:void 0,ot=(rt?rt.indexOf(o):1)===0?"th":"td",it=tt&&tt.type==="table"?tt.align:void 0,st=it?it.length:o.children.length;let at=-1;const ct=[];for(;++at0,!0),rt[0]),nt=rt.index+rt[0].length,rt=tt.exec(o);return ot.push(trimLine(o.slice(nt),nt>0,!1)),ot.join("")}function trimLine(et,o,tt){let rt=0,nt=et.length;if(o){let ot=et.codePointAt(rt);for(;ot===tab||ot===space;)rt++,ot=et.codePointAt(rt)}if(tt){let ot=et.codePointAt(nt-1);for(;ot===tab||ot===space;)nt--,ot=et.codePointAt(nt-1)}return nt>rt?et.slice(rt,nt):""}function text(et,o){const tt={type:"text",value:trimLines(String(o.value))};return et.patch(o,tt),et.applyData(o,tt)}function thematicBreak(et,o){const tt={type:"element",tagName:"hr",properties:{},children:[]};return et.patch(o,tt),et.applyData(o,tt)}const handlers={blockquote,break:hardBreak,code,delete:strikethrough,emphasis,footnoteReference,heading,html,imageReference,image,inlineCode,linkReference,link,listItem,list,paragraph,root,strong,table,tableCell,tableRow,text,thematicBreak,toml:ignore,yaml:ignore,definition:ignore,footnoteDefinition:ignore};function ignore(){}const VOID=-1,PRIMITIVE=0,ARRAY=1,OBJECT=2,DATE=3,REGEXP=4,MAP=5,SET=6,ERROR=7,BIGINT=8,env$1=typeof self=="object"?self:globalThis,deserializer=(et,o)=>{const tt=(nt,ot)=>(et.set(ot,nt),nt),rt=nt=>{if(et.has(nt))return et.get(nt);const[ot,it]=o[nt];switch(ot){case PRIMITIVE:case VOID:return tt(it,nt);case ARRAY:{const st=tt([],nt);for(const at of it)st.push(rt(at));return st}case OBJECT:{const st=tt({},nt);for(const[at,ct]of it)st[rt(at)]=rt(ct);return st}case DATE:return tt(new Date(it),nt);case REGEXP:{const{source:st,flags:at}=it;return tt(new RegExp(st,at),nt)}case MAP:{const st=tt(new Map,nt);for(const[at,ct]of it)st.set(rt(at),rt(ct));return st}case SET:{const st=tt(new Set,nt);for(const at of it)st.add(rt(at));return st}case ERROR:{const{name:st,message:at}=it;return tt(new env$1[st](at),nt)}case BIGINT:return tt(BigInt(it),nt);case"BigInt":return tt(Object(BigInt(it)),nt)}return tt(new env$1[ot](it),nt)};return rt},deserialize=et=>deserializer(new Map,et)(0),EMPTY="",{toString}={},{keys}=Object,typeOf=et=>{const o=typeof et;if(o!=="object"||!et)return[PRIMITIVE,o];const tt=toString.call(et).slice(8,-1);switch(tt){case"Array":return[ARRAY,EMPTY];case"Object":return[OBJECT,EMPTY];case"Date":return[DATE,EMPTY];case"RegExp":return[REGEXP,EMPTY];case"Map":return[MAP,EMPTY];case"Set":return[SET,EMPTY]}return tt.includes("Array")?[ARRAY,tt]:tt.includes("Error")?[ERROR,tt]:[OBJECT,tt]},shouldSkip=([et,o])=>et===PRIMITIVE&&(o==="function"||o==="symbol"),serializer=(et,o,tt,rt)=>{const nt=(it,st)=>{const at=rt.push(it)-1;return tt.set(st,at),at},ot=it=>{if(tt.has(it))return tt.get(it);let[st,at]=typeOf(it);switch(st){case PRIMITIVE:{let lt=it;switch(at){case"bigint":st=BIGINT,lt=it.toString();break;case"function":case"symbol":if(et)throw new TypeError("unable to serialize "+at);lt=null;break;case"undefined":return nt([VOID],it)}return nt([st,lt],it)}case ARRAY:{if(at)return nt([at,[...it]],it);const lt=[],dt=nt([st,lt],it);for(const ht of it)lt.push(ot(ht));return dt}case OBJECT:{if(at)switch(at){case"BigInt":return nt([at,it.toString()],it);case"Boolean":case"Number":case"String":return nt([at,it.valueOf()],it)}if(o&&"toJSON"in it)return ot(it.toJSON());const lt=[],dt=nt([st,lt],it);for(const ht of keys(it))(et||!shouldSkip(typeOf(it[ht])))&<.push([ot(ht),ot(it[ht])]);return dt}case DATE:return nt([st,it.toISOString()],it);case REGEXP:{const{source:lt,flags:dt}=it;return nt([st,{source:lt,flags:dt}],it)}case MAP:{const lt=[],dt=nt([st,lt],it);for(const[ht,mt]of it)(et||!(shouldSkip(typeOf(ht))||shouldSkip(typeOf(mt))))&<.push([ot(ht),ot(mt)]);return dt}case SET:{const lt=[],dt=nt([st,lt],it);for(const ht of it)(et||!shouldSkip(typeOf(ht)))&<.push(ot(ht));return dt}}const{message:ct}=it;return nt([st,{name:at,message:ct}],it)};return ot},serialize=(et,{json:o,lossy:tt}={})=>{const rt=[];return serializer(!(o||tt),!!o,new Map,rt)(et),rt},structuredClone$1=typeof structuredClone=="function"?(et,o)=>o&&("json"in o||"lossy"in o)?deserialize(serialize(et,o)):structuredClone(et):(et,o)=>deserialize(serialize(et,o));function defaultFootnoteBackContent(et,o){const tt=[{type:"text",value:"↩"}];return o>1&&tt.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(o)}]}),tt}function defaultFootnoteBackLabel(et,o){return"Back to reference "+(et+1)+(o>1?"-"+o:"")}function footer(et){const o=typeof et.options.clobberPrefix=="string"?et.options.clobberPrefix:"user-content-",tt=et.options.footnoteBackContent||defaultFootnoteBackContent,rt=et.options.footnoteBackLabel||defaultFootnoteBackLabel,nt=et.options.footnoteLabel||"Footnotes",ot=et.options.footnoteLabelTagName||"h2",it=et.options.footnoteLabelProperties||{className:["sr-only"]},st=[];let at=-1;for(;++at0&&ft.push({type:"text",value:" "});let bt=typeof tt=="string"?tt:tt(at,mt);typeof bt=="string"&&(bt={type:"text",value:bt}),ft.push({type:"element",tagName:"a",properties:{href:"#"+o+"fnref-"+ht+(mt>1?"-"+mt:""),dataFootnoteBackref:"",ariaLabel:typeof rt=="string"?rt:rt(at,mt),className:["data-footnote-backref"]},children:Array.isArray(bt)?bt:[bt]})}const gt=lt[lt.length-1];if(gt&>.type==="element"&>.tagName==="p"){const bt=gt.children[gt.children.length-1];bt&&bt.type==="text"?bt.value+=" ":gt.children.push({type:"text",value:" "}),gt.children.push(...ft)}else lt.push(...ft);const yt={type:"element",tagName:"li",properties:{id:o+"fn-"+ht},children:et.wrap(lt,!0)};et.patch(ct,yt),st.push(yt)}if(st.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:ot,properties:{...structuredClone$1(it),id:"footnote-label"},children:[{type:"text",value:nt}]},{type:"text",value:` +`},{type:"element",tagName:"ol",properties:{},children:et.wrap(st,!0)},{type:"text",value:` +`}]}}const convert=function(et){if(et==null)return ok;if(typeof et=="function")return castFactory(et);if(typeof et=="object")return Array.isArray(et)?anyFactory(et):propsFactory(et);if(typeof et=="string")return typeFactory(et);throw new Error("Expected function, string, or object as test")};function anyFactory(et){const o=[];let tt=-1;for(;++tt":""))+")"})}return ht;function ht(){let mt=empty,ft,pt,gt;if((!o||ot(at,ct,lt[lt.length-1]||void 0))&&(mt=toResult(tt(at,lt)),mt[0]===EXIT))return mt;if("children"in at&&at.children){const yt=at;if(yt.children&&mt[0]!==SKIP)for(pt=(rt?yt.children.length:-1)+it,gt=lt.concat(yt);pt>-1&&pt0&&tt.push({type:"text",value:` +`}),tt}function trimMarkdownSpaceStart(et){let o=0,tt=et.charCodeAt(o);for(;tt===9||tt===32;)o++,tt=et.charCodeAt(o);return et.slice(o)}function toHast(et,o){const tt=createState(et,o),rt=tt.one(et,void 0),nt=footer(tt),ot=Array.isArray(rt)?{type:"root",children:rt}:rt||{type:"root",children:[]};return nt&&ot.children.push({type:"text",value:` +`},nt),ot}function remarkRehype(et,o){return et&&"run"in et?async function(tt,rt){const nt=toHast(tt,{file:rt,...o});await et.run(nt,rt)}:function(tt,rt){return toHast(tt,{file:rt,...et||o})}}function bail(et){if(et)throw et}var hasOwn=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function et(o){return typeof Array.isArray=="function"?Array.isArray(o):toStr.call(o)==="[object Array]"},isPlainObject$1=function et(o){if(!o||toStr.call(o)!=="[object Object]")return!1;var tt=hasOwn.call(o,"constructor"),rt=o.constructor&&o.constructor.prototype&&hasOwn.call(o.constructor.prototype,"isPrototypeOf");if(o.constructor&&!tt&&!rt)return!1;var nt;for(nt in o);return typeof nt>"u"||hasOwn.call(o,nt)},setProperty=function et(o,tt){defineProperty&&tt.name==="__proto__"?defineProperty(o,tt.name,{enumerable:!0,configurable:!0,value:tt.newValue,writable:!0}):o[tt.name]=tt.newValue},getProperty=function et(o,tt){if(tt==="__proto__")if(hasOwn.call(o,tt)){if(gOPD)return gOPD(o,tt).value}else return;return o[tt]},extend=function et(){var o,tt,rt,nt,ot,it,st=arguments[0],at=1,ct=arguments.length,lt=!1;for(typeof st=="boolean"&&(lt=st,st=arguments[1]||{},at=2),(st==null||typeof st!="object"&&typeof st!="function")&&(st={});atit.length;let at;st&&it.push(nt);try{at=et.apply(this,it)}catch(ct){const lt=ct;if(st&&tt)throw lt;return nt(lt)}st||(at&&at.then&&typeof at.then=="function"?at.then(ot,nt):at instanceof Error?nt(at):ot(at))}function nt(it,...st){tt||(tt=!0,o(it,...st))}function ot(it){nt(null,it)}}const minpath={basename,dirname,extname,join,sep:"/"};function basename(et,o){if(o!==void 0&&typeof o!="string")throw new TypeError('"ext" argument must be a string');assertPath$1(et);let tt=0,rt=-1,nt=et.length,ot;if(o===void 0||o.length===0||o.length>et.length){for(;nt--;)if(et.codePointAt(nt)===47){if(ot){tt=nt+1;break}}else rt<0&&(ot=!0,rt=nt+1);return rt<0?"":et.slice(tt,rt)}if(o===et)return"";let it=-1,st=o.length-1;for(;nt--;)if(et.codePointAt(nt)===47){if(ot){tt=nt+1;break}}else it<0&&(ot=!0,it=nt+1),st>-1&&(et.codePointAt(nt)===o.codePointAt(st--)?st<0&&(rt=nt):(st=-1,rt=it));return tt===rt?rt=it:rt<0&&(rt=et.length),et.slice(tt,rt)}function dirname(et){if(assertPath$1(et),et.length===0)return".";let o=-1,tt=et.length,rt;for(;--tt;)if(et.codePointAt(tt)===47){if(rt){o=tt;break}}else rt||(rt=!0);return o<0?et.codePointAt(0)===47?"/":".":o===1&&et.codePointAt(0)===47?"//":et.slice(0,o)}function extname(et){assertPath$1(et);let o=et.length,tt=-1,rt=0,nt=-1,ot=0,it;for(;o--;){const st=et.codePointAt(o);if(st===47){if(it){rt=o+1;break}continue}tt<0&&(it=!0,tt=o+1),st===46?nt<0?nt=o:ot!==1&&(ot=1):nt>-1&&(ot=-1)}return nt<0||tt<0||ot===0||ot===1&&nt===tt-1&&nt===rt+1?"":et.slice(nt,tt)}function join(...et){let o=-1,tt;for(;++o0&&et.codePointAt(et.length-1)===47&&(tt+="/"),o?"/"+tt:tt}function normalizeString(et,o){let tt="",rt=0,nt=-1,ot=0,it=-1,st,at;for(;++it<=et.length;){if(it2){if(at=tt.lastIndexOf("/"),at!==tt.length-1){at<0?(tt="",rt=0):(tt=tt.slice(0,at),rt=tt.length-1-tt.lastIndexOf("/")),nt=it,ot=0;continue}}else if(tt.length>0){tt="",rt=0,nt=it,ot=0;continue}}o&&(tt=tt.length>0?tt+"/..":"..",rt=2)}else tt.length>0?tt+="/"+et.slice(nt+1,it):tt=et.slice(nt+1,it),rt=it-nt-1;nt=it,ot=0}else st===46&&ot>-1?ot++:ot=-1}return tt}function assertPath$1(et){if(typeof et!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(et))}const minproc={cwd};function cwd(){return"/"}function isUrl(et){return!!(et!==null&&typeof et=="object"&&"href"in et&&et.href&&"protocol"in et&&et.protocol&&et.auth===void 0)}function urlToPath(et){if(typeof et=="string")et=new URL(et);else if(!isUrl(et)){const o=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+et+"`");throw o.code="ERR_INVALID_ARG_TYPE",o}if(et.protocol!=="file:"){const o=new TypeError("The URL must be of scheme file");throw o.code="ERR_INVALID_URL_SCHEME",o}return getPathFromURLPosix(et)}function getPathFromURLPosix(et){if(et.hostname!==""){const rt=new TypeError('File URL host must be "localhost" or empty on darwin');throw rt.code="ERR_INVALID_FILE_URL_HOST",rt}const o=et.pathname;let tt=-1;for(;++tt0){let[mt,...ft]=lt;const pt=rt[ht][1];isPlainObject(pt)&&isPlainObject(mt)&&(mt=extend$1(!0,pt,mt)),rt[ht]=[ct,mt,...ft]}}}}const unified=new Processor().freeze();function assertParser(et,o){if(typeof o!="function")throw new TypeError("Cannot `"+et+"` without `parser`")}function assertCompiler(et,o){if(typeof o!="function")throw new TypeError("Cannot `"+et+"` without `compiler`")}function assertUnfrozen(et,o){if(o)throw new Error("Cannot call `"+et+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function assertNode(et){if(!isPlainObject(et)||typeof et.type!="string")throw new TypeError("Expected node, got `"+et+"`")}function assertDone(et,o,tt){if(!tt)throw new Error("`"+et+"` finished async. Use `"+o+"` instead")}function vfile(et){return looksLikeAVFile(et)?et:new VFile(et)}function looksLikeAVFile(et){return!!(et&&typeof et=="object"&&"message"in et&&"messages"in et)}function looksLikeAValue(et){return typeof et=="string"||isUint8Array(et)}function isUint8Array(et){return!!(et&&typeof et=="object"&&"byteLength"in et&&"byteOffset"in et)}const changelog="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",emptyPlugins=[],emptyRemarkRehypeOptions={allowDangerousHtml:!0},safeProtocol=/^(https?|ircs?|mailto|xmpp)$/i,deprecations=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Markdown(et){const o=et.allowedElements,tt=et.allowElement,rt=et.children||"",nt=et.className,ot=et.components,it=et.disallowedElements,st=et.rehypePlugins||emptyPlugins,at=et.remarkPlugins||emptyPlugins,ct=et.remarkRehypeOptions?{...et.remarkRehypeOptions,...emptyRemarkRehypeOptions}:emptyRemarkRehypeOptions,lt=et.skipHtml,dt=et.unwrapDisallowed,ht=et.urlTransform||defaultUrlTransform,mt=unified().use(remarkParse).use(at).use(remarkRehype,ct).use(st),ft=new VFile;typeof rt=="string"&&(ft.value=rt);for(const bt of deprecations)Object.hasOwn(et,bt.from)&&(""+bt.from+(bt.to?"use `"+bt.to+"` instead":"remove it")+changelog+bt.id,void 0);const pt=mt.parse(ft);let gt=mt.runSync(pt,ft);return nt&&(gt={type:"element",tagName:"div",properties:{className:nt},children:gt.type==="root"?gt.children:[gt]}),visit(gt,yt),toJsxRuntime(gt,{Fragment:jsxRuntimeExports.Fragment,components:ot,ignoreInvalidStyle:!0,jsx:jsxRuntimeExports.jsx,jsxs:jsxRuntimeExports.jsxs,passKeys:!0,passNode:!0});function yt(bt,xt,vt){if(bt.type==="raw"&&vt&&typeof xt=="number")return lt?vt.children.splice(xt,1):vt.children[xt]={type:"text",value:bt.value},xt;if(bt.type==="element"){let Et;for(Et in urlAttributes)if(Object.hasOwn(urlAttributes,Et)&&Object.hasOwn(bt.properties,Et)){const Ct=bt.properties[Et],St=urlAttributes[Et];(St===null||St.includes(bt.tagName))&&(bt.properties[Et]=ht(String(Ct||""),Et,bt))}}if(bt.type==="element"){let Et=o?!o.includes(bt.tagName):it?it.includes(bt.tagName):!1;if(!Et&&tt&&typeof xt=="number"&&(Et=!tt(bt,xt,vt)),Et&&vt&&typeof xt=="number")return dt&&bt.children?vt.children.splice(xt,1,...bt.children):vt.children.splice(xt,1),xt}}}function defaultUrlTransform(et){const o=et.indexOf(":"),tt=et.indexOf("?"),rt=et.indexOf("#"),nt=et.indexOf("/");return o<0||nt>-1&&o>nt||tt>-1&&o>tt||rt>-1&&o>rt||safeProtocol.test(et.slice(0,o))?et:""}const PrivacyPolicyOptIn=({onOptIn:et})=>{const[o,tt]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:[jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-md",children:[jsxRuntimeExports.jsx(CardHeader,{className:"space-y-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-xl sm:text-2xl",children:"Privacy Policy & Data Collection"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm sm:text-base text-muted-foreground",children:"We collect data to improve our services. This data is anonymous and helps us understand how our application is used. You can opt-in or opt-out of this data collection."}),jsxRuntimeExports.jsx(Button,{variant:"link",onClick:()=>tt(!0),className:"px-0 text-sm sm:text-base",children:"View Full Privacy Policy"})]})}),jsxRuntimeExports.jsxs(CardFooter,{className:"flex flex-col sm:flex-row gap-3 sm:gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>et(!1),className:"w-full sm:w-auto",children:"Opt Out"}),jsxRuntimeExports.jsx(Button,{onClick:()=>et(!0),className:"w-full sm:w-auto",children:"Opt In"})]})]}),jsxRuntimeExports.jsx(Dialog,{open:o,onOpenChange:tt,children:jsxRuntimeExports.jsxs(DialogContent,{className:"w-[95vw] max-w-4xl max-h-[90vh] p-4 sm:p-6",children:[jsxRuntimeExports.jsx(DialogHeader,{children:jsxRuntimeExports.jsx(DialogTitle,{className:"text-xl sm:text-2xl",children:"Privacy Policy"})}),jsxRuntimeExports.jsx(ScrollArea,{className:"mt-4 h-[50vh] sm:h-[60vh]",children:jsxRuntimeExports.jsx(DialogDescription,{className:"space-y-4",children:jsxRuntimeExports.jsx(Markdown,{className:"prose dark:prose-invert max-w-none text-sm sm:text-base",children:privacyPolicy})})})]})})]})},PrivacyPolicyPage=()=>{const[et,o]=reactExports.useState(!1);reactExports.useEffect(()=>{const rt=localStorage.getItem("privacyPolicyOptIn");rt!==null&&o(rt==="true")},[]);const tt=()=>{const rt=!et;o(rt),localStorage.setItem("privacyPolicyOptIn",rt.toString())};return jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-4xl mx-auto p-4 sm:p-6",children:[jsxRuntimeExports.jsx(CardHeader,{className:"space-y-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl sm:text-3xl",children:"Privacy Policy Settings"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm sm:text-base text-muted-foreground",children:"We collect data to improve our services. This data is anonymous and helps us understand how our application is used."}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[jsxRuntimeExports.jsxs("p",{className:"font-semibold",children:["Current status: ",et?"Opted In":"Opted Out"]}),jsxRuntimeExports.jsx(Button,{onClick:tt,className:"w-full sm:w-auto",children:et?"Opt Out":"Opt In"})]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg sm:text-xl font-semibold mb-4",children:"Privacy Policy"}),jsxRuntimeExports.jsx(ScrollArea,{className:"h-[50vh] sm:h-[60vh] border rounded-md p-2 sm:p-4",children:jsxRuntimeExports.jsx(Markdown,{className:"prose dark:prose-invert max-w-none text-sm sm:text-base",children:privacyPolicy})})]})]})})]})},SignSharedChain=({chainsData:et,onChainUpdate:o,isLoading:tt})=>{const{chainUUID:rt,blockUUID:nt}=useParams(),[ot,it]=reactExports.useState(null),st=useNavigate();return reactExports.useEffect(()=>{const at=et.find(ct=>ct.chainUUID===rt&&ct.blockUUID===nt);at&&it(at)},[et,rt,nt]),tt&&!ot?jsxRuntimeExports.jsx(Card,{className:"w-full max-w-md mx-auto",children:jsxRuntimeExports.jsxs(CardContent,{className:"flex flex-col items-center justify-center py-8 space-y-4",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-8 w-8 animate-spin"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Looking for chain..."})]})}):ot?jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-2xl mx-auto",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{children:"Sign Shared Chain"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold mb-2",children:ot.title}),jsxRuntimeExports.jsx("p",{className:"mb-4",children:ot.description}),jsxRuntimeExports.jsx(SignChain,{block:ot,chainsData:et,onSuccess:o})]})]}):jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-md mx-auto",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{children:"Chain Not Found"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsx("p",{className:"mb-4",children:"The requested chain or block could not be found."}),jsxRuntimeExports.jsx(Button,{onClick:()=>st("/view"),children:"View All Chains"})]})]})};function App(){const[et,o]=reactExports.useState(!1),[tt,rt]=reactExports.useState([]),{isLoading:nt,error:ot,node:it}=useWaku(),[st,at]=reactExports.useState({filter:"in-progress",store:"in-progress"}),[ct,lt]=reactExports.useState(null),[dt,ht]=reactExports.useState(!0);reactExports.useEffect(()=>{const gt=localStorage.getItem("telemetryOptIn");gt!==null&<(gt==="true")},[]),reactExports.useEffect(()=>{nt||!it||it.libp2p.getConnections().length===0||tt.length>0||et||(o(!0),ft())},[it,nt,st]);const mt=gt=>{lt(gt),localStorage.setItem("telemetryOptIn",gt.toString())};if(nt)return jsxRuntimeExports.jsx("div",{className:"min-h-screen bg-background text-foreground",children:jsxRuntimeExports.jsxs("div",{className:"container mx-auto px-4 py-16 flex flex-col items-center justify-center space-y-4",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl md:text-4xl font-bold",children:"BuddyBook"}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-8 w-8 animate-spin"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Connecting to Waku's decentralized network..."})]})]})});const ft=async()=>{console.log("Starting message listening");try{at(yt=>({...yt,store:"in-progress"})),ht(!0);const gt=getMessagesFromStore(it);for await(const yt of gt)rt(bt=>bt.some(vt=>vt.blockUUID===yt.blockUUID)?bt:[...bt,yt]);at(yt=>({...yt,store:"success"}))}catch(gt){console.error("Error fetching messages from store:",gt),at(yt=>({...yt,store:"error"}))}finally{ht(!1)}try{at(gt=>({...gt,filter:"in-progress"})),await subscribeToFilter(it,gt=>{pt(gt)}),at(gt=>({...gt,filter:"success"}))}catch(gt){console.error("Error subscribing to filter:",gt),at(yt=>({...yt,filter:"error"}))}};if(ot)return jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground flex flex-col justify-center items-center",children:[jsxRuntimeExports.jsx("p",{className:"text-red-500",children:"Error connecting to Waku network"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:ot.toString()})]});const pt=gt=>{rt(yt=>yt.some(xt=>xt.blockUUID===gt.blockUUID)?yt:[...yt,gt])};return ct===null?jsxRuntimeExports.jsx(PrivacyPolicyOptIn,{onOptIn:mt}):jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx(Header,{wakuStatus:st}),jsxRuntimeExports.jsx("main",{className:"container mx-auto px-4 py-4 md:py-8 max-w-7xl",children:jsxRuntimeExports.jsxs(Routes,{children:[jsxRuntimeExports.jsx(Route,{path:"/create",element:jsxRuntimeExports.jsx(ChainCreationForm,{})}),jsxRuntimeExports.jsx(Route,{path:"/view",element:jsxRuntimeExports.jsx(ChainList,{chainsData:tt,onChainUpdate:pt,isLoading:dt})}),jsxRuntimeExports.jsx(Route,{path:"/",element:jsxRuntimeExports.jsx(Home,{})}),jsxRuntimeExports.jsx(Route,{path:"/sign/:chainUUID/:blockUUID",element:jsxRuntimeExports.jsx(SignSharedChain,{chainsData:tt,onChainUpdate:pt,isLoading:dt})}),jsxRuntimeExports.jsx(Route,{path:"/telemetry",element:jsxRuntimeExports.jsx(PrivacyPolicyPage,{})}),jsxRuntimeExports.jsx(Route,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"/",replace:!0})})]})})]})}const Home=()=>jsxRuntimeExports.jsxs("div",{className:"space-y-4 md:space-y-6 p-4 md:p-6",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl md:text-4xl font-bold",children:"BuddyBook"}),jsxRuntimeExports.jsxs("div",{className:"w-full max-w-sm mx-auto p-4 md:p-6 bg-card rounded-lg shadow-md",children:[jsxRuntimeExports.jsx(Link,{to:"/create",children:jsxRuntimeExports.jsx(Button,{className:"w-full mb-4",children:"Create New Chain"})}),jsxRuntimeExports.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Click the button above to start creating a new chain."})]}),jsxRuntimeExports.jsx("p",{className:"text-xs md:text-sm text-muted-foreground text-center",children:"Welcome to BuddyBook - Create and share your chains!"})]});var util;(function(et){et.assertEqual=nt=>nt;function o(nt){}et.assertIs=o;function tt(nt){throw new Error}et.assertNever=tt,et.arrayToEnum=nt=>{const ot={};for(const it of nt)ot[it]=it;return ot},et.getValidEnumValues=nt=>{const ot=et.objectKeys(nt).filter(st=>typeof nt[nt[st]]!="number"),it={};for(const st of ot)it[st]=nt[st];return et.objectValues(it)},et.objectValues=nt=>et.objectKeys(nt).map(function(ot){return nt[ot]}),et.objectKeys=typeof Object.keys=="function"?nt=>Object.keys(nt):nt=>{const ot=[];for(const it in nt)Object.prototype.hasOwnProperty.call(nt,it)&&ot.push(it);return ot},et.find=(nt,ot)=>{for(const it of nt)if(ot(it))return it},et.isInteger=typeof Number.isInteger=="function"?nt=>Number.isInteger(nt):nt=>typeof nt=="number"&&isFinite(nt)&&Math.floor(nt)===nt;function rt(nt,ot=" | "){return nt.map(it=>typeof it=="string"?`'${it}'`:it).join(ot)}et.joinValues=rt,et.jsonStringifyReplacer=(nt,ot)=>typeof ot=="bigint"?ot.toString():ot})(util||(util={}));var objectUtil;(function(et){et.mergeShapes=(o,tt)=>({...o,...tt})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=et=>{switch(typeof et){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return isNaN(et)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(et)?ZodParsedType.array:et===null?ZodParsedType.null:et.then&&typeof et.then=="function"&&et.catch&&typeof et.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&et instanceof Map?ZodParsedType.map:typeof Set<"u"&&et instanceof Set?ZodParsedType.set:typeof Date<"u"&&et instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=et=>JSON.stringify(et,null,2).replace(/"([^"]+)":/g,"$1:");class ZodError extends Error{constructor(o){super(),this.issues=[],this.addIssue=rt=>{this.issues=[...this.issues,rt]},this.addIssues=(rt=[])=>{this.issues=[...this.issues,...rt]};const tt=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,tt):this.__proto__=tt,this.name="ZodError",this.issues=o}get errors(){return this.issues}format(o){const tt=o||function(ot){return ot.message},rt={_errors:[]},nt=ot=>{for(const it of ot.issues)if(it.code==="invalid_union")it.unionErrors.map(nt);else if(it.code==="invalid_return_type")nt(it.returnTypeError);else if(it.code==="invalid_arguments")nt(it.argumentsError);else if(it.path.length===0)rt._errors.push(tt(it));else{let st=rt,at=0;for(;attt.message){const tt={},rt=[];for(const nt of this.issues)nt.path.length>0?(tt[nt.path[0]]=tt[nt.path[0]]||[],tt[nt.path[0]].push(o(nt))):rt.push(o(nt));return{formErrors:rt,fieldErrors:tt}}get formErrors(){return this.flatten()}}ZodError.create=et=>new ZodError(et);const errorMap=(et,o)=>{let tt;switch(et.code){case ZodIssueCode.invalid_type:et.received===ZodParsedType.undefined?tt="Required":tt=`Expected ${et.expected}, received ${et.received}`;break;case ZodIssueCode.invalid_literal:tt=`Invalid literal value, expected ${JSON.stringify(et.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:tt=`Unrecognized key(s) in object: ${util.joinValues(et.keys,", ")}`;break;case ZodIssueCode.invalid_union:tt="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:tt=`Invalid discriminator value. Expected ${util.joinValues(et.options)}`;break;case ZodIssueCode.invalid_enum_value:tt=`Invalid enum value. Expected ${util.joinValues(et.options)}, received '${et.received}'`;break;case ZodIssueCode.invalid_arguments:tt="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:tt="Invalid function return type";break;case ZodIssueCode.invalid_date:tt="Invalid date";break;case ZodIssueCode.invalid_string:typeof et.validation=="object"?"includes"in et.validation?(tt=`Invalid input: must include "${et.validation.includes}"`,typeof et.validation.position=="number"&&(tt=`${tt} at one or more positions greater than or equal to ${et.validation.position}`)):"startsWith"in et.validation?tt=`Invalid input: must start with "${et.validation.startsWith}"`:"endsWith"in et.validation?tt=`Invalid input: must end with "${et.validation.endsWith}"`:util.assertNever(et.validation):et.validation!=="regex"?tt=`Invalid ${et.validation}`:tt="Invalid";break;case ZodIssueCode.too_small:et.type==="array"?tt=`Array must contain ${et.exact?"exactly":et.inclusive?"at least":"more than"} ${et.minimum} element(s)`:et.type==="string"?tt=`String must contain ${et.exact?"exactly":et.inclusive?"at least":"over"} ${et.minimum} character(s)`:et.type==="number"?tt=`Number must be ${et.exact?"exactly equal to ":et.inclusive?"greater than or equal to ":"greater than "}${et.minimum}`:et.type==="date"?tt=`Date must be ${et.exact?"exactly equal to ":et.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(et.minimum))}`:tt="Invalid input";break;case ZodIssueCode.too_big:et.type==="array"?tt=`Array must contain ${et.exact?"exactly":et.inclusive?"at most":"less than"} ${et.maximum} element(s)`:et.type==="string"?tt=`String must contain ${et.exact?"exactly":et.inclusive?"at most":"under"} ${et.maximum} character(s)`:et.type==="number"?tt=`Number must be ${et.exact?"exactly":et.inclusive?"less than or equal to":"less than"} ${et.maximum}`:et.type==="bigint"?tt=`BigInt must be ${et.exact?"exactly":et.inclusive?"less than or equal to":"less than"} ${et.maximum}`:et.type==="date"?tt=`Date must be ${et.exact?"exactly":et.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(et.maximum))}`:tt="Invalid input";break;case ZodIssueCode.custom:tt="Invalid input";break;case ZodIssueCode.invalid_intersection_types:tt="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:tt=`Number must be a multiple of ${et.multipleOf}`;break;case ZodIssueCode.not_finite:tt="Number must be finite";break;default:tt=o.defaultError,util.assertNever(et)}return{message:tt}};let overrideErrorMap=errorMap;function setErrorMap(et){overrideErrorMap=et}function getErrorMap(){return overrideErrorMap}const makeIssue=et=>{const{data:o,path:tt,errorMaps:rt,issueData:nt}=et,ot=[...tt,...nt.path||[]],it={...nt,path:ot};if(nt.message!==void 0)return{...nt,path:ot,message:nt.message};let st="";const at=rt.filter(ct=>!!ct).slice().reverse();for(const ct of at)st=ct(it,{data:o,defaultError:st}).message;return{...nt,path:ot,message:st}},EMPTY_PATH=[];function addIssueToContext(et,o){const tt=getErrorMap(),rt=makeIssue({issueData:o,data:et.data,path:et.path,errorMaps:[et.common.contextualErrorMap,et.schemaErrorMap,tt,tt===errorMap?void 0:errorMap].filter(nt=>!!nt)});et.common.issues.push(rt)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(o,tt){const rt=[];for(const nt of tt){if(nt.status==="aborted")return INVALID;nt.status==="dirty"&&o.dirty(),rt.push(nt.value)}return{status:o.value,value:rt}}static async mergeObjectAsync(o,tt){const rt=[];for(const nt of tt){const ot=await nt.key,it=await nt.value;rt.push({key:ot,value:it})}return ParseStatus.mergeObjectSync(o,rt)}static mergeObjectSync(o,tt){const rt={};for(const nt of tt){const{key:ot,value:it}=nt;if(ot.status==="aborted"||it.status==="aborted")return INVALID;ot.status==="dirty"&&o.dirty(),it.status==="dirty"&&o.dirty(),ot.value!=="__proto__"&&(typeof it.value<"u"||nt.alwaysSet)&&(rt[ot.value]=it.value)}return{status:o.value,value:rt}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=et=>({status:"dirty",value:et}),OK=et=>({status:"valid",value:et}),isAborted=et=>et.status==="aborted",isDirty=et=>et.status==="dirty",isValid=et=>et.status==="valid",isAsync=et=>typeof Promise<"u"&&et instanceof Promise;function __classPrivateFieldGet(et,o,tt,rt){if(typeof o=="function"?et!==o||!rt:!o.has(et))throw new TypeError("Cannot read private member from an object whose class did not declare it");return o.get(et)}function __classPrivateFieldSet(et,o,tt,rt,nt){if(typeof o=="function"?et!==o||!nt:!o.has(et))throw new TypeError("Cannot write private member to an object whose class did not declare it");return o.set(et,tt),tt}typeof SuppressedError=="function"&&SuppressedError;var errorUtil;(function(et){et.errToObj=o=>typeof o=="string"?{message:o}:o||{},et.toString=o=>typeof o=="string"?o:o==null?void 0:o.message})(errorUtil||(errorUtil={}));var _ZodEnum_cache,_ZodNativeEnum_cache;class ParseInputLazyPath{constructor(o,tt,rt,nt){this._cachedPath=[],this.parent=o,this.data=tt,this._path=rt,this._key=nt}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(et,o)=>{if(isValid(o))return{success:!0,data:o.value};if(!et.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const tt=new ZodError(et.common.issues);return this._error=tt,this._error}}};function processCreateParams(et){if(!et)return{};const{errorMap:o,invalid_type_error:tt,required_error:rt,description:nt}=et;if(o&&(tt||rt))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return o?{errorMap:o,description:nt}:{errorMap:(it,st)=>{var at,ct;const{message:lt}=et;return it.code==="invalid_enum_value"?{message:lt??st.defaultError}:typeof st.data>"u"?{message:(at=lt??rt)!==null&&at!==void 0?at:st.defaultError}:it.code!=="invalid_type"?{message:st.defaultError}:{message:(ct=lt??tt)!==null&&ct!==void 0?ct:st.defaultError}},description:nt}}class ZodType{constructor(o){this.spa=this.safeParseAsync,this._def=o,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(o){return getParsedType(o.data)}_getOrReturnCtx(o,tt){return tt||{common:o.parent.common,data:o.data,parsedType:getParsedType(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new ParseStatus,ctx:{common:o.parent.common,data:o.data,parsedType:getParsedType(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){const tt=this._parse(o);if(isAsync(tt))throw new Error("Synchronous parse encountered promise.");return tt}_parseAsync(o){const tt=this._parse(o);return Promise.resolve(tt)}parse(o,tt){const rt=this.safeParse(o,tt);if(rt.success)return rt.data;throw rt.error}safeParse(o,tt){var rt;const nt={common:{issues:[],async:(rt=tt==null?void 0:tt.async)!==null&&rt!==void 0?rt:!1,contextualErrorMap:tt==null?void 0:tt.errorMap},path:(tt==null?void 0:tt.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:getParsedType(o)},ot=this._parseSync({data:o,path:nt.path,parent:nt});return handleResult(nt,ot)}async parseAsync(o,tt){const rt=await this.safeParseAsync(o,tt);if(rt.success)return rt.data;throw rt.error}async safeParseAsync(o,tt){const rt={common:{issues:[],contextualErrorMap:tt==null?void 0:tt.errorMap,async:!0},path:(tt==null?void 0:tt.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:getParsedType(o)},nt=this._parse({data:o,path:rt.path,parent:rt}),ot=await(isAsync(nt)?nt:Promise.resolve(nt));return handleResult(rt,ot)}refine(o,tt){const rt=nt=>typeof tt=="string"||typeof tt>"u"?{message:tt}:typeof tt=="function"?tt(nt):tt;return this._refinement((nt,ot)=>{const it=o(nt),st=()=>ot.addIssue({code:ZodIssueCode.custom,...rt(nt)});return typeof Promise<"u"&&it instanceof Promise?it.then(at=>at?!0:(st(),!1)):it?!0:(st(),!1)})}refinement(o,tt){return this._refinement((rt,nt)=>o(rt)?!0:(nt.addIssue(typeof tt=="function"?tt(rt,nt):tt),!1))}_refinement(o){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this,this._def)}promise(){return ZodPromise.create(this,this._def)}or(o){return ZodUnion.create([this,o],this._def)}and(o){return ZodIntersection.create(this,o,this._def)}transform(o){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:o}})}default(o){const tt=typeof o=="function"?o:()=>o;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:tt,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(o){const tt=typeof o=="function"?o:()=>o;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:tt,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(o){const tt=this.constructor;return new tt({...this._def,description:o})}pipe(o){return ZodPipeline.create(this,o)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6Regex=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(et){let o="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return et.precision?o=`${o}\\.\\d{${et.precision}}`:et.precision==null&&(o=`${o}(\\.\\d+)?`),o}function timeRegex(et){return new RegExp(`^${timeRegexSource(et)}$`)}function datetimeRegex(et){let o=`${dateRegexSource}T${timeRegexSource(et)}`;const tt=[];return tt.push(et.local?"Z?":"Z"),et.offset&&tt.push("([+-]\\d{2}:?\\d{2})"),o=`${o}(${tt.join("|")})`,new RegExp(`^${o}$`)}function isValidIP(et,o){return!!((o==="v4"||!o)&&ipv4Regex.test(et)||(o==="v6"||!o)&&ipv6Regex.test(et))}class ZodString extends ZodType{_parse(o){if(this._def.coerce&&(o.data=String(o.data)),this._getType(o)!==ZodParsedType.string){const ot=this._getOrReturnCtx(o);return addIssueToContext(ot,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ot.parsedType}),INVALID}const rt=new ParseStatus;let nt;for(const ot of this._def.checks)if(ot.kind==="min")o.data.lengthot.value&&(nt=this._getOrReturnCtx(o,nt),addIssueToContext(nt,{code:ZodIssueCode.too_big,maximum:ot.value,type:"string",inclusive:!0,exact:!1,message:ot.message}),rt.dirty());else if(ot.kind==="length"){const it=o.data.length>ot.value,st=o.data.lengtho.test(nt),{validation:tt,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(rt)})}_addCheck(o){return new ZodString({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...errorUtil.errToObj(o)})}url(o){return this._addCheck({kind:"url",...errorUtil.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...errorUtil.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...errorUtil.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...errorUtil.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...errorUtil.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...errorUtil.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...errorUtil.errToObj(o)})}datetime(o){var tt,rt;return typeof o=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:o}):this._addCheck({kind:"datetime",precision:typeof(o==null?void 0:o.precision)>"u"?null:o==null?void 0:o.precision,offset:(tt=o==null?void 0:o.offset)!==null&&tt!==void 0?tt:!1,local:(rt=o==null?void 0:o.local)!==null&&rt!==void 0?rt:!1,...errorUtil.errToObj(o==null?void 0:o.message)})}date(o){return this._addCheck({kind:"date",message:o})}time(o){return typeof o=="string"?this._addCheck({kind:"time",precision:null,message:o}):this._addCheck({kind:"time",precision:typeof(o==null?void 0:o.precision)>"u"?null:o==null?void 0:o.precision,...errorUtil.errToObj(o==null?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...errorUtil.errToObj(o)})}regex(o,tt){return this._addCheck({kind:"regex",regex:o,...errorUtil.errToObj(tt)})}includes(o,tt){return this._addCheck({kind:"includes",value:o,position:tt==null?void 0:tt.position,...errorUtil.errToObj(tt==null?void 0:tt.message)})}startsWith(o,tt){return this._addCheck({kind:"startsWith",value:o,...errorUtil.errToObj(tt)})}endsWith(o,tt){return this._addCheck({kind:"endsWith",value:o,...errorUtil.errToObj(tt)})}min(o,tt){return this._addCheck({kind:"min",value:o,...errorUtil.errToObj(tt)})}max(o,tt){return this._addCheck({kind:"max",value:o,...errorUtil.errToObj(tt)})}length(o,tt){return this._addCheck({kind:"length",value:o,...errorUtil.errToObj(tt)})}nonempty(o){return this.min(1,errorUtil.errToObj(o))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(o=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find(o=>o.kind==="date")}get isTime(){return!!this._def.checks.find(o=>o.kind==="time")}get isDuration(){return!!this._def.checks.find(o=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find(o=>o.kind==="email")}get isURL(){return!!this._def.checks.find(o=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find(o=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find(o=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(o=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(o=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(o=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find(o=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find(o=>o.kind==="ip")}get isBase64(){return!!this._def.checks.find(o=>o.kind==="base64")}get minLength(){let o=null;for(const tt of this._def.checks)tt.kind==="min"&&(o===null||tt.value>o)&&(o=tt.value);return o}get maxLength(){let o=null;for(const tt of this._def.checks)tt.kind==="max"&&(o===null||tt.value{var o;return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:(o=et==null?void 0:et.coerce)!==null&&o!==void 0?o:!1,...processCreateParams(et)})};function floatSafeRemainder(et,o){const tt=(et.toString().split(".")[1]||"").length,rt=(o.toString().split(".")[1]||"").length,nt=tt>rt?tt:rt,ot=parseInt(et.toFixed(nt).replace(".","")),it=parseInt(o.toFixed(nt).replace(".",""));return ot%it/Math.pow(10,nt)}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce&&(o.data=Number(o.data)),this._getType(o)!==ZodParsedType.number){const ot=this._getOrReturnCtx(o);return addIssueToContext(ot,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ot.parsedType}),INVALID}let rt;const nt=new ParseStatus;for(const ot of this._def.checks)ot.kind==="int"?util.isInteger(o.data)||(rt=this._getOrReturnCtx(o,rt),addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:ot.message}),nt.dirty()):ot.kind==="min"?(ot.inclusive?o.dataot.value:o.data>=ot.value)&&(rt=this._getOrReturnCtx(o,rt),addIssueToContext(rt,{code:ZodIssueCode.too_big,maximum:ot.value,type:"number",inclusive:ot.inclusive,exact:!1,message:ot.message}),nt.dirty()):ot.kind==="multipleOf"?floatSafeRemainder(o.data,ot.value)!==0&&(rt=this._getOrReturnCtx(o,rt),addIssueToContext(rt,{code:ZodIssueCode.not_multiple_of,multipleOf:ot.value,message:ot.message}),nt.dirty()):ot.kind==="finite"?Number.isFinite(o.data)||(rt=this._getOrReturnCtx(o,rt),addIssueToContext(rt,{code:ZodIssueCode.not_finite,message:ot.message}),nt.dirty()):util.assertNever(ot);return{status:nt.value,value:o.data}}gte(o,tt){return this.setLimit("min",o,!0,errorUtil.toString(tt))}gt(o,tt){return this.setLimit("min",o,!1,errorUtil.toString(tt))}lte(o,tt){return this.setLimit("max",o,!0,errorUtil.toString(tt))}lt(o,tt){return this.setLimit("max",o,!1,errorUtil.toString(tt))}setLimit(o,tt,rt,nt){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:o,value:tt,inclusive:rt,message:errorUtil.toString(nt)}]})}_addCheck(o){return new ZodNumber({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:errorUtil.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(o)})}multipleOf(o,tt){return this._addCheck({kind:"multipleOf",value:o,message:errorUtil.toString(tt)})}finite(o){return this._addCheck({kind:"finite",message:errorUtil.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(o)})}get minValue(){let o=null;for(const tt of this._def.checks)tt.kind==="min"&&(o===null||tt.value>o)&&(o=tt.value);return o}get maxValue(){let o=null;for(const tt of this._def.checks)tt.kind==="max"&&(o===null||tt.valueo.kind==="int"||o.kind==="multipleOf"&&util.isInteger(o.value))}get isFinite(){let o=null,tt=null;for(const rt of this._def.checks){if(rt.kind==="finite"||rt.kind==="int"||rt.kind==="multipleOf")return!0;rt.kind==="min"?(tt===null||rt.value>tt)&&(tt=rt.value):rt.kind==="max"&&(o===null||rt.valuenew ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:(et==null?void 0:et.coerce)||!1,...processCreateParams(et)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce&&(o.data=BigInt(o.data)),this._getType(o)!==ZodParsedType.bigint){const ot=this._getOrReturnCtx(o);return addIssueToContext(ot,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ot.parsedType}),INVALID}let rt;const nt=new ParseStatus;for(const ot of this._def.checks)ot.kind==="min"?(ot.inclusive?o.dataot.value:o.data>=ot.value)&&(rt=this._getOrReturnCtx(o,rt),addIssueToContext(rt,{code:ZodIssueCode.too_big,type:"bigint",maximum:ot.value,inclusive:ot.inclusive,message:ot.message}),nt.dirty()):ot.kind==="multipleOf"?o.data%ot.value!==BigInt(0)&&(rt=this._getOrReturnCtx(o,rt),addIssueToContext(rt,{code:ZodIssueCode.not_multiple_of,multipleOf:ot.value,message:ot.message}),nt.dirty()):util.assertNever(ot);return{status:nt.value,value:o.data}}gte(o,tt){return this.setLimit("min",o,!0,errorUtil.toString(tt))}gt(o,tt){return this.setLimit("min",o,!1,errorUtil.toString(tt))}lte(o,tt){return this.setLimit("max",o,!0,errorUtil.toString(tt))}lt(o,tt){return this.setLimit("max",o,!1,errorUtil.toString(tt))}setLimit(o,tt,rt,nt){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:o,value:tt,inclusive:rt,message:errorUtil.toString(nt)}]})}_addCheck(o){return new ZodBigInt({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(o)})}multipleOf(o,tt){return this._addCheck({kind:"multipleOf",value:o,message:errorUtil.toString(tt)})}get minValue(){let o=null;for(const tt of this._def.checks)tt.kind==="min"&&(o===null||tt.value>o)&&(o=tt.value);return o}get maxValue(){let o=null;for(const tt of this._def.checks)tt.kind==="max"&&(o===null||tt.value{var o;return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:(o=et==null?void 0:et.coerce)!==null&&o!==void 0?o:!1,...processCreateParams(et)})};class ZodBoolean extends ZodType{_parse(o){if(this._def.coerce&&(o.data=!!o.data),this._getType(o)!==ZodParsedType.boolean){const rt=this._getOrReturnCtx(o);return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:rt.parsedType}),INVALID}return OK(o.data)}}ZodBoolean.create=et=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:(et==null?void 0:et.coerce)||!1,...processCreateParams(et)});class ZodDate extends ZodType{_parse(o){if(this._def.coerce&&(o.data=new Date(o.data)),this._getType(o)!==ZodParsedType.date){const ot=this._getOrReturnCtx(o);return addIssueToContext(ot,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ot.parsedType}),INVALID}if(isNaN(o.data.getTime())){const ot=this._getOrReturnCtx(o);return addIssueToContext(ot,{code:ZodIssueCode.invalid_date}),INVALID}const rt=new ParseStatus;let nt;for(const ot of this._def.checks)ot.kind==="min"?o.data.getTime()ot.value&&(nt=this._getOrReturnCtx(o,nt),addIssueToContext(nt,{code:ZodIssueCode.too_big,message:ot.message,inclusive:!0,exact:!1,maximum:ot.value,type:"date"}),rt.dirty()):util.assertNever(ot);return{status:rt.value,value:new Date(o.data.getTime())}}_addCheck(o){return new ZodDate({...this._def,checks:[...this._def.checks,o]})}min(o,tt){return this._addCheck({kind:"min",value:o.getTime(),message:errorUtil.toString(tt)})}max(o,tt){return this._addCheck({kind:"max",value:o.getTime(),message:errorUtil.toString(tt)})}get minDate(){let o=null;for(const tt of this._def.checks)tt.kind==="min"&&(o===null||tt.value>o)&&(o=tt.value);return o!=null?new Date(o):null}get maxDate(){let o=null;for(const tt of this._def.checks)tt.kind==="max"&&(o===null||tt.valuenew ZodDate({checks:[],coerce:(et==null?void 0:et.coerce)||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(et)});class ZodSymbol extends ZodType{_parse(o){if(this._getType(o)!==ZodParsedType.symbol){const rt=this._getOrReturnCtx(o);return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:rt.parsedType}),INVALID}return OK(o.data)}}ZodSymbol.create=et=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(et)});class ZodUndefined extends ZodType{_parse(o){if(this._getType(o)!==ZodParsedType.undefined){const rt=this._getOrReturnCtx(o);return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:rt.parsedType}),INVALID}return OK(o.data)}}ZodUndefined.create=et=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(et)});class ZodNull extends ZodType{_parse(o){if(this._getType(o)!==ZodParsedType.null){const rt=this._getOrReturnCtx(o);return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:rt.parsedType}),INVALID}return OK(o.data)}}ZodNull.create=et=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(et)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(o){return OK(o.data)}}ZodAny.create=et=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(et)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(o){return OK(o.data)}}ZodUnknown.create=et=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(et)});class ZodNever extends ZodType{_parse(o){const tt=this._getOrReturnCtx(o);return addIssueToContext(tt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:tt.parsedType}),INVALID}}ZodNever.create=et=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(et)});class ZodVoid extends ZodType{_parse(o){if(this._getType(o)!==ZodParsedType.undefined){const rt=this._getOrReturnCtx(o);return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:rt.parsedType}),INVALID}return OK(o.data)}}ZodVoid.create=et=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(et)});class ZodArray extends ZodType{_parse(o){const{ctx:tt,status:rt}=this._processInputParams(o),nt=this._def;if(tt.parsedType!==ZodParsedType.array)return addIssueToContext(tt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:tt.parsedType}),INVALID;if(nt.exactLength!==null){const it=tt.data.length>nt.exactLength.value,st=tt.data.lengthnt.maxLength.value&&(addIssueToContext(tt,{code:ZodIssueCode.too_big,maximum:nt.maxLength.value,type:"array",inclusive:!0,exact:!1,message:nt.maxLength.message}),rt.dirty()),tt.common.async)return Promise.all([...tt.data].map((it,st)=>nt.type._parseAsync(new ParseInputLazyPath(tt,it,tt.path,st)))).then(it=>ParseStatus.mergeArray(rt,it));const ot=[...tt.data].map((it,st)=>nt.type._parseSync(new ParseInputLazyPath(tt,it,tt.path,st)));return ParseStatus.mergeArray(rt,ot)}get element(){return this._def.type}min(o,tt){return new ZodArray({...this._def,minLength:{value:o,message:errorUtil.toString(tt)}})}max(o,tt){return new ZodArray({...this._def,maxLength:{value:o,message:errorUtil.toString(tt)}})}length(o,tt){return new ZodArray({...this._def,exactLength:{value:o,message:errorUtil.toString(tt)}})}nonempty(o){return this.min(1,o)}}ZodArray.create=(et,o)=>new ZodArray({type:et,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(o)});function deepPartialify(et){if(et instanceof ZodObject){const o={};for(const tt in et.shape){const rt=et.shape[tt];o[tt]=ZodOptional.create(deepPartialify(rt))}return new ZodObject({...et._def,shape:()=>o})}else return et instanceof ZodArray?new ZodArray({...et._def,type:deepPartialify(et.element)}):et instanceof ZodOptional?ZodOptional.create(deepPartialify(et.unwrap())):et instanceof ZodNullable?ZodNullable.create(deepPartialify(et.unwrap())):et instanceof ZodTuple?ZodTuple.create(et.items.map(o=>deepPartialify(o))):et}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const o=this._def.shape(),tt=util.objectKeys(o);return this._cached={shape:o,keys:tt}}_parse(o){if(this._getType(o)!==ZodParsedType.object){const ct=this._getOrReturnCtx(o);return addIssueToContext(ct,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ct.parsedType}),INVALID}const{status:rt,ctx:nt}=this._processInputParams(o),{shape:ot,keys:it}=this._getCached(),st=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const ct in nt.data)it.includes(ct)||st.push(ct);const at=[];for(const ct of it){const lt=ot[ct],dt=nt.data[ct];at.push({key:{status:"valid",value:ct},value:lt._parse(new ParseInputLazyPath(nt,dt,nt.path,ct)),alwaysSet:ct in nt.data})}if(this._def.catchall instanceof ZodNever){const ct=this._def.unknownKeys;if(ct==="passthrough")for(const lt of st)at.push({key:{status:"valid",value:lt},value:{status:"valid",value:nt.data[lt]}});else if(ct==="strict")st.length>0&&(addIssueToContext(nt,{code:ZodIssueCode.unrecognized_keys,keys:st}),rt.dirty());else if(ct!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const ct=this._def.catchall;for(const lt of st){const dt=nt.data[lt];at.push({key:{status:"valid",value:lt},value:ct._parse(new ParseInputLazyPath(nt,dt,nt.path,lt)),alwaysSet:lt in nt.data})}}return nt.common.async?Promise.resolve().then(async()=>{const ct=[];for(const lt of at){const dt=await lt.key,ht=await lt.value;ct.push({key:dt,value:ht,alwaysSet:lt.alwaysSet})}return ct}).then(ct=>ParseStatus.mergeObjectSync(rt,ct)):ParseStatus.mergeObjectSync(rt,at)}get shape(){return this._def.shape()}strict(o){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(tt,rt)=>{var nt,ot,it,st;const at=(it=(ot=(nt=this._def).errorMap)===null||ot===void 0?void 0:ot.call(nt,tt,rt).message)!==null&&it!==void 0?it:rt.defaultError;return tt.code==="unrecognized_keys"?{message:(st=errorUtil.errToObj(o).message)!==null&&st!==void 0?st:at}:{message:at}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(o){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new ZodObject({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(o,tt){return this.augment({[o]:tt})}catchall(o){return new ZodObject({...this._def,catchall:o})}pick(o){const tt={};return util.objectKeys(o).forEach(rt=>{o[rt]&&this.shape[rt]&&(tt[rt]=this.shape[rt])}),new ZodObject({...this._def,shape:()=>tt})}omit(o){const tt={};return util.objectKeys(this.shape).forEach(rt=>{o[rt]||(tt[rt]=this.shape[rt])}),new ZodObject({...this._def,shape:()=>tt})}deepPartial(){return deepPartialify(this)}partial(o){const tt={};return util.objectKeys(this.shape).forEach(rt=>{const nt=this.shape[rt];o&&!o[rt]?tt[rt]=nt:tt[rt]=nt.optional()}),new ZodObject({...this._def,shape:()=>tt})}required(o){const tt={};return util.objectKeys(this.shape).forEach(rt=>{if(o&&!o[rt])tt[rt]=this.shape[rt];else{let ot=this.shape[rt];for(;ot instanceof ZodOptional;)ot=ot._def.innerType;tt[rt]=ot}}),new ZodObject({...this._def,shape:()=>tt})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(et,o)=>new ZodObject({shape:()=>et,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(o)});ZodObject.strictCreate=(et,o)=>new ZodObject({shape:()=>et,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(o)});ZodObject.lazycreate=(et,o)=>new ZodObject({shape:et,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(o)});class ZodUnion extends ZodType{_parse(o){const{ctx:tt}=this._processInputParams(o),rt=this._def.options;function nt(ot){for(const st of ot)if(st.result.status==="valid")return st.result;for(const st of ot)if(st.result.status==="dirty")return tt.common.issues.push(...st.ctx.common.issues),st.result;const it=ot.map(st=>new ZodError(st.ctx.common.issues));return addIssueToContext(tt,{code:ZodIssueCode.invalid_union,unionErrors:it}),INVALID}if(tt.common.async)return Promise.all(rt.map(async ot=>{const it={...tt,common:{...tt.common,issues:[]},parent:null};return{result:await ot._parseAsync({data:tt.data,path:tt.path,parent:it}),ctx:it}})).then(nt);{let ot;const it=[];for(const at of rt){const ct={...tt,common:{...tt.common,issues:[]},parent:null},lt=at._parseSync({data:tt.data,path:tt.path,parent:ct});if(lt.status==="valid")return lt;lt.status==="dirty"&&!ot&&(ot={result:lt,ctx:ct}),ct.common.issues.length&&it.push(ct.common.issues)}if(ot)return tt.common.issues.push(...ot.ctx.common.issues),ot.result;const st=it.map(at=>new ZodError(at));return addIssueToContext(tt,{code:ZodIssueCode.invalid_union,unionErrors:st}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(et,o)=>new ZodUnion({options:et,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(o)});const getDiscriminator=et=>et instanceof ZodLazy?getDiscriminator(et.schema):et instanceof ZodEffects?getDiscriminator(et.innerType()):et instanceof ZodLiteral?[et.value]:et instanceof ZodEnum?et.options:et instanceof ZodNativeEnum?util.objectValues(et.enum):et instanceof ZodDefault?getDiscriminator(et._def.innerType):et instanceof ZodUndefined?[void 0]:et instanceof ZodNull?[null]:et instanceof ZodOptional?[void 0,...getDiscriminator(et.unwrap())]:et instanceof ZodNullable?[null,...getDiscriminator(et.unwrap())]:et instanceof ZodBranded||et instanceof ZodReadonly?getDiscriminator(et.unwrap()):et instanceof ZodCatch?getDiscriminator(et._def.innerType):[];class ZodDiscriminatedUnion extends ZodType{_parse(o){const{ctx:tt}=this._processInputParams(o);if(tt.parsedType!==ZodParsedType.object)return addIssueToContext(tt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:tt.parsedType}),INVALID;const rt=this.discriminator,nt=tt.data[rt],ot=this.optionsMap.get(nt);return ot?tt.common.async?ot._parseAsync({data:tt.data,path:tt.path,parent:tt}):ot._parseSync({data:tt.data,path:tt.path,parent:tt}):(addIssueToContext(tt,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[rt]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(o,tt,rt){const nt=new Map;for(const ot of tt){const it=getDiscriminator(ot.shape[o]);if(!it.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(const st of it){if(nt.has(st))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(st)}`);nt.set(st,ot)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:o,options:tt,optionsMap:nt,...processCreateParams(rt)})}}function mergeValues(et,o){const tt=getParsedType(et),rt=getParsedType(o);if(et===o)return{valid:!0,data:et};if(tt===ZodParsedType.object&&rt===ZodParsedType.object){const nt=util.objectKeys(o),ot=util.objectKeys(et).filter(st=>nt.indexOf(st)!==-1),it={...et,...o};for(const st of ot){const at=mergeValues(et[st],o[st]);if(!at.valid)return{valid:!1};it[st]=at.data}return{valid:!0,data:it}}else if(tt===ZodParsedType.array&&rt===ZodParsedType.array){if(et.length!==o.length)return{valid:!1};const nt=[];for(let ot=0;ot{if(isAborted(ot)||isAborted(it))return INVALID;const st=mergeValues(ot.value,it.value);return st.valid?((isDirty(ot)||isDirty(it))&&tt.dirty(),{status:tt.value,value:st.data}):(addIssueToContext(rt,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return rt.common.async?Promise.all([this._def.left._parseAsync({data:rt.data,path:rt.path,parent:rt}),this._def.right._parseAsync({data:rt.data,path:rt.path,parent:rt})]).then(([ot,it])=>nt(ot,it)):nt(this._def.left._parseSync({data:rt.data,path:rt.path,parent:rt}),this._def.right._parseSync({data:rt.data,path:rt.path,parent:rt}))}}ZodIntersection.create=(et,o,tt)=>new ZodIntersection({left:et,right:o,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(tt)});class ZodTuple extends ZodType{_parse(o){const{status:tt,ctx:rt}=this._processInputParams(o);if(rt.parsedType!==ZodParsedType.array)return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:rt.parsedType}),INVALID;if(rt.data.lengththis._def.items.length&&(addIssueToContext(rt,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),tt.dirty());const ot=[...rt.data].map((it,st)=>{const at=this._def.items[st]||this._def.rest;return at?at._parse(new ParseInputLazyPath(rt,it,rt.path,st)):null}).filter(it=>!!it);return rt.common.async?Promise.all(ot).then(it=>ParseStatus.mergeArray(tt,it)):ParseStatus.mergeArray(tt,ot)}get items(){return this._def.items}rest(o){return new ZodTuple({...this._def,rest:o})}}ZodTuple.create=(et,o)=>{if(!Array.isArray(et))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:et,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(o)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:tt,ctx:rt}=this._processInputParams(o);if(rt.parsedType!==ZodParsedType.object)return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:rt.parsedType}),INVALID;const nt=[],ot=this._def.keyType,it=this._def.valueType;for(const st in rt.data)nt.push({key:ot._parse(new ParseInputLazyPath(rt,st,rt.path,st)),value:it._parse(new ParseInputLazyPath(rt,rt.data[st],rt.path,st)),alwaysSet:st in rt.data});return rt.common.async?ParseStatus.mergeObjectAsync(tt,nt):ParseStatus.mergeObjectSync(tt,nt)}get element(){return this._def.valueType}static create(o,tt,rt){return tt instanceof ZodType?new ZodRecord({keyType:o,valueType:tt,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(rt)}):new ZodRecord({keyType:ZodString.create(),valueType:o,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(tt)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:tt,ctx:rt}=this._processInputParams(o);if(rt.parsedType!==ZodParsedType.map)return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:rt.parsedType}),INVALID;const nt=this._def.keyType,ot=this._def.valueType,it=[...rt.data.entries()].map(([st,at],ct)=>({key:nt._parse(new ParseInputLazyPath(rt,st,rt.path,[ct,"key"])),value:ot._parse(new ParseInputLazyPath(rt,at,rt.path,[ct,"value"]))}));if(rt.common.async){const st=new Map;return Promise.resolve().then(async()=>{for(const at of it){const ct=await at.key,lt=await at.value;if(ct.status==="aborted"||lt.status==="aborted")return INVALID;(ct.status==="dirty"||lt.status==="dirty")&&tt.dirty(),st.set(ct.value,lt.value)}return{status:tt.value,value:st}})}else{const st=new Map;for(const at of it){const ct=at.key,lt=at.value;if(ct.status==="aborted"||lt.status==="aborted")return INVALID;(ct.status==="dirty"||lt.status==="dirty")&&tt.dirty(),st.set(ct.value,lt.value)}return{status:tt.value,value:st}}}}ZodMap.create=(et,o,tt)=>new ZodMap({valueType:o,keyType:et,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(tt)});class ZodSet extends ZodType{_parse(o){const{status:tt,ctx:rt}=this._processInputParams(o);if(rt.parsedType!==ZodParsedType.set)return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:rt.parsedType}),INVALID;const nt=this._def;nt.minSize!==null&&rt.data.sizent.maxSize.value&&(addIssueToContext(rt,{code:ZodIssueCode.too_big,maximum:nt.maxSize.value,type:"set",inclusive:!0,exact:!1,message:nt.maxSize.message}),tt.dirty());const ot=this._def.valueType;function it(at){const ct=new Set;for(const lt of at){if(lt.status==="aborted")return INVALID;lt.status==="dirty"&&tt.dirty(),ct.add(lt.value)}return{status:tt.value,value:ct}}const st=[...rt.data.values()].map((at,ct)=>ot._parse(new ParseInputLazyPath(rt,at,rt.path,ct)));return rt.common.async?Promise.all(st).then(at=>it(at)):it(st)}min(o,tt){return new ZodSet({...this._def,minSize:{value:o,message:errorUtil.toString(tt)}})}max(o,tt){return new ZodSet({...this._def,maxSize:{value:o,message:errorUtil.toString(tt)}})}size(o,tt){return this.min(o,tt).max(o,tt)}nonempty(o){return this.min(1,o)}}ZodSet.create=(et,o)=>new ZodSet({valueType:et,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(o)});class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(o){const{ctx:tt}=this._processInputParams(o);if(tt.parsedType!==ZodParsedType.function)return addIssueToContext(tt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:tt.parsedType}),INVALID;function rt(st,at){return makeIssue({data:st,path:tt.path,errorMaps:[tt.common.contextualErrorMap,tt.schemaErrorMap,getErrorMap(),errorMap].filter(ct=>!!ct),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:at}})}function nt(st,at){return makeIssue({data:st,path:tt.path,errorMaps:[tt.common.contextualErrorMap,tt.schemaErrorMap,getErrorMap(),errorMap].filter(ct=>!!ct),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:at}})}const ot={errorMap:tt.common.contextualErrorMap},it=tt.data;if(this._def.returns instanceof ZodPromise){const st=this;return OK(async function(...at){const ct=new ZodError([]),lt=await st._def.args.parseAsync(at,ot).catch(mt=>{throw ct.addIssue(rt(at,mt)),ct}),dt=await Reflect.apply(it,this,lt);return await st._def.returns._def.type.parseAsync(dt,ot).catch(mt=>{throw ct.addIssue(nt(dt,mt)),ct})})}else{const st=this;return OK(function(...at){const ct=st._def.args.safeParse(at,ot);if(!ct.success)throw new ZodError([rt(at,ct.error)]);const lt=Reflect.apply(it,this,ct.data),dt=st._def.returns.safeParse(lt,ot);if(!dt.success)throw new ZodError([nt(lt,dt.error)]);return dt.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new ZodFunction({...this._def,args:ZodTuple.create(o).rest(ZodUnknown.create())})}returns(o){return new ZodFunction({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,tt,rt){return new ZodFunction({args:o||ZodTuple.create([]).rest(ZodUnknown.create()),returns:tt||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(rt)})}}class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(o){const{ctx:tt}=this._processInputParams(o);return this._def.getter()._parse({data:tt.data,path:tt.path,parent:tt})}}ZodLazy.create=(et,o)=>new ZodLazy({getter:et,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(o)});class ZodLiteral extends ZodType{_parse(o){if(o.data!==this._def.value){const tt=this._getOrReturnCtx(o);return addIssueToContext(tt,{received:tt.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:o.data}}get value(){return this._def.value}}ZodLiteral.create=(et,o)=>new ZodLiteral({value:et,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(o)});function createZodEnum(et,o){return new ZodEnum({values:et,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(o)})}class ZodEnum extends ZodType{constructor(){super(...arguments),_ZodEnum_cache.set(this,void 0)}_parse(o){if(typeof o.data!="string"){const tt=this._getOrReturnCtx(o),rt=this._def.values;return addIssueToContext(tt,{expected:util.joinValues(rt),received:tt.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodEnum_cache)||__classPrivateFieldSet(this,_ZodEnum_cache,new Set(this._def.values)),!__classPrivateFieldGet(this,_ZodEnum_cache).has(o.data)){const tt=this._getOrReturnCtx(o),rt=this._def.values;return addIssueToContext(tt,{received:tt.data,code:ZodIssueCode.invalid_enum_value,options:rt}),INVALID}return OK(o.data)}get options(){return this._def.values}get enum(){const o={};for(const tt of this._def.values)o[tt]=tt;return o}get Values(){const o={};for(const tt of this._def.values)o[tt]=tt;return o}get Enum(){const o={};for(const tt of this._def.values)o[tt]=tt;return o}extract(o,tt=this._def){return ZodEnum.create(o,{...this._def,...tt})}exclude(o,tt=this._def){return ZodEnum.create(this.options.filter(rt=>!o.includes(rt)),{...this._def,...tt})}}_ZodEnum_cache=new WeakMap;ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{constructor(){super(...arguments),_ZodNativeEnum_cache.set(this,void 0)}_parse(o){const tt=util.getValidEnumValues(this._def.values),rt=this._getOrReturnCtx(o);if(rt.parsedType!==ZodParsedType.string&&rt.parsedType!==ZodParsedType.number){const nt=util.objectValues(tt);return addIssueToContext(rt,{expected:util.joinValues(nt),received:rt.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodNativeEnum_cache)||__classPrivateFieldSet(this,_ZodNativeEnum_cache,new Set(util.getValidEnumValues(this._def.values))),!__classPrivateFieldGet(this,_ZodNativeEnum_cache).has(o.data)){const nt=util.objectValues(tt);return addIssueToContext(rt,{received:rt.data,code:ZodIssueCode.invalid_enum_value,options:nt}),INVALID}return OK(o.data)}get enum(){return this._def.values}}_ZodNativeEnum_cache=new WeakMap;ZodNativeEnum.create=(et,o)=>new ZodNativeEnum({values:et,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(o)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(o){const{ctx:tt}=this._processInputParams(o);if(tt.parsedType!==ZodParsedType.promise&&tt.common.async===!1)return addIssueToContext(tt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:tt.parsedType}),INVALID;const rt=tt.parsedType===ZodParsedType.promise?tt.data:Promise.resolve(tt.data);return OK(rt.then(nt=>this._def.type.parseAsync(nt,{path:tt.path,errorMap:tt.common.contextualErrorMap})))}}ZodPromise.create=(et,o)=>new ZodPromise({type:et,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(o)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(o){const{status:tt,ctx:rt}=this._processInputParams(o),nt=this._def.effect||null,ot={addIssue:it=>{addIssueToContext(rt,it),it.fatal?tt.abort():tt.dirty()},get path(){return rt.path}};if(ot.addIssue=ot.addIssue.bind(ot),nt.type==="preprocess"){const it=nt.transform(rt.data,ot);if(rt.common.async)return Promise.resolve(it).then(async st=>{if(tt.value==="aborted")return INVALID;const at=await this._def.schema._parseAsync({data:st,path:rt.path,parent:rt});return at.status==="aborted"?INVALID:at.status==="dirty"||tt.value==="dirty"?DIRTY(at.value):at});{if(tt.value==="aborted")return INVALID;const st=this._def.schema._parseSync({data:it,path:rt.path,parent:rt});return st.status==="aborted"?INVALID:st.status==="dirty"||tt.value==="dirty"?DIRTY(st.value):st}}if(nt.type==="refinement"){const it=st=>{const at=nt.refinement(st,ot);if(rt.common.async)return Promise.resolve(at);if(at instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return st};if(rt.common.async===!1){const st=this._def.schema._parseSync({data:rt.data,path:rt.path,parent:rt});return st.status==="aborted"?INVALID:(st.status==="dirty"&&tt.dirty(),it(st.value),{status:tt.value,value:st.value})}else return this._def.schema._parseAsync({data:rt.data,path:rt.path,parent:rt}).then(st=>st.status==="aborted"?INVALID:(st.status==="dirty"&&tt.dirty(),it(st.value).then(()=>({status:tt.value,value:st.value}))))}if(nt.type==="transform")if(rt.common.async===!1){const it=this._def.schema._parseSync({data:rt.data,path:rt.path,parent:rt});if(!isValid(it))return it;const st=nt.transform(it.value,ot);if(st instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:tt.value,value:st}}else return this._def.schema._parseAsync({data:rt.data,path:rt.path,parent:rt}).then(it=>isValid(it)?Promise.resolve(nt.transform(it.value,ot)).then(st=>({status:tt.value,value:st})):it);util.assertNever(nt)}}ZodEffects.create=(et,o,tt)=>new ZodEffects({schema:et,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:o,...processCreateParams(tt)});ZodEffects.createWithPreprocess=(et,o,tt)=>new ZodEffects({schema:o,effect:{type:"preprocess",transform:et},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(tt)});class ZodOptional extends ZodType{_parse(o){return this._getType(o)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}ZodOptional.create=(et,o)=>new ZodOptional({innerType:et,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(o)});class ZodNullable extends ZodType{_parse(o){return this._getType(o)===ZodParsedType.null?OK(null):this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}ZodNullable.create=(et,o)=>new ZodNullable({innerType:et,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(o)});class ZodDefault extends ZodType{_parse(o){const{ctx:tt}=this._processInputParams(o);let rt=tt.data;return tt.parsedType===ZodParsedType.undefined&&(rt=this._def.defaultValue()),this._def.innerType._parse({data:rt,path:tt.path,parent:tt})}removeDefault(){return this._def.innerType}}ZodDefault.create=(et,o)=>new ZodDefault({innerType:et,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof o.default=="function"?o.default:()=>o.default,...processCreateParams(o)});class ZodCatch extends ZodType{_parse(o){const{ctx:tt}=this._processInputParams(o),rt={...tt,common:{...tt.common,issues:[]}},nt=this._def.innerType._parse({data:rt.data,path:rt.path,parent:{...rt}});return isAsync(nt)?nt.then(ot=>({status:"valid",value:ot.status==="valid"?ot.value:this._def.catchValue({get error(){return new ZodError(rt.common.issues)},input:rt.data})})):{status:"valid",value:nt.status==="valid"?nt.value:this._def.catchValue({get error(){return new ZodError(rt.common.issues)},input:rt.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(et,o)=>new ZodCatch({innerType:et,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof o.catch=="function"?o.catch:()=>o.catch,...processCreateParams(o)});class ZodNaN extends ZodType{_parse(o){if(this._getType(o)!==ZodParsedType.nan){const rt=this._getOrReturnCtx(o);return addIssueToContext(rt,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:rt.parsedType}),INVALID}return{status:"valid",value:o.data}}}ZodNaN.create=et=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(et)});const BRAND=Symbol("zod_brand");class ZodBranded extends ZodType{_parse(o){const{ctx:tt}=this._processInputParams(o),rt=tt.data;return this._def.type._parse({data:rt,path:tt.path,parent:tt})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(o){const{status:tt,ctx:rt}=this._processInputParams(o);if(rt.common.async)return(async()=>{const ot=await this._def.in._parseAsync({data:rt.data,path:rt.path,parent:rt});return ot.status==="aborted"?INVALID:ot.status==="dirty"?(tt.dirty(),DIRTY(ot.value)):this._def.out._parseAsync({data:ot.value,path:rt.path,parent:rt})})();{const nt=this._def.in._parseSync({data:rt.data,path:rt.path,parent:rt});return nt.status==="aborted"?INVALID:nt.status==="dirty"?(tt.dirty(),{status:"dirty",value:nt.value}):this._def.out._parseSync({data:nt.value,path:rt.path,parent:rt})}}static create(o,tt){return new ZodPipeline({in:o,out:tt,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(o){const tt=this._def.innerType._parse(o),rt=nt=>(isValid(nt)&&(nt.value=Object.freeze(nt.value)),nt);return isAsync(tt)?tt.then(nt=>rt(nt)):rt(tt)}unwrap(){return this._def.innerType}}ZodReadonly.create=(et,o)=>new ZodReadonly({innerType:et,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(o)});function custom(et,o={},tt){return et?ZodAny.create().superRefine((rt,nt)=>{var ot,it;if(!et(rt)){const st=typeof o=="function"?o(rt):typeof o=="string"?{message:o}:o,at=(it=(ot=st.fatal)!==null&&ot!==void 0?ot:tt)!==null&&it!==void 0?it:!0,ct=typeof st=="string"?{message:st}:st;nt.addIssue({code:"custom",...ct,fatal:at})}}):ZodAny.create()}const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(et){et.ZodString="ZodString",et.ZodNumber="ZodNumber",et.ZodNaN="ZodNaN",et.ZodBigInt="ZodBigInt",et.ZodBoolean="ZodBoolean",et.ZodDate="ZodDate",et.ZodSymbol="ZodSymbol",et.ZodUndefined="ZodUndefined",et.ZodNull="ZodNull",et.ZodAny="ZodAny",et.ZodUnknown="ZodUnknown",et.ZodNever="ZodNever",et.ZodVoid="ZodVoid",et.ZodArray="ZodArray",et.ZodObject="ZodObject",et.ZodUnion="ZodUnion",et.ZodDiscriminatedUnion="ZodDiscriminatedUnion",et.ZodIntersection="ZodIntersection",et.ZodTuple="ZodTuple",et.ZodRecord="ZodRecord",et.ZodMap="ZodMap",et.ZodSet="ZodSet",et.ZodFunction="ZodFunction",et.ZodLazy="ZodLazy",et.ZodLiteral="ZodLiteral",et.ZodEnum="ZodEnum",et.ZodEffects="ZodEffects",et.ZodNativeEnum="ZodNativeEnum",et.ZodOptional="ZodOptional",et.ZodNullable="ZodNullable",et.ZodDefault="ZodDefault",et.ZodCatch="ZodCatch",et.ZodPromise="ZodPromise",et.ZodBranded="ZodBranded",et.ZodPipeline="ZodPipeline",et.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const instanceOfType=(et,o={message:`Input not instance of ${et.name}`})=>custom(tt=>tt instanceof et,o),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:et=>ZodString.create({...et,coerce:!0}),number:et=>ZodNumber.create({...et,coerce:!0}),boolean:et=>ZodBoolean.create({...et,coerce:!0}),bigint:et=>ZodBigInt.create({...et,coerce:!0}),date:et=>ZodDate.create({...et,coerce:!0})},NEVER=INVALID;var z=Object.freeze({__proto__:null,defaultErrorMap:errorMap,setErrorMap,getErrorMap,makeIssue,EMPTY_PATH,addIssueToContext,ParseStatus,INVALID,DIRTY,OK,isAborted,isDirty,isValid,isAsync,get util(){return util},get objectUtil(){return objectUtil},ZodParsedType,getParsedType,ZodType,datetimeRegex,ZodString,ZodNumber,ZodBigInt,ZodBoolean,ZodDate,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodArray,ZodObject,ZodUnion,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodFunction,ZodLazy,ZodLiteral,ZodEnum,ZodNativeEnum,ZodPromise,ZodEffects,ZodTransformer:ZodEffects,ZodOptional,ZodNullable,ZodDefault,ZodCatch,ZodNaN,BRAND,ZodBranded,ZodPipeline,ZodReadonly,custom,Schema:ZodType,ZodSchema:ZodType,late,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind},coerce,any:anyType,array:arrayType,bigint:bigIntType,boolean:booleanType,date:dateType,discriminatedUnion:discriminatedUnionType,effect:effectsType,enum:enumType,function:functionType,instanceof:instanceOfType,intersection:intersectionType,lazy:lazyType,literal:literalType,map:mapType,nan:nanType,nativeEnum:nativeEnumType,never:neverType,null:nullType,nullable:nullableType,number:numberType,object:objectType,oboolean,onumber,optional:optionalType,ostring,pipeline:pipelineType,preprocess:preprocessType,promise:promiseType,record:recordType,set:setType,strictObject:strictObjectType,string:stringType,symbol:symbolType,transformer:effectsType,tuple:tupleType,undefined:undefinedType,union:unionType,unknown:unknownType,void:voidType,NEVER,ZodIssueCode,quotelessJson,ZodError}),define_process_env_default={};function createEnv(et){const o=et.runtimeEnvStrict??et.runtimeEnv??define_process_env_default;if(et.emptyStringAsUndefined??!1)for(const[Ct,St]of Object.entries(o))St===""&&delete o[Ct];if(!!et.skipValidation)return o;const nt=typeof et.client=="object"?et.client:{},ot=typeof et.server=="object"?et.server:{},it=typeof et.shared=="object"?et.shared:{},st=z.object(nt),at=z.object(ot),ct=z.object(it),lt=et.isServer??typeof window>"u",dt=st.merge(ct),ht=at.merge(ct).merge(st),mt=lt?ht.safeParse(o):dt.safeParse(o),ft=et.onValidationError??(Ct=>{throw console.error("❌ Invalid environment variables:",Ct.flatten().fieldErrors),new Error("Invalid environment variables")}),pt=et.onInvalidAccess??(Ct=>{throw new Error("❌ Attempted to access a server-side environment variable on the client")});if(mt.success===!1)return ft(mt.error);const gt=Ct=>et.clientPrefix?!Ct.startsWith(et.clientPrefix)&&!(Ct in ct.shape):!0,yt=Ct=>lt||!gt(Ct),bt=Ct=>Ct==="__esModule"||Ct==="$$typeof",xt=(et.extends??[]).reduce((Ct,St)=>Object.assign(Ct,St),{}),vt=Object.assign(mt.data,xt);return new Proxy(vt,{get(Ct,St){if(typeof St=="string"&&!bt(St))return yt(St)?Reflect.get(Ct,St):pt(St)}})}const __vite_import_meta_env__={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},env=createEnv({clientPrefix:"VITE_",client:{VITE_WALLETCONNECT_PROJECT_ID:z.string().min(1)},runtimeEnv:__vite_import_meta_env__}),config=createConfig(defaultConfig({appName:"BuddyBook",walletConnectProjectId:env.VITE_WALLETCONNECT_PROJECT_ID,chains:[mainnet],transports:{[mainnet.id]:http()}})),queryClient=new QueryClient;createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(reactExports.StrictMode,{children:jsxRuntimeExports.jsx(WagmiProvider,{config,children:jsxRuntimeExports.jsx(QueryClientProvider,{client:queryClient,children:jsxRuntimeExports.jsx(ConnectKitProvider,{children:jsxRuntimeExports.jsx(LightNodeProvider,{options:WAKU_NODE_OPTIONS,children:jsxRuntimeExports.jsx(BrowserRouter,{children:jsxRuntimeExports.jsx(App,{})})})})})})}));export{isHex as A,BytesSizeMismatchError as B,dijkstraExports as C,EventEmitter$1 as E,HttpRequestError as H,InvalidAddressError as I,__vitePreload as _,stringToHex as a,bytesToHex$3 as b,concat$6 as c,commonjsGlobal as d,encodeAbiParameters as e,encodeFunctionData as f,getAugmentedNamespace as g,getDefaultExportFromCjs as h,isAddress as i,browserExports as j,keccak256$1 as k,tslib_es6$1 as l,buffer as m,numberToHex as n,allocUnsafe$h as o,BASES$1 as p,fromString$2 as q,detect as r,size$2 as s,toHex as t,__viteBrowserExternal$1 as u,BaseError$3 as v,getUrl as w,stringify$2 as x,decodeErrorResult as y,call as z}; diff --git a/buddybook/assets/index-D2uqR4Ry.js b/buddybook/assets/index-D2uqR4Ry.js new file mode 100644 index 0000000..91588f5 --- /dev/null +++ b/buddybook/assets/index-D2uqR4Ry.js @@ -0,0 +1 @@ +import{d as M,g as sn,h as an}from"./index-B-6Lwopd.js";import{j as on,s as cn,r as _t,a as dn,b as ln}from"./hooks.module-D7M4pAco.js";var Et={},te={},me={};Object.defineProperty(me,"__esModule",{value:!0});me.walletLogo=void 0;const un=(n,e)=>{let t;switch(n){case"standard":return t=e,`data:image/svg+xml,%3Csvg width='${e}' height='${t}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `;case"circle":return t=e,`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${e}' height='${t}' viewBox='0 0 999.81 999.81'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052fe;%7D.cls-2%7Bfill:%23fefefe;%7D.cls-3%7Bfill:%230152fe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M655-115.9h56c.83,1.59,2.36.88,3.56,1a478,478,0,0,1,75.06,10.42C891.4-81.76,978.33-32.58,1049.19,44q116.7,126,131.94,297.61c.38,4.14-.34,8.53,1.78,12.45v59c-1.58.84-.91,2.35-1,3.56a482.05,482.05,0,0,1-10.38,74.05c-24,106.72-76.64,196.76-158.83,268.93s-178.18,112.82-287.2,122.6c-4.83.43-9.86-.25-14.51,1.77H654c-1-1.68-2.69-.91-4.06-1a496.89,496.89,0,0,1-105.9-18.59c-93.54-27.42-172.78-77.59-236.91-150.94Q199.34,590.1,184.87,426.58c-.47-5.19.25-10.56-1.77-15.59V355c1.68-1,.91-2.7,1-4.06a498.12,498.12,0,0,1,18.58-105.9c26-88.75,72.64-164.9,140.6-227.57q126-116.27,297.21-131.61C645.32-114.57,650.35-113.88,655-115.9Zm377.92,500c0-192.44-156.31-349.49-347.56-350.15-194.13-.68-350.94,155.13-352.29,347.42-1.37,194.55,155.51,352.1,348.56,352.47C876.15,734.23,1032.93,577.84,1032.93,384.11Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-2' d='M1032.93,384.11c0,193.73-156.78,350.12-351.29,349.74-193-.37-349.93-157.92-348.56-352.47C334.43,189.09,491.24,33.28,685.37,34,876.62,34.62,1032.94,191.67,1032.93,384.11ZM683,496.81q43.74,0,87.48,0c15.55,0,25.32-9.72,25.33-25.21q0-87.48,0-175c0-15.83-9.68-25.46-25.59-25.46H595.77c-15.88,0-25.57,9.64-25.58,25.46q0,87.23,0,174.45c0,16.18,9.59,25.7,25.84,25.71Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-3' d='M683,496.81H596c-16.25,0-25.84-9.53-25.84-25.71q0-87.23,0-174.45c0-15.82,9.7-25.46,25.58-25.46H770.22c15.91,0,25.59,9.63,25.59,25.46q0,87.47,0,175c0,15.49-9.78,25.2-25.33,25.21Q726.74,496.84,683,496.81Z' transform='translate(-183.1 115.9)'/%3E%3C/svg%3E`;case"text":return t=(.1*e).toFixed(2),`data:image/svg+xml,%3Csvg width='${e}' height='${t}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogo":return t=(.25*e).toFixed(2),`data:image/svg+xml,%3Csvg width='${e}' height='${t}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;case"textLight":return t=(.1*e).toFixed(2),`data:image/svg+xml,%3Csvg width='${e}' height='${t}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogoLight":return t=(.25*e).toFixed(2),`data:image/svg+xml,%3Csvg width='${e}' height='${t}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;default:return t=e,`data:image/svg+xml,%3Csvg width='${e}' height='${t}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `}};me.walletLogo=un;var be={},j={},U={};Object.defineProperty(U,"__esModule",{value:!0});U.errorValues=U.standardErrorCodes=void 0;U.standardErrorCodes={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}};U.errorValues={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}};var ye={},$e={};(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.serialize=n.getErrorCode=n.isValidCode=n.getMessageFromCode=n.JSON_RPC_SERVER_ERROR_MESSAGE=void 0;const e=U,t="Unspecified error message.";n.JSON_RPC_SERVER_ERROR_MESSAGE="Unspecified server error.";function r(d,p=t){if(d&&Number.isInteger(d)){const m=d.toString();if(h(e.errorValues,m))return e.errorValues[m].message;if(c(d))return n.JSON_RPC_SERVER_ERROR_MESSAGE}return p}n.getMessageFromCode=r;function s(d){if(!Number.isInteger(d))return!1;const p=d.toString();return!!(e.errorValues[p]||c(d))}n.isValidCode=s;function i(d){var p;if(typeof d=="number")return d;if(a(d))return(p=d.code)!==null&&p!==void 0?p:d.errorCode}n.getErrorCode=i;function a(d){return typeof d=="object"&&d!==null&&(typeof d.code=="number"||typeof d.errorCode=="number")}function o(d,{shouldIncludeStack:p=!1}={}){const m={};if(d&&typeof d=="object"&&!Array.isArray(d)&&h(d,"code")&&s(d.code)){const B=d;m.code=B.code,B.message&&typeof B.message=="string"?(m.message=B.message,h(B,"data")&&(m.data=B.data)):(m.message=r(m.code),m.data={originalError:l(d)})}else m.code=e.standardErrorCodes.rpc.internal,m.message=f(d,"message")?d.message:t,m.data={originalError:l(d)};return p&&(m.stack=f(d,"stack")?d.stack:void 0),m}n.serialize=o;function c(d){return d>=-32099&&d<=-32e3}function l(d){return d&&typeof d=="object"&&!Array.isArray(d)?Object.assign({},d):d}function h(d,p){return Object.prototype.hasOwnProperty.call(d,p)}function f(d,p){return typeof d=="object"&&d!==null&&p in d&&typeof d[p]=="string"}})($e);Object.defineProperty(ye,"__esModule",{value:!0});ye.standardErrors=void 0;const v=U,St=$e;ye.standardErrors={rpc:{parse:n=>C(v.standardErrorCodes.rpc.parse,n),invalidRequest:n=>C(v.standardErrorCodes.rpc.invalidRequest,n),invalidParams:n=>C(v.standardErrorCodes.rpc.invalidParams,n),methodNotFound:n=>C(v.standardErrorCodes.rpc.methodNotFound,n),internal:n=>C(v.standardErrorCodes.rpc.internal,n),server:n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:e}=n;if(!Number.isInteger(e)||e>-32005||e<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return C(e,n)},invalidInput:n=>C(v.standardErrorCodes.rpc.invalidInput,n),resourceNotFound:n=>C(v.standardErrorCodes.rpc.resourceNotFound,n),resourceUnavailable:n=>C(v.standardErrorCodes.rpc.resourceUnavailable,n),transactionRejected:n=>C(v.standardErrorCodes.rpc.transactionRejected,n),methodNotSupported:n=>C(v.standardErrorCodes.rpc.methodNotSupported,n),limitExceeded:n=>C(v.standardErrorCodes.rpc.limitExceeded,n)},provider:{userRejectedRequest:n=>$(v.standardErrorCodes.provider.userRejectedRequest,n),unauthorized:n=>$(v.standardErrorCodes.provider.unauthorized,n),unsupportedMethod:n=>$(v.standardErrorCodes.provider.unsupportedMethod,n),disconnected:n=>$(v.standardErrorCodes.provider.disconnected,n),chainDisconnected:n=>$(v.standardErrorCodes.provider.chainDisconnected,n),unsupportedChain:n=>$(v.standardErrorCodes.provider.unsupportedChain,n),custom:n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:e,message:t,data:r}=n;if(!t||typeof t!="string")throw new Error('"message" must be a nonempty string');return new It(e,t,r)}}};function C(n,e){const[t,r]=Ct(e);return new kt(n,t||(0,St.getMessageFromCode)(n),r)}function $(n,e){const[t,r]=Ct(e);return new It(n,t||(0,St.getMessageFromCode)(n),r)}function Ct(n){if(n){if(typeof n=="string")return[n];if(typeof n=="object"&&!Array.isArray(n)){const{message:e,data:t}=n;if(e&&typeof e!="string")throw new Error("Must specify string message.");return[e||void 0,t]}}return[]}class kt extends Error{constructor(e,t,r){if(!Number.isInteger(e))throw new Error('"code" must be an integer.');if(!t||typeof t!="string")throw new Error('"message" must be a nonempty string.');super(t),this.code=e,r!==void 0&&(this.data=r)}}class It extends kt{constructor(e,t,r){if(!hn(e))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(e,t,r)}}function hn(n){return Number.isInteger(n)&&n>=1e3&&n<=4999}(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.standardErrors=n.standardErrorCodes=void 0;var e=U;Object.defineProperty(n,"standardErrorCodes",{enumerable:!0,get:function(){return e.standardErrorCodes}});var t=ye;Object.defineProperty(n,"standardErrors",{enumerable:!0,get:function(){return t.standardErrors}})})(j);var we={},Q={};Object.defineProperty(Q,"__esModule",{value:!0});Q.isErrorResponse=void 0;function gn(n){return n.errorMessage!==void 0}Q.isErrorResponse=gn;var K={};Object.defineProperty(K,"__esModule",{value:!0});K.LIB_VERSION=void 0;K.LIB_VERSION="4.0.4";Object.defineProperty(we,"__esModule",{value:!0});we.serializeError=void 0;const pn=Q,fn=K,mn=U,bn=$e;function yn(n,e){const t=(0,bn.serialize)(wn(n),{shouldIncludeStack:!0}),r=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");r.searchParams.set("version",fn.LIB_VERSION),r.searchParams.set("code",t.code.toString());const s=vn(t.data,e);return s&&r.searchParams.set("method",s),r.searchParams.set("message",t.message),Object.assign(Object.assign({},t),{docUrl:r.href})}we.serializeError=yn;function wn(n){return typeof n=="string"?{message:n,code:mn.standardErrorCodes.rpc.internal}:(0,pn.isErrorResponse)(n)?Object.assign(Object.assign({},n),{message:n.errorMessage,code:n.errorCode,data:{method:n.method}}):n}function vn(n,e){const t=n==null?void 0:n.method;if(t)return t;if(e!==void 0){if(typeof e=="string")return e;if(Array.isArray(e)){if(e.length>0)return e[0].method}else return e.method}}var _={};Object.defineProperty(_,"__esModule",{value:!0});_.RegExpString=_.IntNumber=_.BigIntString=_.AddressString=_.HexString=_.OpaqueType=void 0;function ne(){return n=>n}_.OpaqueType=ne;_.HexString=ne();_.AddressString=ne();_.BigIntString=ne();function _n(n){return Math.floor(n)}_.IntNumber=_n;_.RegExpString=ne();var u={};Object.defineProperty(u,"__esModule",{value:!0});u.areAddressArraysEqual=u.getFavicon=u.range=u.isBigNumber=u.ensureParsedJSONObject=u.ensureBigInt=u.ensureRegExpString=u.ensureIntNumber=u.ensureBuffer=u.ensureAddressString=u.ensureEvenLengthHexString=u.ensureHexString=u.isHexString=u.prepend0x=u.strip0x=u.has0xPrefix=u.hexStringFromIntNumber=u.intNumberFromHexString=u.bigIntStringFromBigInt=u.hexStringFromBuffer=u.hexStringToUint8Array=u.uint8ArrayToHex=u.randomBytesHex=void 0;const q=j,I=_,Mt=/^[0-9]*$/,Lt=/^[a-f0-9]*$/;function En(n){return At(crypto.getRandomValues(new Uint8Array(n)))}u.randomBytesHex=En;function At(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}u.uint8ArrayToHex=At;function Sn(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}u.hexStringToUint8Array=Sn;function Cn(n,e=!1){const t=n.toString("hex");return(0,I.HexString)(e?`0x${t}`:t)}u.hexStringFromBuffer=Cn;function kn(n){return(0,I.BigIntString)(n.toString(10))}u.bigIntStringFromBigInt=kn;function In(n){return(0,I.IntNumber)(Number(BigInt(se(n,!0))))}u.intNumberFromHexString=In;function Mn(n){return(0,I.HexString)(`0x${BigInt(n).toString(16)}`)}u.hexStringFromIntNumber=Mn;function Fe(n){return n.startsWith("0x")||n.startsWith("0X")}u.has0xPrefix=Fe;function ve(n){return Fe(n)?n.slice(2):n}u.strip0x=ve;function Rt(n){return Fe(n)?`0x${n.slice(2)}`:`0x${n}`}u.prepend0x=Rt;function re(n){if(typeof n!="string")return!1;const e=ve(n).toLowerCase();return Lt.test(e)}u.isHexString=re;function xt(n,e=!1){if(typeof n=="string"){const t=ve(n).toLowerCase();if(Lt.test(t))return(0,I.HexString)(e?`0x${t}`:t)}throw q.standardErrors.rpc.invalidParams(`"${String(n)}" is not a hexadecimal string`)}u.ensureHexString=xt;function se(n,e=!1){let t=xt(n,!1);return t.length%2===1&&(t=(0,I.HexString)(`0${t}`)),e?(0,I.HexString)(`0x${t}`):t}u.ensureEvenLengthHexString=se;function Ln(n){if(typeof n=="string"){const e=ve(n).toLowerCase();if(re(e)&&e.length===40)return(0,I.AddressString)(Rt(e))}throw q.standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(n)}`)}u.ensureAddressString=Ln;function An(n){if(Buffer.isBuffer(n))return n;if(typeof n=="string"){if(re(n)){const e=se(n,!1);return Buffer.from(e,"hex")}return Buffer.from(n,"utf8")}throw q.standardErrors.rpc.invalidParams(`Not binary data: ${String(n)}`)}u.ensureBuffer=An;function Pt(n){if(typeof n=="number"&&Number.isInteger(n))return(0,I.IntNumber)(n);if(typeof n=="string"){if(Mt.test(n))return(0,I.IntNumber)(Number(n));if(re(n))return(0,I.IntNumber)(Number(BigInt(se(n,!0))))}throw q.standardErrors.rpc.invalidParams(`Not an integer: ${String(n)}`)}u.ensureIntNumber=Pt;function Rn(n){if(n instanceof RegExp)return(0,I.RegExpString)(n.toString());throw q.standardErrors.rpc.invalidParams(`Not a RegExp: ${String(n)}`)}u.ensureRegExpString=Rn;function xn(n){if(n!==null&&(typeof n=="bigint"||Nt(n)))return BigInt(n.toString(10));if(typeof n=="number")return BigInt(Pt(n));if(typeof n=="string"){if(Mt.test(n))return BigInt(n);if(re(n))return BigInt(se(n,!0))}throw q.standardErrors.rpc.invalidParams(`Not an integer: ${String(n)}`)}u.ensureBigInt=xn;function Pn(n){if(typeof n=="string")return JSON.parse(n);if(typeof n=="object")return n;throw q.standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(n)}`)}u.ensureParsedJSONObject=Pn;function Nt(n){if(n==null||typeof n.constructor!="function")return!1;const{constructor:e}=n;return typeof e.config=="function"&&typeof e.EUCLID=="number"}u.isBigNumber=Nt;function Nn(n,e){return Array.from({length:e-n},(t,r)=>n+r)}u.range=Nn;function Tn(){const n=document.querySelector('link[sizes="192x192"]')||document.querySelector('link[sizes="180x180"]')||document.querySelector('link[rel="icon"]')||document.querySelector('link[rel="shortcut icon"]'),{protocol:e,host:t}=document.location,r=n?n.getAttribute("href"):null;return!r||r.startsWith("javascript:")||r.startsWith("vbscript:")?null:r.startsWith("http://")||r.startsWith("https://")||r.startsWith("data:")?r:r.startsWith("//")?e+r:`${e}//${t}${r}`}u.getFavicon=Tn;function jn(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}u.areAddressArraysEqual=jn;var P={},_e={},Ee={},y={};Object.defineProperty(y,"__esModule",{value:!0});y.decryptContent=y.encryptContent=y.importKeyFromHexString=y.exportKeyToHexString=y.decrypt=y.encrypt=y.deriveSharedSecret=y.generateKeyPair=void 0;const Tt=u;async function On(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}y.generateKeyPair=On;async function Dn(n,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}y.deriveSharedSecret=Dn;async function jt(n,e){const t=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},n,new TextEncoder().encode(e));return{iv:t,cipherText:r}}y.encrypt=jt;async function Ot(n,{iv:e,cipherText:t}){const r=await crypto.subtle.decrypt({name:"AES-GCM",iv:e},n,t);return new TextDecoder().decode(r)}y.decrypt=Ot;function Dt(n){switch(n){case"public":return"spki";case"private":return"pkcs8"}}async function Wn(n,e){const t=Dt(n),r=await crypto.subtle.exportKey(t,e);return(0,Tt.uint8ArrayToHex)(new Uint8Array(r))}y.exportKeyToHexString=Wn;async function Un(n,e){const t=Dt(n),r=(0,Tt.hexStringToUint8Array)(e).buffer;return await crypto.subtle.importKey(t,r,{name:"ECDH",namedCurve:"P-256"},!0,n==="private"?["deriveKey"]:[])}y.importKeyFromHexString=Un;async function Bn(n,e){const t=JSON.stringify(n,(r,s)=>{if(!(s instanceof Error))return s;const i=s;return Object.assign(Object.assign({},i.code?{code:i.code}:{}),{message:i.message})});return jt(e,t)}y.encryptContent=Bn;async function Hn(n,e){return JSON.parse(await Ot(e,n))}y.decryptContent=Hn;var O={};Object.defineProperty(O,"__esModule",{value:!0});O.ScopedLocalStorage=void 0;class fe{constructor(e,t){this.scope=e,this.module=t}setItem(e,t){localStorage.setItem(this.scopedKey(e),t)}getItem(e){return localStorage.getItem(this.scopedKey(e))}removeItem(e){localStorage.removeItem(this.scopedKey(e))}clear(){const e=this.scopedKey(""),t=[];for(let r=0;rlocalStorage.removeItem(r))}scopedKey(e){return`-${this.scope}${this.module?`:${this.module}`:""}:${e}`}static clearAll(){new fe("CBWSDK").clear(),new fe("walletlink").clear()}}O.ScopedLocalStorage=fe;Object.defineProperty(Ee,"__esModule",{value:!0});Ee.SCWKeyManager=void 0;const oe=y,Kn=O,De={storageKey:"ownPrivateKey",keyType:"private"},We={storageKey:"ownPublicKey",keyType:"public"},Ue={storageKey:"peerPublicKey",keyType:"public"};class qn{constructor(){this.storage=new Kn.ScopedLocalStorage("CBWSDK","SCWKeyManager"),this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null}async getOwnPublicKey(){return await this.loadKeysIfNeeded(),this.ownPublicKey}async getSharedSecret(){return await this.loadKeysIfNeeded(),this.sharedSecret}async setPeerPublicKey(e){this.sharedSecret=null,this.peerPublicKey=e,await this.storeKey(Ue,e),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,this.storage.removeItem(We.storageKey),this.storage.removeItem(De.storageKey),this.storage.removeItem(Ue.storageKey)}async generateKeyPair(){const e=await(0,oe.generateKeyPair)();this.ownPrivateKey=e.privateKey,this.ownPublicKey=e.publicKey,await this.storeKey(De,e.privateKey),await this.storeKey(We,e.publicKey)}async loadKeysIfNeeded(){if(this.ownPrivateKey===null&&(this.ownPrivateKey=await this.loadKey(De)),this.ownPublicKey===null&&(this.ownPublicKey=await this.loadKey(We)),(this.ownPrivateKey===null||this.ownPublicKey===null)&&await this.generateKeyPair(),this.peerPublicKey===null&&(this.peerPublicKey=await this.loadKey(Ue)),this.sharedSecret===null){if(this.ownPrivateKey===null||this.peerPublicKey===null)return;this.sharedSecret=await(0,oe.deriveSharedSecret)(this.ownPrivateKey,this.peerPublicKey)}}async loadKey(e){const t=this.storage.getItem(e.storageKey);return t?(0,oe.importKeyFromHexString)(e.keyType,t):null}async storeKey(e,t){const r=await(0,oe.exportKeyToHexString)(e.keyType,t);this.storage.setItem(e.storageKey,r)}}Ee.SCWKeyManager=qn;var Se={};Object.defineProperty(Se,"__esModule",{value:!0});Se.SCWStateManager=void 0;const $n=O,Qe="accounts",Xe="activeChain",et="availableChains",tt="walletCapabilities";class Fn{get accounts(){return this._accounts}get activeChain(){return this._activeChain}get walletCapabilities(){return this._walletCapabilities}constructor(e){var t,r;this.storage=new $n.ScopedLocalStorage("CBWSDK","SCWStateManager"),this.updateListener=e.updateListener,this.availableChains=this.loadItemFromStorage(et),this._walletCapabilities=this.loadItemFromStorage(tt);const s=this.loadItemFromStorage(Qe),i=this.loadItemFromStorage(Xe);s&&this.updateListener.onAccountsUpdate({accounts:s,source:"storage"}),i&&this.updateListener.onChainUpdate({chain:i,source:"storage"}),this._accounts=s||[],this._activeChain=i||{id:(r=(t=e.appChainIds)===null||t===void 0?void 0:t[0])!==null&&r!==void 0?r:1}}updateAccounts(e){this._accounts=e,this.storeItemToStorage(Qe,e),this.updateListener.onAccountsUpdate({accounts:e,source:"wallet"})}switchChain(e){var t;const r=(t=this.availableChains)===null||t===void 0?void 0:t.find(s=>s.id===e);return r?(r===this._activeChain||(this._activeChain=r,this.storeItemToStorage(Xe,r),this.updateListener.onChainUpdate({chain:r,source:"wallet"})),!0):!1}updateAvailableChains(e){if(!e||Object.keys(e).length===0)return;const t=Object.entries(e).map(([r,s])=>({id:Number(r),rpcUrl:s}));this.availableChains=t,this.storeItemToStorage(et,t),this.switchChain(this._activeChain.id)}updateWalletCapabilities(e){this._walletCapabilities=e,this.storeItemToStorage(tt,e)}storeItemToStorage(e,t){this.storage.setItem(e,JSON.stringify(t))}loadItemFromStorage(e){const t=this.storage.getItem(e);return t?JSON.parse(t):void 0}clear(){this.storage.clear()}}Se.SCWStateManager=Fn;Object.defineProperty(_e,"__esModule",{value:!0});_e.SCWSigner=void 0;const zn=Ee,Vn=Se,ce=j,nt=u,de=y;class Zn{constructor(e){this.metadata=e.metadata,this.communicator=e.communicator,this.keyManager=new zn.SCWKeyManager,this.stateManager=new Vn.SCWStateManager({appChainIds:this.metadata.appChainIds,updateListener:e.updateListener}),this.handshake=this.handshake.bind(this),this.request=this.request.bind(this),this.createRequestMessage=this.createRequestMessage.bind(this),this.decryptResponseMessage=this.decryptResponseMessage.bind(this)}async handshake(){const e=await this.createRequestMessage({handshake:{method:"eth_requestAccounts",params:this.metadata}}),t=await this.communicator.postRequestAndWaitForResponse(e);if("failure"in t.content)throw t.content.failure;const r=await(0,de.importKeyFromHexString)("public",t.sender);await this.keyManager.setPeerPublicKey(r);const s=await this.decryptResponseMessage(t);this.updateInternalState({method:"eth_requestAccounts"},s);const i=s.result;if("error"in i)throw i.error;return this.stateManager.accounts}async request(e){const t=this.tryLocalHandling(e);if(t!==void 0){if(t instanceof Error)throw t;return t}await this.communicator.waitForPopupLoaded();const r=await this.sendEncryptedRequest(e),s=await this.decryptResponseMessage(r);this.updateInternalState(e,s);const i=s.result;if("error"in i)throw i.error;return i.value}async disconnect(){this.stateManager.clear(),await this.keyManager.clear()}tryLocalHandling(e){var t;switch(e.method){case"wallet_switchEthereumChain":{const r=e.params;if(!r||!(!((t=r[0])===null||t===void 0)&&t.chainId))throw ce.standardErrors.rpc.invalidParams();const s=(0,nt.ensureIntNumber)(r[0].chainId);return this.stateManager.switchChain(s)?null:void 0}case"wallet_getCapabilities":{const r=this.stateManager.walletCapabilities;if(!r)throw ce.standardErrors.provider.unauthorized("No wallet capabilities found, please disconnect and reconnect");return r}default:return}}async sendEncryptedRequest(e){const t=await this.keyManager.getSharedSecret();if(!t)throw ce.standardErrors.provider.unauthorized("No valid session found, try requestAccounts before other methods");const r=await(0,de.encryptContent)({action:e,chainId:this.stateManager.activeChain.id},t),s=await this.createRequestMessage({encrypted:r});return this.communicator.postRequestAndWaitForResponse(s)}async createRequestMessage(e){const t=await(0,de.exportKeyToHexString)("public",await this.keyManager.getOwnPublicKey());return{id:crypto.randomUUID(),sender:t,content:e,timestamp:new Date}}async decryptResponseMessage(e){const t=e.content;if("failure"in t)throw t.failure;const r=await this.keyManager.getSharedSecret();if(!r)throw ce.standardErrors.provider.unauthorized("Invalid session");return(0,de.decryptContent)(t.encrypted,r)}updateInternalState(e,t){var r,s;const i=(r=t.data)===null||r===void 0?void 0:r.chains;i&&this.stateManager.updateAvailableChains(i);const a=(s=t.data)===null||s===void 0?void 0:s.capabilities;a&&this.stateManager.updateWalletCapabilities(a);const o=t.result;if(!("error"in o))switch(e.method){case"eth_requestAccounts":{const c=o.value;this.stateManager.updateAccounts(c);break}case"wallet_switchEthereumChain":{if(o.value!==null)return;const c=e.params,l=(0,nt.ensureIntNumber)(c[0].chainId);this.stateManager.switchChain(l);break}}}}_e.SCWSigner=Zn;var Ce={};const Gn=on;function Wt(n){return Buffer.allocUnsafe(n).fill(0)}function Yn(n){return n.toString(2).length}function Ut(n,e){let t=n.toString(16);t.length%2!==0&&(t="0"+t);const r=t.match(/.{1,2}/g).map(s=>parseInt(s,16));for(;r.length"u")throw new Error("Not an array?");if(t=Ft(n),t!=="dynamic"&&t!==0&&e.length>t)throw new Error("Elements exceed array size: "+t);s=[],n=n.slice(0,n.lastIndexOf("[")),typeof e=="string"&&(e=JSON.parse(e));for(i in e)s.push(R(n,e[i]));if(t==="dynamic"){var a=R("uint256",e.length);s.unshift(a)}return Buffer.concat(s)}else{if(n==="bytes")return e=new Buffer(e),s=Buffer.concat([R("uint256",e.length),e]),e.length%32!==0&&(s=Buffer.concat([s,E.zeros(32-e.length%32)])),s;if(n.startsWith("bytes")){if(t=G(n),t<1||t>32)throw new Error("Invalid bytes width: "+t);return E.setLengthRight(e,32)}else if(n.startsWith("uint")){if(t=G(n),t%8||t<8||t>256)throw new Error("Invalid uint width: "+t);r=H(e);const o=E.bitLengthFromBigInt(r);if(o>t)throw new Error("Supplied uint exceeds width: "+t+" vs "+o);if(r<0)throw new Error("Supplied uint is negative");return E.bufferBEFromBigInt(r,32)}else if(n.startsWith("int")){if(t=G(n),t%8||t<8||t>256)throw new Error("Invalid int width: "+t);r=H(e);const o=E.bitLengthFromBigInt(r);if(o>t)throw new Error("Supplied int exceeds width: "+t+" vs "+o);const c=E.twosFromBigInt(r,256);return E.bufferBEFromBigInt(c,32)}else if(n.startsWith("ufixed")){if(t=rt(n),r=H(e),r<0)throw new Error("Supplied ufixed is negative");return R("uint256",r*BigInt(2)**BigInt(t[1]))}else if(n.startsWith("fixed"))return t=rt(n),R("int256",H(e)*BigInt(2)**BigInt(t[1]))}throw new Error("Unsupported or invalid type: "+n)}function nr(n){return n==="string"||n==="bytes"||Ft(n)==="dynamic"}function rr(n){return n.lastIndexOf("]")===n.length-1}function sr(n,e){var t=[],r=[],s=32*n.length;for(var i in n){var a=$t(n[i]),o=e[i],c=R(a,o);nr(a)?(t.push(R("uint256",s)),r.push(c),s+=c.length):t.push(c)}return Buffer.concat(t.concat(r))}function zt(n,e){if(n.length!==e.length)throw new Error("Number of types are not matching the values");for(var t,r,s=[],i=0;i32)throw new Error("Invalid bytes width: "+t);s.push(E.setLengthRight(o,t))}else if(a.startsWith("uint")){if(t=G(a),t%8||t<8||t>256)throw new Error("Invalid uint width: "+t);r=H(o);const c=E.bitLengthFromBigInt(r);if(c>t)throw new Error("Supplied uint exceeds width: "+t+" vs "+c);s.push(E.bufferBEFromBigInt(r,t/8))}else if(a.startsWith("int")){if(t=G(a),t%8||t<8||t>256)throw new Error("Invalid int width: "+t);r=H(o);const c=E.bitLengthFromBigInt(r);if(c>t)throw new Error("Supplied int exceeds width: "+t+" vs "+c);const l=E.twosFromBigInt(r,t);s.push(E.bufferBEFromBigInt(l,t/8))}else throw new Error("Unsupported or invalid type: "+a)}return Buffer.concat(s)}function ir(n,e){return E.keccak(zt(n,e))}var ar={rawEncode:sr,solidityPack:zt,soliditySHA3:ir};const A=qt,ee=ar,Vt={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},Be={encodeData(n,e,t,r=!0){const s=["bytes32"],i=[this.hashType(n,t)];if(r){const a=(o,c,l)=>{if(t[c]!==void 0)return["bytes32",l==null?"0x0000000000000000000000000000000000000000000000000000000000000000":A.keccak(this.encodeData(c,l,t,r))];if(l===void 0)throw new Error(`missing value for field ${o} of type ${c}`);if(c==="bytes")return["bytes32",A.keccak(l)];if(c==="string")return typeof l=="string"&&(l=Buffer.from(l,"utf8")),["bytes32",A.keccak(l)];if(c.lastIndexOf("]")===c.length-1){const h=c.slice(0,c.lastIndexOf("[")),f=l.map(d=>a(o,h,d));return["bytes32",A.keccak(ee.rawEncode(f.map(([d])=>d),f.map(([,d])=>d)))]}return[c,l]};for(const o of t[n]){const[c,l]=a(o.name,o.type,e[o.name]);s.push(c),i.push(l)}}else for(const a of t[n]){let o=e[a.name];if(o!==void 0)if(a.type==="bytes")s.push("bytes32"),o=A.keccak(o),i.push(o);else if(a.type==="string")s.push("bytes32"),typeof o=="string"&&(o=Buffer.from(o,"utf8")),o=A.keccak(o),i.push(o);else if(t[a.type]!==void 0)s.push("bytes32"),o=A.keccak(this.encodeData(a.type,o,t,r)),i.push(o);else{if(a.type.lastIndexOf("]")===a.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");s.push(a.type),i.push(o)}}return ee.rawEncode(s,i)},encodeType(n,e){let t="",r=this.findTypeDependencies(n,e).filter(s=>s!==n);r=[n].concat(r.sort());for(const s of r){if(!e[s])throw new Error("No type definition specified: "+s);t+=s+"("+e[s].map(({name:a,type:o})=>o+" "+a).join(",")+")"}return t},findTypeDependencies(n,e,t=[]){if(n=n.match(/^\w*/)[0],t.includes(n)||e[n]===void 0)return t;t.push(n);for(const r of e[n])for(const s of this.findTypeDependencies(r.type,e,t))!t.includes(s)&&t.push(s);return t},hashStruct(n,e,t,r=!0){return A.keccak(this.encodeData(n,e,t,r))},hashType(n,e){return A.keccak(this.encodeType(n,e))},sanitizeData(n){const e={};for(const t in Vt.properties)n[t]&&(e[t]=n[t]);return e.types&&(e.types=Object.assign({EIP712Domain:[]},e.types)),e},hash(n,e=!0){const t=this.sanitizeData(n),r=[Buffer.from("1901","hex")];return r.push(this.hashStruct("EIP712Domain",t.domain,t.types,e)),t.primaryType!=="EIP712Domain"&&r.push(this.hashStruct(t.primaryType,t.message,t.types,e)),A.keccak(Buffer.concat(r))}};var or={TYPED_MESSAGE_SCHEMA:Vt,TypedDataUtils:Be,hashForSignTypedDataLegacy:function(n){return cr(n.data)},hashForSignTypedData_v3:function(n){return Be.hash(n.data,!1)},hashForSignTypedData_v4:function(n){return Be.hash(n.data)}};function cr(n){const e=new Error("Expect argument to be non-empty array");if(typeof n!="object"||!n.length)throw e;const t=n.map(function(i){return i.type==="bytes"?A.toBuffer(i.value):i.value}),r=n.map(function(i){return i.type}),s=n.map(function(i){if(!i.name)throw e;return i.type+" "+i.name});return ee.soliditySHA3(["bytes32","bytes32"],[ee.soliditySHA3(new Array(n.length).fill("string"),s),ee.soliditySHA3(r,t)])}var N={};Object.defineProperty(N,"__esModule",{value:!0});N.APP_VERSION_KEY=N.LOCAL_STORAGE_ADDRESSES_KEY=N.WALLET_USER_NAME_KEY=void 0;N.WALLET_USER_NAME_KEY="walletUsername";N.LOCAL_STORAGE_ADDRESSES_KEY="Addresses";N.APP_VERSION_KEY="AppVersion";var ie={};Object.defineProperty(ie,"__esModule",{value:!0});ie.RelayEventManager=void 0;const dr=u;class lr{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const e=this._nextRequestId,t=(0,dr.prepend0x)(e.toString(16));return this.callbacks.get(t)&&this.callbacks.delete(t),e}}ie.RelayEventManager=lr;var Ie={},Me={},Le={};Object.defineProperty(Le,"__esModule",{value:!0});Le.WalletLinkCipher=void 0;const le=u;class ur{constructor(e){this.secret=e}async encrypt(e){const t=this.secret;if(t.length!==64)throw Error("secret must be 256 bits");const r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.importKey("raw",(0,le.hexStringToUint8Array)(t),{name:"aes-gcm"},!1,["encrypt","decrypt"]),i=new TextEncoder,a=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},s,i.encode(e)),o=16,c=a.slice(a.byteLength-o),l=a.slice(0,a.byteLength-o),h=new Uint8Array(c),f=new Uint8Array(l),d=new Uint8Array([...r,...h,...f]);return(0,le.uint8ArrayToHex)(d)}async decrypt(e){const t=this.secret;if(t.length!==64)throw Error("secret must be 256 bits");return new Promise((r,s)=>{(async function(){const i=await crypto.subtle.importKey("raw",(0,le.hexStringToUint8Array)(t),{name:"aes-gcm"},!1,["encrypt","decrypt"]),a=(0,le.hexStringToUint8Array)(e),o=a.slice(0,12),c=a.slice(12,28),l=a.slice(28),h=new Uint8Array([...l,...c]),f={name:"AES-GCM",iv:new Uint8Array(o)};try{const d=await window.crypto.subtle.decrypt(f,i,h),p=new TextDecoder;r(p.decode(d))}catch(d){s(d)}})()})}}Le.WalletLinkCipher=ur;var Ae={};Object.defineProperty(Ae,"__esModule",{value:!0});Ae.WalletLinkHTTP=void 0;class hr{constructor(e,t,r){this.linkAPIUrl=e,this.sessionId=t;const s=`${t}:${r}`;this.auth=`Basic ${btoa(s)}`}async markUnseenEventsAsSeen(e){return Promise.all(e.map(t=>fetch(`${this.linkAPIUrl}/events/${t.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(t=>console.error("Unabled to mark event as failed:",t))}async fetchUnseenEvents(){var e;const t=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(t.ok){const{events:r,error:s}=await t.json();if(s)throw new Error(`Check unseen events failed: ${s}`);const i=(e=r==null?void 0:r.filter(a=>a.event==="Web3Response").map(a=>({type:"Event",sessionId:this.sessionId,eventId:a.id,event:a.event,data:a.data})))!==null&&e!==void 0?e:[];return this.markUnseenEventsAsSeen(i),i}throw new Error(`Check unseen events failed: ${t.status}`)}}Ae.WalletLinkHTTP=hr;var Y={};Object.defineProperty(Y,"__esModule",{value:!0});Y.WalletLinkWebSocket=Y.ConnectionState=void 0;var Z;(function(n){n[n.DISCONNECTED=0]="DISCONNECTED",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED"})(Z||(Y.ConnectionState=Z={}));class gr{setConnectionStateListener(e){this.connectionStateListener=e}setIncomingDataListener(e){this.incomingDataListener=e}constructor(e,t=WebSocket){this.WebSocketClass=t,this.webSocket=null,this.pendingData=[],this.url=e.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");return new Promise((e,t)=>{var r;let s;try{this.webSocket=s=new this.WebSocketClass(this.url)}catch(i){t(i);return}(r=this.connectionStateListener)===null||r===void 0||r.call(this,Z.CONNECTING),s.onclose=i=>{var a;this.clearWebSocket(),t(new Error(`websocket error ${i.code}: ${i.reason}`)),(a=this.connectionStateListener)===null||a===void 0||a.call(this,Z.DISCONNECTED)},s.onopen=i=>{var a;e(),(a=this.connectionStateListener)===null||a===void 0||a.call(this,Z.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(c=>this.sendData(c)),this.pendingData=[])},s.onmessage=i=>{var a,o;if(i.data==="h")(a=this.incomingDataListener)===null||a===void 0||a.call(this,{type:"Heartbeat"});else try{const c=JSON.parse(i.data);(o=this.incomingDataListener)===null||o===void 0||o.call(this,c)}catch{}}})}disconnect(){var e;const{webSocket:t}=this;if(t){this.clearWebSocket(),(e=this.connectionStateListener)===null||e===void 0||e.call(this,Z.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{t.close()}catch{}}}sendData(e){const{webSocket:t}=this;if(!t){this.pendingData.push(e),this.connect();return}t.send(e)}clearWebSocket(){const{webSocket:e}=this;e&&(this.webSocket=null,e.onclose=null,e.onerror=null,e.onmessage=null,e.onopen=null)}}Y.WalletLinkWebSocket=gr;Object.defineProperty(Me,"__esModule",{value:!0});Me.WalletLinkConnection=void 0;const st=N,pr=Le,fr=Ae,ue=Y,F=_,it=1e4,mr=6e4;class br{constructor({session:e,linkAPIUrl:t,listener:r,WebSocketClass:s=WebSocket}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=(0,F.IntNumber)(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=a=>{if(!a)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",c=>a.JsonRpcUrl&&this.handleChainUpdated(c,a.JsonRpcUrl)]]).forEach((c,l)=>{const h=a[l];h!==void 0&&c(h)})},this.handleDestroyed=a=>{var o;a==="1"&&((o=this.listener)===null||o===void 0||o.resetAndReload())},this.handleAccountUpdated=async a=>{var o;{const c=await this.cipher.decrypt(a);(o=this.listener)===null||o===void 0||o.accountUpdated(c)}},this.handleMetadataUpdated=async(a,o)=>{var c;{const l=await this.cipher.decrypt(o);(c=this.listener)===null||c===void 0||c.metadataUpdated(a,l)}},this.handleWalletUsernameUpdated=async a=>{this.handleMetadataUpdated(st.WALLET_USER_NAME_KEY,a)},this.handleAppVersionUpdated=async a=>{this.handleMetadataUpdated(st.APP_VERSION_KEY,a)},this.handleChainUpdated=async(a,o)=>{var c;{const l=await this.cipher.decrypt(a),h=await this.cipher.decrypt(o);(c=this.listener)===null||c===void 0||c.chainUpdated(l,h)}},this.session=e,this.cipher=new pr.WalletLinkCipher(e.secret),this.listener=r;const i=new ue.WalletLinkWebSocket(`${t}/rpc`,s);i.setConnectionStateListener(async a=>{let o=!1;switch(a){case ue.ConnectionState.DISCONNECTED:if(!this.destroyed){const c=async()=>{await new Promise(l=>setTimeout(l,5e3)),this.destroyed||i.connect().catch(()=>{c()})};c()}break;case ue.ConnectionState.CONNECTED:try{await this.authenticate(),this.sendIsLinked(),this.sendGetSessionConfig(),o=!0}catch{}this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},it),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();break;case ue.ConnectionState.CONNECTING:break}this.connected!==o&&(this.connected=o)}),i.setIncomingDataListener(a=>{var o;switch(a.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const c=a.type==="IsLinkedOK"?a.linked:void 0;this.linked=c||a.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{this.handleSessionMetadataUpdated(a.metadata);break}case"Event":{this.handleIncomingEvent(a);break}}a.id!==void 0&&((o=this.requestResolutions.get(a.id))===null||o===void 0||o(a))}),this.ws=i,this.http=new fr.WalletLinkHTTP(t,e.id,e.key)}connect(){if(this.destroyed)throw new Error("instance is destroyed");this.ws.connect()}destroy(){this.destroyed=!0,this.ws.disconnect(),this.listener=void 0}get isDestroyed(){return this.destroyed}get connected(){return this._connected}set connected(e){var t;this._connected=e,e&&((t=this.onceConnected)===null||t===void 0||t.call(this))}setOnceConnected(e){return new Promise(t=>{this.connected?e().then(t):this.onceConnected=()=>{e().then(t),this.onceConnected=void 0}})}get linked(){return this._linked}set linked(e){var t,r;this._linked=e,e&&((t=this.onceLinked)===null||t===void 0||t.call(this)),(r=this.listener)===null||r===void 0||r.linkedUpdated(e)}setOnceLinked(e){return new Promise(t=>{this.linked?e().then(t):this.onceLinked=()=>{e().then(t),this.onceLinked=void 0}})}async handleIncomingEvent(e){var t;if(!(e.type!=="Event"||e.event!=="Web3Response")){const r=await this.cipher.decrypt(e.data),s=JSON.parse(r);if(s.type!=="WEB3_RESPONSE")return;(t=this.listener)===null||t===void 0||t.handleWeb3ResponseMessage(s)}}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(e=>setTimeout(e,250));try{await this.fetchUnseenEventsAPI()}catch(e){console.error("Unable to check for unseen events",e)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(t=>this.handleIncomingEvent(t))}async setSessionMetadata(e,t){const r={type:"SetSessionConfig",id:(0,F.IntNumber)(this.nextReqId++),sessionId:this.session.id,metadata:{[e]:t}};return this.setOnceConnected(async()=>{const s=await this.makeRequest(r);if(s.type==="Fail")throw new Error(s.error||"failed to set session metadata")})}async publishEvent(e,t,r=!1){const s=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},t),{origin:location.origin,relaySource:"coinbaseWalletExtension"in window&&window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),i={type:"PublishEvent",id:(0,F.IntNumber)(this.nextReqId++),sessionId:this.session.id,event:e,data:s,callWebhook:r};return this.setOnceLinked(async()=>{const a=await this.makeRequest(i);if(a.type==="Fail")throw new Error(a.error||"failed to publish event");return a.eventId})}sendData(e){this.ws.sendData(JSON.stringify(e))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>it*2){this.ws.disconnect();return}try{this.ws.sendData("h")}catch{}}async makeRequest(e,t=mr){const r=e.id;this.sendData(e);let s;return Promise.race([new Promise((i,a)=>{s=window.setTimeout(()=>{a(new Error(`request ${r} timed out`))},t)}),new Promise(i=>{this.requestResolutions.set(r,a=>{clearTimeout(s),i(a),this.requestResolutions.delete(r)})})])}async authenticate(){const e={type:"HostSession",id:(0,F.IntNumber)(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key},t=await this.makeRequest(e);if(t.type==="Fail")throw new Error(t.error||"failed to authenticate")}sendIsLinked(){const e={type:"IsLinked",id:(0,F.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(e)}sendGetSessionConfig(){const e={type:"GetSessionConfig",id:(0,F.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(e)}}Me.WalletLinkConnection=br;var Re={};Object.defineProperty(Re,"__esModule",{value:!0});Re.WalletLinkSession=void 0;const yr=cn,at=u,ot="session:id",ct="session:secret",dt="session:linked";class ze{constructor(e,t,r,s){this._storage=e,this._id=t||(0,at.randomBytesHex)(16),this._secret=r||(0,at.randomBytesHex)(32),this._key=new yr.sha256().update(`${this._id}, ${this._secret} WalletLink`).digest("hex"),this._linked=!!s}static load(e){const t=e.getItem(ot),r=e.getItem(dt),s=e.getItem(ct);return t&&s?new ze(e,t,s,r==="1"):null}get id(){return this._id}get secret(){return this._secret}get key(){return this._key}get linked(){return this._linked}set linked(e){this._linked=e,this.persistLinked()}save(){return this._storage.setItem(ot,this._id),this._storage.setItem(ct,this._secret),this.persistLinked(),this}persistLinked(){this._storage.setItem(dt,this._linked?"1":"0")}}Re.WalletLinkSession=ze;var S={};Object.defineProperty(S,"__esModule",{value:!0});S.isDarkMode=S.isMobileWeb=S.getLocation=S.createQrUrl=void 0;function wr(n,e,t,r,s,i){const a=r?"parent-id":"id",o=new URLSearchParams({[a]:n,secret:e,server:t,v:s,chainId:i.toString()}).toString();return`${t}/#/link?${o}`}S.createQrUrl=wr;function vr(){try{return window.frameElement!==null}catch{return!1}}function _r(){try{return vr()&&window.top?window.top.location:window.location}catch{return window.location}}S.getLocation=_r;function Er(){var n;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((n=window==null?void 0:window.navigator)===null||n===void 0?void 0:n.userAgent)}S.isMobileWeb=Er;function Sr(){var n,e;return(e=(n=window==null?void 0:window.matchMedia)===null||n===void 0?void 0:n.call(window,"(prefers-color-scheme: dark)").matches)!==null&&e!==void 0?e:!1}S.isDarkMode=Sr;var xe={},ae={},Ve={};Object.defineProperty(Ve,"__esModule",{value:!0});Ve.default='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';var Cr=M&&M.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(ae,"__esModule",{value:!0});ae.injectCssReset=void 0;const kr=Cr(Ve);function Ir(){const n=document.createElement("style");n.type="text/css",n.appendChild(document.createTextNode(kr.default)),document.documentElement.appendChild(n)}ae.injectCssReset=Ir;var Ze={};function Zt(n){var e,t,r="";if(typeof n=="string"||typeof n=="number")r+=n;else if(typeof n=="object")if(Array.isArray(n))for(e=0;e{this.items.delete(m),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&(0,r.render)((0,r.h)("div",null,(0,r.h)(n.SnackbarContainer,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([p,m])=>(0,r.h)(n.SnackbarInstance,Object.assign({},m,{key:p}))))),this.root)}}n.Snackbar=l;const h=d=>(0,r.h)("div",{class:(0,t.default)("-cbwsdk-snackbar-container")},(0,r.h)("style",null,a.default),(0,r.h)("div",{class:"-cbwsdk-snackbar"},d.children));n.SnackbarContainer=h;const f=({autoExpand:d,message:p,menuItems:m})=>{const[B,tn]=(0,s.useState)(!0),[Oe,Je]=(0,s.useState)(d??!1);(0,s.useEffect)(()=>{const L=[window.setTimeout(()=>{tn(!1)},1),window.setTimeout(()=>{Je(!0)},1e4)];return()=>{L.forEach(window.clearTimeout)}});const nn=()=>{Je(!Oe)};return(0,r.h)("div",{class:(0,t.default)("-cbwsdk-snackbar-instance",B&&"-cbwsdk-snackbar-instance-hidden",Oe&&"-cbwsdk-snackbar-instance-expanded")},(0,r.h)("div",{class:"-cbwsdk-snackbar-instance-header",onClick:nn},(0,r.h)("img",{src:o,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",(0,r.h)("div",{class:"-cbwsdk-snackbar-instance-header-message"},p),(0,r.h)("div",{class:"-gear-container"},!Oe&&(0,r.h)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,r.h)("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),(0,r.h)("img",{src:c,class:"-gear-icon",title:"Expand"}))),m&&m.length>0&&(0,r.h)("div",{class:"-cbwsdk-snackbar-instance-menu"},m.map((L,rn)=>(0,r.h)("div",{class:(0,t.default)("-cbwsdk-snackbar-instance-menu-item",L.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:L.onClick,key:rn},(0,r.h)("svg",{width:L.svgWidth,height:L.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,r.h)("path",{"fill-rule":L.defaultFillRule,"clip-rule":L.defaultClipRule,d:L.path,fill:"#AAAAAA"})),(0,r.h)("span",{class:(0,t.default)("-cbwsdk-snackbar-instance-menu-item-info",L.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},L.info)))))};n.SnackbarInstance=f})(Ze);Object.defineProperty(xe,"__esModule",{value:!0});xe.WalletLinkRelayUI=void 0;const Lr=ae,Ar=Ze;class Rr{constructor(){this.attached=!1,this.snackbar=new Ar.Snackbar}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const e=document.documentElement,t=document.createElement("div");t.className="-cbwsdk-css-reset",e.appendChild(t),this.snackbar.attach(t),this.attached=!0,(0,Lr.injectCssReset)()}showConnecting(e){let t;return e.isUnlinkedErrorState?t={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]}:t={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:e.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]},this.snackbar.presentItem(t)}}xe.WalletLinkRelayUI=Rr;var Pe={},Ne={},Ye={};Object.defineProperty(Ye,"__esModule",{value:!0});Ye.default=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";var Yt=M&&M.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Ne,"__esModule",{value:!0});Ne.RedirectDialog=void 0;const xr=Yt(Gt),x=_t,Pr=ae,Nr=Ze,Tr=S,jr=Yt(Ye);class Or{constructor(){this.root=null,this.darkMode=(0,Tr.isDarkMode)()}attach(){const e=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",e.appendChild(this.root),(0,Pr.injectCssReset)()}present(e){this.render(e)}clear(){this.render(null)}render(e){this.root&&((0,x.render)(null,this.root),e&&(0,x.render)((0,x.h)(Dr,Object.assign({},e,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}Ne.RedirectDialog=Or;const Dr=({title:n,buttonText:e,darkMode:t,onButtonClick:r,onDismiss:s})=>{const i=t?"dark":"light";return(0,x.h)(Nr.SnackbarContainer,{darkMode:t},(0,x.h)("div",{class:"-cbwsdk-redirect-dialog"},(0,x.h)("style",null,jr.default),(0,x.h)("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:s}),(0,x.h)("div",{class:(0,xr.default)("-cbwsdk-redirect-dialog-box",i)},(0,x.h)("p",null,n),(0,x.h)("button",{onClick:r},e))))};var T={};Object.defineProperty(T,"__esModule",{value:!0});T.CBW_MOBILE_DEEPLINK_URL=T.WALLETLINK_URL=T.CB_KEYS_URL=void 0;T.CB_KEYS_URL="https://keys.coinbase.com/connect";T.WALLETLINK_URL="https://www.walletlink.org";T.CBW_MOBILE_DEEPLINK_URL="https://go.cb-w.com/walletlink";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.WLMobileRelayUI=void 0;const Wr=Ne,Ur=S,Br=T;class Hr{constructor(){this.attached=!1,this.redirectDialog=new Wr.RedirectDialog}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}redirectToCoinbaseWallet(e){const t=new URL(Br.CBW_MOBILE_DEEPLINK_URL);t.searchParams.append("redirect_url",(0,Ur.getLocation)().href),e&&t.searchParams.append("wl_url",e);const r=document.createElement("a");r.target="cbw-opener",r.href=t.href,r.rel="noreferrer noopener",r.click()}openCoinbaseWalletDeeplink(e){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",onButtonClick:()=>{this.redirectToCoinbaseWallet(e)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(e)},99)}showConnecting(e){return()=>{this.redirectDialog.clear()}}}Pe.WLMobileRelayUI=Hr;Object.defineProperty(Ie,"__esModule",{value:!0});Ie.WalletLinkRelay=void 0;const Kr=Me,qr=N,$r=ie,He=Re,z=Q,Fr=S,zr=xe,ut=Pe,Vr=j,b=u,Zr=O;class W{constructor(e){this.accountsCallback=null,this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.chainCallback=null,this.dappDefaultChain=1,this.isMobileWeb=(0,Fr.isMobileWeb)(),this.appName="",this.appLogoUrl=null,this.linkedUpdated=i=>{this.isLinked=i;const a=this.storage.getItem(qr.LOCAL_STORAGE_ADDRESSES_KEY);if(i&&(this._session.linked=i),this.isUnlinkedErrorState=!1,a){const o=a.split(" "),c=this.storage.getItem("IsStandaloneSigning")==="true";o[0]!==""&&!i&&this._session.linked&&!c&&(this.isUnlinkedErrorState=!0)}},this.metadataUpdated=(i,a)=>{this.storage.setItem(i,a)},this.chainUpdated=(i,a)=>{this.chainCallbackParams.chainId===i&&this.chainCallbackParams.jsonRpcUrl===a||(this.chainCallbackParams={chainId:i,jsonRpcUrl:a},this.chainCallback&&this.chainCallback(i,a))},this.accountUpdated=i=>{this.accountsCallback&&this.accountsCallback([i]),W.accountRequestCallbackIds.size>0&&(Array.from(W.accountRequestCallbackIds.values()).forEach(a=>{const o={type:"WEB3_RESPONSE",id:a,response:{method:"requestEthereumAccounts",result:[i]}};this.invokeCallback(Object.assign(Object.assign({},o),{id:a}))}),W.accountRequestCallbackIds.clear())},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=e.linkAPIUrl,this.storage=e.storage;const{session:t,ui:r,connection:s}=this.subscribe();this._session=t,this.connection=s,this.relayEventManager=new $r.RelayEventManager,this.ui=r}subscribe(){const e=He.WalletLinkSession.load(this.storage)||new He.WalletLinkSession(this.storage).save(),{linkAPIUrl:t}=this,r=new Kr.WalletLinkConnection({session:e,linkAPIUrl:t,listener:this}),s=this.isMobileWeb?new ut.WLMobileRelayUI:new zr.WalletLinkRelayUI;return r.connect(),{session:e,ui:s,connection:r}}attachUI(){this.ui.attach()}resetAndReload(){Promise.race([this.connection.setSessionMetadata("__destroyed","1"),new Promise(e=>setTimeout(()=>e(null),1e3))]).then(()=>{this.connection.destroy();const e=He.WalletLinkSession.load(this.storage);(e==null?void 0:e.id)===this._session.id&&Zr.ScopedLocalStorage.clearAll(),document.location.reload()}).catch(e=>{})}setAppInfo(e,t){this.appName=e,this.appLogoUrl=t}getStorageItem(e){return this.storage.getItem(e)}setStorageItem(e,t){this.storage.setItem(e,t)}signEthereumMessage(e,t,r,s){return this.sendRequest({method:"signEthereumMessage",params:{message:(0,b.hexStringFromBuffer)(e,!0),address:t,addPrefix:r,typedDataJson:s||null}})}ethereumAddressFromSignedMessage(e,t,r){return this.sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:(0,b.hexStringFromBuffer)(e,!0),signature:(0,b.hexStringFromBuffer)(t,!0),addPrefix:r}})}signEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:(0,b.bigIntStringFromBigInt)(e.weiValue),data:(0,b.hexStringFromBuffer)(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?(0,b.bigIntStringFromBigInt)(e.gasPriceInWei):null,maxFeePerGas:e.gasPriceInWei?(0,b.bigIntStringFromBigInt)(e.gasPriceInWei):null,maxPriorityFeePerGas:e.gasPriceInWei?(0,b.bigIntStringFromBigInt)(e.gasPriceInWei):null,gasLimit:e.gasLimit?(0,b.bigIntStringFromBigInt)(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:(0,b.bigIntStringFromBigInt)(e.weiValue),data:(0,b.hexStringFromBuffer)(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?(0,b.bigIntStringFromBigInt)(e.gasPriceInWei):null,maxFeePerGas:e.maxFeePerGas?(0,b.bigIntStringFromBigInt)(e.maxFeePerGas):null,maxPriorityFeePerGas:e.maxPriorityFeePerGas?(0,b.bigIntStringFromBigInt)(e.maxPriorityFeePerGas):null,gasLimit:e.gasLimit?(0,b.bigIntStringFromBigInt)(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!0}})}submitEthereumTransaction(e,t){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:(0,b.hexStringFromBuffer)(e,!0),chainId:t}})}scanQRCode(e){return this.sendRequest({method:"scanQRCode",params:{regExp:e}})}getWalletLinkSession(){return this._session}genericRequest(e,t){return this.sendRequest({method:"generic",params:{action:t,data:e}})}sendGenericMessage(e){return this.sendRequest(e)}sendRequest(e){let t=null;const r=(0,b.randomBytesHex)(8),s=i=>{this.publishWeb3RequestCanceledEvent(r),this.handleErrorResponse(r,e.method,i),t==null||t()};return new Promise((i,a)=>{t=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:s,onResetConnection:this.resetAndReload}),this.relayEventManager.callbacks.set(r,o=>{if(t==null||t(),(0,z.isErrorResponse)(o))return a(new Error(o.errorMessage));i(o)}),this.publishWeb3RequestEvent(r,e)})}setAccountsCallback(e){this.accountsCallback=e}setChainCallback(e){this.chainCallback=e}setDappDefaultChainCallback(e){this.dappDefaultChain=e}publishWeb3RequestEvent(e,t){const r={type:"WEB3_REQUEST",id:e,request:t};this.publishEvent("Web3Request",r,!0).then(s=>{}).catch(s=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:r.id,response:{method:t.method,errorMessage:s.message}})}),this.isMobileWeb&&this.openCoinbaseWalletDeeplink(t.method)}openCoinbaseWalletDeeplink(e){if(this.ui instanceof ut.WLMobileRelayUI)switch(e){case"requestEthereumAccounts":case"switchEthereumChain":return;default:window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0}),this.ui.openCoinbaseWalletDeeplink();break}}publishWeb3RequestCanceledEvent(e){const t={type:"WEB3_REQUEST_CANCELED",id:e};this.publishEvent("Web3RequestCanceled",t,!1).then()}publishEvent(e,t,r){return this.connection.publishEvent(e,t,r)}handleWeb3ResponseMessage(e){const{response:t}=e;if(t.method==="requestEthereumAccounts"){W.accountRequestCallbackIds.forEach(r=>this.invokeCallback(Object.assign(Object.assign({},e),{id:r}))),W.accountRequestCallbackIds.clear();return}this.invokeCallback(e)}handleErrorResponse(e,t,r){var s;const i=(s=r==null?void 0:r.message)!==null&&s!==void 0?s:"Unspecified error message.";this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:e,response:{method:t,errorMessage:i}})}invokeCallback(e){const t=this.relayEventManager.callbacks.get(e.id);t&&(t(e.response),this.relayEventManager.callbacks.delete(e.id))}requestEthereumAccounts(){const e={method:"requestEthereumAccounts",params:{appName:this.appName,appLogoUrl:this.appLogoUrl||null}},t=(0,b.randomBytesHex)(8);return new Promise((r,s)=>{this.relayEventManager.callbacks.set(t,i=>{if((0,z.isErrorResponse)(i))return s(new Error(i.errorMessage));r(i)}),W.accountRequestCallbackIds.add(t),this.publishWeb3RequestEvent(t,e)})}watchAsset(e,t,r,s,i,a){const o={method:"watchAsset",params:{type:e,options:{address:t,symbol:r,decimals:s,image:i},chainId:a}};let c=null;const l=(0,b.randomBytesHex)(8),h=f=>{this.publishWeb3RequestCanceledEvent(l),this.handleErrorResponse(l,o.method,f),c==null||c()};return c=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:h,onResetConnection:this.resetAndReload}),new Promise((f,d)=>{this.relayEventManager.callbacks.set(l,p=>{if(c==null||c(),(0,z.isErrorResponse)(p))return d(new Error(p.errorMessage));f(p)}),this.publishWeb3RequestEvent(l,o)})}addEthereumChain(e,t,r,s,i,a){const o={method:"addEthereumChain",params:{chainId:e,rpcUrls:t,blockExplorerUrls:s,chainName:i,iconUrls:r,nativeCurrency:a}};let c=null;const l=(0,b.randomBytesHex)(8),h=f=>{this.publishWeb3RequestCanceledEvent(l),this.handleErrorResponse(l,o.method,f),c==null||c()};return c=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:h,onResetConnection:this.resetAndReload}),new Promise((f,d)=>{this.relayEventManager.callbacks.set(l,p=>{if(c==null||c(),(0,z.isErrorResponse)(p))return d(new Error(p.errorMessage));f(p)}),this.publishWeb3RequestEvent(l,o)})}switchEthereumChain(e,t){const r={method:"switchEthereumChain",params:Object.assign({chainId:e},{address:t})},s=(0,b.randomBytesHex)(8);return new Promise((i,a)=>{this.relayEventManager.callbacks.set(s,o=>{if((0,z.isErrorResponse)(o)&&o.errorCode)return a(Vr.standardErrors.provider.custom({code:o.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if((0,z.isErrorResponse)(o))return a(new Error(o.errorMessage));i(o)}),this.publishWeb3RequestEvent(s,r)})}}Ie.WalletLinkRelay=W;W.accountRequestCallbackIds=new Set;var Gr=M&&M.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Ce,"__esModule",{value:!0});Ce.WalletLinkSigner=void 0;const Ke=Gr(or),ht=N,Yr=ie,D=Q,Jr=Ie,gt=T,w=j,g=u,Qr=O,qe="DefaultChainId",pt="DefaultJsonRpcUrl";class Xr{constructor(e){var t,r;this._relay=null,this._addresses=[],this.hasMadeFirstChainChangedEmission=!1;const{appName:s,appLogoUrl:i}=e.metadata;this._appName=s,this._appLogoUrl=i,this._storage=new Qr.ScopedLocalStorage("walletlink",gt.WALLETLINK_URL),this.updateListener=e.updateListener,this._relayEventManager=new Yr.RelayEventManager,this._jsonRpcUrlFromOpts="";const a=this._storage.getItem(ht.LOCAL_STORAGE_ADDRESSES_KEY);if(a){const c=a.split(" ");c[0]!==""&&(this._addresses=c.map(l=>(0,g.ensureAddressString)(l)),(t=this.updateListener)===null||t===void 0||t.onAccountsUpdate({accounts:this._addresses,source:"storage"}))}this._storage.getItem(qe)&&((r=this.updateListener)===null||r===void 0||r.onChainUpdate({chain:{id:this.getChainId(),rpcUrl:this.jsonRpcUrl},source:"storage"}),this.hasMadeFirstChainChangedEmission=!0),this.initializeRelay()}getSession(){const e=this.initializeRelay(),{id:t,secret:r}=e.getWalletLinkSession();return{id:t,secret:r}}async handshake(){return await this.request({method:"eth_requestAccounts"})}get selectedAddress(){return this._addresses[0]||void 0}get jsonRpcUrl(){var e;return(e=this._storage.getItem(pt))!==null&&e!==void 0?e:this._jsonRpcUrlFromOpts}set jsonRpcUrl(e){this._storage.setItem(pt,e)}updateProviderInfo(e,t){var r;this.jsonRpcUrl=e;const s=this.getChainId();this._storage.setItem(qe,t.toString(10)),((0,g.ensureIntNumber)(t)!==s||!this.hasMadeFirstChainChangedEmission)&&((r=this.updateListener)===null||r===void 0||r.onChainUpdate({chain:{id:t,rpcUrl:e},source:"wallet"}),this.hasMadeFirstChainChangedEmission=!0)}async watchAsset(e,t,r,s,i,a){const c=await this.initializeRelay().watchAsset(e,t,r,s,i,a==null?void 0:a.toString());return(0,D.isErrorResponse)(c)?!1:!!c.result}async addEthereumChain(e,t,r,s,i,a){var o,c;if((0,g.ensureIntNumber)(e)===this.getChainId())return!1;const l=this.initializeRelay();this._isAuthorized()||await l.requestEthereumAccounts();const h=await l.addEthereumChain(e.toString(),t,i,r,s,a);return(0,D.isErrorResponse)(h)?!1:(((o=h.result)===null||o===void 0?void 0:o.isApproved)===!0&&this.updateProviderInfo(t[0],e),((c=h.result)===null||c===void 0?void 0:c.isApproved)===!0)}async switchEthereumChain(e){const r=await this.initializeRelay().switchEthereumChain(e.toString(10),this.selectedAddress||void 0);if((0,D.isErrorResponse)(r)){if(!r.errorCode)return;throw r.errorCode===w.standardErrorCodes.provider.unsupportedChain?w.standardErrors.provider.unsupportedChain():w.standardErrors.provider.custom({message:r.errorMessage,code:r.errorCode})}const s=r.result;s.isApproved&&s.rpcUrl.length>0&&this.updateProviderInfo(s.rpcUrl,e)}async disconnect(){this._relay&&this._relay.resetAndReload(),this._storage.clear()}async request(e){try{return this._request(e).catch(t=>{throw t})}catch(t){return Promise.reject(t)}}async _request(e){if(!e||typeof e!="object"||Array.isArray(e))throw w.standardErrors.rpc.invalidRequest({message:"Expected a single, non-array, object argument.",data:e});const{method:t,params:r}=e;if(typeof t!="string"||t.length===0)throw w.standardErrors.rpc.invalidRequest({message:"'args.method' must be a non-empty string.",data:e});if(r!==void 0&&!Array.isArray(r)&&(typeof r!="object"||r===null))throw w.standardErrors.rpc.invalidRequest({message:"'args.params' must be an object or array if provided.",data:e});const s=r===void 0?[]:r,i=this._relayEventManager.makeRequestId();return(await this._sendRequestAsync({method:t,params:s,jsonrpc:"2.0",id:i})).result}_setAddresses(e,t){var r;if(!Array.isArray(e))throw new Error("addresses is not an array");const s=e.map(i=>(0,g.ensureAddressString)(i));JSON.stringify(s)!==JSON.stringify(this._addresses)&&(this._addresses=s,(r=this.updateListener)===null||r===void 0||r.onAccountsUpdate({accounts:s,source:"wallet"}),this._storage.setItem(ht.LOCAL_STORAGE_ADDRESSES_KEY,s.join(" ")))}_sendRequestAsync(e){return new Promise((t,r)=>{try{const s=this._handleSynchronousMethods(e);if(s!==void 0)return t({jsonrpc:"2.0",id:e.id,result:s})}catch(s){return r(s)}this._handleAsynchronousMethods(e).then(s=>s&&t(Object.assign(Object.assign({},s),{id:e.id}))).catch(s=>r(s))})}_handleSynchronousMethods(e){const{method:t}=e;switch(t){case"eth_accounts":return this._eth_accounts();case"eth_coinbase":return this._eth_coinbase();case"net_version":return this._net_version();case"eth_chainId":return this._eth_chainId();default:return}}async _handleAsynchronousMethods(e){const{method:t}=e,r=e.params||[];switch(t){case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_sign":return this._eth_sign(r);case"eth_ecRecover":return this._eth_ecRecover(r);case"personal_sign":return this._personal_sign(r);case"personal_ecRecover":return this._personal_ecRecover(r);case"eth_signTransaction":return this._eth_signTransaction(r);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(r);case"eth_sendTransaction":return this._eth_sendTransaction(r);case"eth_signTypedData_v1":return this._eth_signTypedData_v1(r);case"eth_signTypedData_v2":return this._throwUnsupportedMethodError();case"eth_signTypedData_v3":return this._eth_signTypedData_v3(r);case"eth_signTypedData_v4":case"eth_signTypedData":return this._eth_signTypedData_v4(r);case"wallet_addEthereumChain":return this._wallet_addEthereumChain(r);case"wallet_switchEthereumChain":return this._wallet_switchEthereumChain(r);case"wallet_watchAsset":return this._wallet_watchAsset(r);default:return this._throwUnsupportedMethodError()}}_isKnownAddress(e){try{const t=(0,g.ensureAddressString)(e);return this._addresses.map(s=>(0,g.ensureAddressString)(s)).includes(t)}catch{}return!1}_ensureKnownAddress(e){if(!this._isKnownAddress(e))throw new Error("Unknown Ethereum address")}_prepareTransactionParams(e){const t=e.from?(0,g.ensureAddressString)(e.from):this.selectedAddress;if(!t)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(t);const r=e.to?(0,g.ensureAddressString)(e.to):null,s=e.value!=null?(0,g.ensureBigInt)(e.value):BigInt(0),i=e.data?(0,g.ensureBuffer)(e.data):Buffer.alloc(0),a=e.nonce!=null?(0,g.ensureIntNumber)(e.nonce):null,o=e.gasPrice!=null?(0,g.ensureBigInt)(e.gasPrice):null,c=e.maxFeePerGas!=null?(0,g.ensureBigInt)(e.maxFeePerGas):null,l=e.maxPriorityFeePerGas!=null?(0,g.ensureBigInt)(e.maxPriorityFeePerGas):null,h=e.gas!=null?(0,g.ensureBigInt)(e.gas):null,f=e.chainId?(0,g.ensureIntNumber)(e.chainId):this.getChainId();return{fromAddress:t,toAddress:r,weiValue:s,data:i,nonce:a,gasPriceInWei:o,maxFeePerGas:c,maxPriorityFeePerGas:l,gasLimit:h,chainId:f}}_isAuthorized(){return this._addresses.length>0}_requireAuthorization(){if(!this._isAuthorized())throw w.standardErrors.provider.unauthorized({})}_throwUnsupportedMethodError(){throw w.standardErrors.provider.unsupportedMethod({})}async _signEthereumMessage(e,t,r,s){this._ensureKnownAddress(t);try{const a=await this.initializeRelay().signEthereumMessage(e,t,r,s);if((0,D.isErrorResponse)(a))throw new Error(a.errorMessage);return{jsonrpc:"2.0",id:0,result:a.result}}catch(i){throw typeof i.message=="string"&&i.message.match(/(denied|rejected)/i)?w.standardErrors.provider.userRejectedRequest("User denied message signature"):i}}async _ethereumAddressFromSignedMessage(e,t,r){const i=await this.initializeRelay().ethereumAddressFromSignedMessage(e,t,r);if((0,D.isErrorResponse)(i))throw new Error(i.errorMessage);return{jsonrpc:"2.0",id:0,result:i.result}}_eth_accounts(){return[...this._addresses]}_eth_coinbase(){return this.selectedAddress||null}_net_version(){return this.getChainId().toString(10)}_eth_chainId(){return(0,g.hexStringFromIntNumber)(this.getChainId())}getChainId(){const e=this._storage.getItem(qe);if(!e)return(0,g.ensureIntNumber)(1);const t=parseInt(e,10);return(0,g.ensureIntNumber)(t)}async _eth_requestAccounts(){if(this._isAuthorized())return Promise.resolve({jsonrpc:"2.0",id:0,result:this._addresses});let e;try{if(e=await this.initializeRelay().requestEthereumAccounts(),(0,D.isErrorResponse)(e))throw new Error(e.errorMessage)}catch(t){throw typeof t.message=="string"&&t.message.match(/(denied|rejected)/i)?w.standardErrors.provider.userRejectedRequest("User denied account authorization"):t}if(!e.result)throw new Error("accounts received is empty");return this._setAddresses(e.result),{jsonrpc:"2.0",id:0,result:this._addresses}}_eth_sign(e){this._requireAuthorization();const t=(0,g.ensureAddressString)(e[0]),r=(0,g.ensureBuffer)(e[1]);return this._signEthereumMessage(r,t,!1)}_eth_ecRecover(e){const t=(0,g.ensureBuffer)(e[0]),r=(0,g.ensureBuffer)(e[1]);return this._ethereumAddressFromSignedMessage(t,r,!1)}_personal_sign(e){this._requireAuthorization();const t=(0,g.ensureBuffer)(e[0]),r=(0,g.ensureAddressString)(e[1]);return this._signEthereumMessage(t,r,!0)}_personal_ecRecover(e){const t=(0,g.ensureBuffer)(e[0]),r=(0,g.ensureBuffer)(e[1]);return this._ethereumAddressFromSignedMessage(t,r,!0)}async _eth_signTransaction(e){this._requireAuthorization();const t=this._prepareTransactionParams(e[0]||{});try{const s=await this.initializeRelay().signEthereumTransaction(t);if((0,D.isErrorResponse)(s))throw new Error(s.errorMessage);return{jsonrpc:"2.0",id:0,result:s.result}}catch(r){throw typeof r.message=="string"&&r.message.match(/(denied|rejected)/i)?w.standardErrors.provider.userRejectedRequest("User denied transaction signature"):r}}async _eth_sendRawTransaction(e){const t=(0,g.ensureBuffer)(e[0]),s=await this.initializeRelay().submitEthereumTransaction(t,this.getChainId());if((0,D.isErrorResponse)(s))throw new Error(s.errorMessage);return{jsonrpc:"2.0",id:0,result:s.result}}async _eth_sendTransaction(e){this._requireAuthorization();const t=this._prepareTransactionParams(e[0]||{});try{const s=await this.initializeRelay().signAndSubmitEthereumTransaction(t);if((0,D.isErrorResponse)(s))throw new Error(s.errorMessage);return{jsonrpc:"2.0",id:0,result:s.result}}catch(r){throw typeof r.message=="string"&&r.message.match(/(denied|rejected)/i)?w.standardErrors.provider.userRejectedRequest("User denied transaction signature"):r}}async _eth_signTypedData_v1(e){this._requireAuthorization();const t=(0,g.ensureParsedJSONObject)(e[0]),r=(0,g.ensureAddressString)(e[1]);this._ensureKnownAddress(r);const s=Ke.default.hashForSignTypedDataLegacy({data:t}),i=JSON.stringify(t,null,2);return this._signEthereumMessage(s,r,!1,i)}async _eth_signTypedData_v3(e){this._requireAuthorization();const t=(0,g.ensureAddressString)(e[0]),r=(0,g.ensureParsedJSONObject)(e[1]);this._ensureKnownAddress(t);const s=Ke.default.hashForSignTypedData_v3({data:r}),i=JSON.stringify(r,null,2);return this._signEthereumMessage(s,t,!1,i)}async _eth_signTypedData_v4(e){this._requireAuthorization();const t=(0,g.ensureAddressString)(e[0]),r=(0,g.ensureParsedJSONObject)(e[1]);this._ensureKnownAddress(t);const s=Ke.default.hashForSignTypedData_v4({data:r}),i=JSON.stringify(r,null,2);return this._signEthereumMessage(s,t,!1,i)}async _wallet_addEthereumChain(e){var t,r,s,i;const a=e[0];if(((t=a.rpcUrls)===null||t===void 0?void 0:t.length)===0)return{jsonrpc:"2.0",id:0,error:{code:2,message:"please pass in at least 1 rpcUrl"}};if(!a.chainName||a.chainName.trim()==="")throw w.standardErrors.rpc.invalidParams("chainName is a required field");if(!a.nativeCurrency)throw w.standardErrors.rpc.invalidParams("nativeCurrency is a required field");const o=parseInt(a.chainId,16);return await this.addEthereumChain(o,(r=a.rpcUrls)!==null&&r!==void 0?r:[],(s=a.blockExplorerUrls)!==null&&s!==void 0?s:[],a.chainName,(i=a.iconUrls)!==null&&i!==void 0?i:[],a.nativeCurrency)?{jsonrpc:"2.0",id:0,result:null}:{jsonrpc:"2.0",id:0,error:{code:2,message:"unable to add ethereum chain"}}}async _wallet_switchEthereumChain(e){const t=e[0];return await this.switchEthereumChain(parseInt(t.chainId,16)),{jsonrpc:"2.0",id:0,result:null}}async _wallet_watchAsset(e){const t=Array.isArray(e)?e[0]:e;if(!t.type)throw w.standardErrors.rpc.invalidParams("Type is required");if((t==null?void 0:t.type)!=="ERC20")throw w.standardErrors.rpc.invalidParams(`Asset of type '${t.type}' is not supported`);if(!(t!=null&&t.options))throw w.standardErrors.rpc.invalidParams("Options are required");if(!(t!=null&&t.options.address))throw w.standardErrors.rpc.invalidParams("Address is required");const r=this.getChainId(),{address:s,symbol:i,image:a,decimals:o}=t.options;return{jsonrpc:"2.0",id:0,result:await this.watchAsset(t.type,s,i,o,a,r)}}initializeRelay(){if(!this._relay){const e=new Jr.WalletLinkRelay({linkAPIUrl:gt.WALLETLINK_URL,storage:this._storage});e.setAppInfo(this._appName,this._appLogoUrl),e.attachUI(),e.setAccountsCallback((t,r)=>this._setAddresses(t,r)),e.setChainCallback((t,r)=>{this.updateProviderInfo(r,parseInt(t,10))}),this._relay=e}return this._relay}}Ce.WalletLinkSigner=Xr;var k={};Object.defineProperty(k,"__esModule",{value:!0});k.checkErrorForInvalidRequestArgs=k.getCoinbaseInjectedProvider=k.getCoinbaseInjectedSigner=k.fetchRPCRequest=void 0;const es=K,pe=j;async function ts(n,e){if(!e.rpcUrl)throw pe.standardErrors.rpc.internal("No RPC URL set for chain");const t=Object.assign(Object.assign({},n),{jsonrpc:"2.0",id:crypto.randomUUID()});return(await(await window.fetch(e.rpcUrl,{method:"POST",body:JSON.stringify(t),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":es.LIB_VERSION}})).json()).result}k.fetchRPCRequest=ts;function Jt(){return globalThis.coinbaseWalletSigner}k.getCoinbaseInjectedSigner=Jt;function ns(){return globalThis.coinbaseWalletExtension}function rs(){var n,e;try{const t=globalThis;return(n=t.ethereum)!==null&&n!==void 0?n:(e=t.top)===null||e===void 0?void 0:e.ethereum}catch{return}}function ss({metadata:n,preference:e}){var t;if(e.options!=="smartWalletOnly"){if(Jt())return;const i=ns();if(i){const{appName:a,appLogoUrl:o,appChainIds:c}=n;return(t=i.setAppInfo)===null||t===void 0||t.call(i,a,o,c),i}}const r=rs();if(r!=null&&r.isCoinbaseBrowser)return r}k.getCoinbaseInjectedProvider=ss;function is(n){if(!n||typeof n!="object"||Array.isArray(n))return pe.standardErrors.rpc.invalidParams({message:"Expected a single, non-array, object argument.",data:n});const{method:e,params:t}=n;if(typeof e!="string"||e.length===0)return pe.standardErrors.rpc.invalidParams({message:"'args.method' must be a non-empty string.",data:n});if(t!==void 0&&!Array.isArray(t)&&(typeof t!="object"||t===null))return pe.standardErrors.rpc.invalidParams({message:"'args.params' must be an object or array if provided.",data:n})}k.checkErrorForInvalidRequestArgs=is;Object.defineProperty(P,"__esModule",{value:!0});P.createSigner=P.fetchSignerType=P.storeSignerType=P.loadSignerType=void 0;const as=_e,Qt=Ce,os=j,cs=k,ds=O,Xt="SignerType",en=new ds.ScopedLocalStorage("CBWSDK","SignerConfigurator");function ls(){return en.getItem(Xt)}P.loadSignerType=ls;function us(n){en.setItem(Xt,n)}P.storeSignerType=us;async function hs(n){const{communicator:e,metadata:t}=n;ps(e,t).catch(()=>{});const r={id:crypto.randomUUID(),event:"selectSignerType",data:n.preference},{data:s}=await e.postRequestAndWaitForResponse(r);return s}P.fetchSignerType=hs;function gs(n){const{signerType:e,metadata:t,communicator:r,updateListener:s}=n;switch(e){case"scw":return new as.SCWSigner({metadata:t,updateListener:s,communicator:r});case"walletlink":return new Qt.WalletLinkSigner({metadata:t,updateListener:s});case"extension":{const i=(0,cs.getCoinbaseInjectedSigner)();if(!i)throw os.standardErrors.rpc.internal("injected signer not found");return i}}}P.createSigner=gs;async function ps(n,e){await n.onMessage(({event:r})=>r==="WalletLinkSessionRequest");const t=new Qt.WalletLinkSigner({metadata:e});n.postMessage({event:"WalletLinkUpdate",data:{session:t.getSession()}}),await t.handshake(),n.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}var Te={},J={};Object.defineProperty(J,"__esModule",{value:!0});J.closePopup=J.openPopup=void 0;const fs=j,ft=420,mt=540;function ms(n){const e=(window.innerWidth-ft)/2+window.screenX,t=(window.innerHeight-mt)/2+window.screenY,r=window.open(n,"Smart Wallet",`width=${ft}, height=${mt}, left=${e}, top=${t}`);if(r==null||r.focus(),!r)throw fs.standardErrors.rpc.internal("Pop up window failed to open");return r}J.openPopup=ms;function bs(n){n&&!n.closed&&n.close()}J.closePopup=bs;Object.defineProperty(Te,"__esModule",{value:!0});Te.Communicator=void 0;const ys=K,bt=J,ws=T,yt=j;class vs{constructor(e=ws.CB_KEYS_URL){this.popup=null,this.listeners=new Map,this.postMessage=async t=>{(await this.waitForPopupLoaded()).postMessage(t,this.url.origin)},this.postRequestAndWaitForResponse=async t=>{const r=this.onMessage(({requestId:s})=>s===t.id);return this.postMessage(t),await r},this.onMessage=async t=>new Promise((r,s)=>{const i=a=>{if(a.origin!==this.url.origin)return;const o=a.data;t(o)&&(r(o),window.removeEventListener("message",i),this.listeners.delete(i))};window.addEventListener("message",i),this.listeners.set(i,{reject:s})}),this.disconnect=()=>{(0,bt.closePopup)(this.popup),this.popup=null,this.listeners.forEach(({reject:t},r)=>{t(yt.standardErrors.provider.userRejectedRequest("Request rejected")),window.removeEventListener("message",r)}),this.listeners.clear()},this.waitForPopupLoaded=async()=>this.popup&&!this.popup.closed?(this.popup.focus(),this.popup):(this.popup=(0,bt.openPopup)(this.url),this.onMessage(({event:t})=>t==="PopupUnload").then(this.disconnect).catch(()=>{}),this.onMessage(({event:t})=>t==="PopupLoaded").then(t=>{this.postMessage({requestId:t.id,data:{version:ys.LIB_VERSION}})}).then(()=>{if(!this.popup)throw yt.standardErrors.rpc.internal();return this.popup})),this.url=new URL(e)}}Te.Communicator=vs;var je={};Object.defineProperty(je,"__esModule",{value:!0});je.determineMethodCategory=void 0;const wt={handshake:["eth_requestAccounts"],sign:["eth_ecRecover","personal_sign","personal_ecRecover","eth_signTransaction","eth_sendTransaction","eth_signTypedData_v1","eth_signTypedData_v3","eth_signTypedData_v4","eth_signTypedData","wallet_addEthereumChain","wallet_switchEthereumChain","wallet_watchAsset","wallet_getCapabilities","wallet_sendCalls","wallet_showCallsStatus"],state:["eth_chainId","eth_accounts","eth_coinbase","net_version"],deprecated:["eth_sign","eth_signTypedData_v2"],unsupported:["eth_subscribe","eth_unsubscribe"],fetch:[]};function _s(n){for(const e in wt){const t=e;if(wt[t].includes(n))return t}}je.determineMethodCategory=_s;var Es=M&&M.__rest||function(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s{try{if(this.connected)return this.emit("connect",{chainId:(0,X.hexStringFromIntNumber)((0,he.IntNumber)(this.chain.id))}),this.accounts;const h=await this.requestSignerSelection(),f=this.initSigner(h),d=await f.handshake();return this.signer=f,(0,ge.storeSignerType)(h),this.emit("connect",{chainId:(0,X.hexStringFromIntNumber)((0,he.IntNumber)(this.chain.id))}),d}catch(h){throw this.handleUnauthorizedError(h),h}},sign:async l=>{if(!this.connected||!this.signer)throw V.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods");try{return await this.signer.request(l)}catch(h){throw this.handleUnauthorizedError(h),h}},fetch:l=>(0,vt.fetchRPCRequest)(l,this.chain),state:l=>{const h=()=>{if(this.connected)return this.accounts;throw V.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods")};switch(l.method){case"eth_chainId":return(0,X.hexStringFromIntNumber)((0,he.IntNumber)(this.chain.id));case"net_version":return this.chain.id;case"eth_accounts":return h();case"eth_coinbase":return h()[0];default:return this.handlers.unsupported(l)}},deprecated:({method:l})=>{throw V.standardErrors.rpc.methodNotSupported(`Method ${l} is deprecated.`)},unsupported:({method:l})=>{throw V.standardErrors.rpc.methodNotSupported(`Method ${l} is not supported.`)}},this.isCoinbaseWallet=!0,this.updateListener={onAccountsUpdate:({accounts:l,source:h})=>{(0,X.areAddressArraysEqual)(this.accounts,l)||(this.accounts=l,h!=="storage"&&this.emit("accountsChanged",this.accounts))},onChainUpdate:({chain:l,source:h})=>{l.id===this.chain.id&&l.rpcUrl===this.chain.rpcUrl||(this.chain=l,h!=="storage"&&this.emit("chainChanged",(0,X.hexStringFromIntNumber)((0,he.IntNumber)(l.id))))}},this.metadata=s,this.preference=o,this.communicator=new Is.Communicator(a),this.chain={id:(r=(t=s.appChainIds)===null||t===void 0?void 0:t[0])!==null&&r!==void 0?r:1};const c=(0,ge.loadSignerType)();this.signer=c?this.initSigner(c):null}get connected(){return this.accounts.length>0}async request(e){var t;try{const r=(0,vt.checkErrorForInvalidRequestArgs)(e);if(r)throw r;const s=(t=(0,Ms.determineMethodCategory)(e.method))!==null&&t!==void 0?t:"fetch";return this.handlers[s](e)}catch(r){return Promise.reject((0,ks.serializeError)(r,e.method))}}handleUnauthorizedError(e){e.code===V.standardErrorCodes.provider.unauthorized&&this.disconnect()}async enable(){return console.warn('.enable() has been deprecated. Please use .request({ method: "eth_requestAccounts" }) instead.'),await this.request({method:"eth_requestAccounts"})}async disconnect(){this.accounts=[],this.chain={id:1},Ls.ScopedLocalStorage.clearAll(),this.emit("disconnect",V.standardErrors.provider.disconnected("User initiated disconnection"))}requestSignerSelection(){return(0,ge.fetchSignerType)({communicator:this.communicator,preference:this.preference,metadata:this.metadata})}initSigner(e){return(0,ge.createSigner)({signerType:e,metadata:this.metadata,communicator:this.communicator,updateListener:this.updateListener})}}be.CoinbaseWalletProvider=As;Object.defineProperty(te,"__esModule",{value:!0});te.CoinbaseWalletSDK=void 0;const Rs=me,xs=be,Ps=O,Ns=K,Ts=u,js=k;class Os{constructor(e){this.metadata={appName:e.appName||"Dapp",appLogoUrl:e.appLogoUrl||(0,Ts.getFavicon)(),appChainIds:e.appChainIds||[]},this.storeLatestVersion()}makeWeb3Provider(e={options:"all"}){var t;const r={metadata:this.metadata,preference:e};return(t=(0,js.getCoinbaseInjectedProvider)(r))!==null&&t!==void 0?t:new xs.CoinbaseWalletProvider(r)}getCoinbaseWalletLogo(e,t=240){return(0,Rs.walletLogo)(e,t)}storeLatestVersion(){new Ps.ScopedLocalStorage("CBWSDK").setItem("VERSION",Ns.LIB_VERSION)}}te.CoinbaseWalletSDK=Os;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.CoinbaseWalletSDK=void 0;const e=te;n.default=e.CoinbaseWalletSDK;var t=te;Object.defineProperty(n,"CoinbaseWalletSDK",{enumerable:!0,get:function(){return t.CoinbaseWalletSDK}})})(Et);const Ds=an(Et),Bs=Object.freeze(Object.defineProperty({__proto__:null,default:Ds},Symbol.toStringTag,{value:"Module"}));export{Bs as i}; diff --git a/buddybook/assets/index-DY1ObU95.js b/buddybook/assets/index-DY1ObU95.js new file mode 100644 index 0000000..9b83ece --- /dev/null +++ b/buddybook/assets/index-DY1ObU95.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-wat9_83N.js","assets/index-B-6Lwopd.js","assets/index-Dt_CGZqf.css"])))=>i.map(i=>d[i]); +import{_ as pe}from"./index-B-6Lwopd.js";const me=Symbol(),ee=Object.getPrototypeOf,Y=new WeakMap,he=e=>e&&(Y.has(e)?Y.get(e):ee(e)===Object.prototype||ee(e)===Array.prototype),ge=e=>he(e)&&e[me]||null,te=(e,t=!0)=>{Y.set(e,t)},z={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},F=e=>typeof e=="object"&&e!==null,C=new WeakMap,x=new WeakSet,ye=(e=Object.is,t=(o,g)=>new Proxy(o,g),s=o=>F(o)&&!x.has(o)&&(Array.isArray(o)||!(Symbol.iterator in o))&&!(o instanceof WeakMap)&&!(o instanceof WeakSet)&&!(o instanceof Error)&&!(o instanceof Number)&&!(o instanceof Date)&&!(o instanceof String)&&!(o instanceof RegExp)&&!(o instanceof ArrayBuffer),n=o=>{switch(o.status){case"fulfilled":return o.value;case"rejected":throw o.reason;default:throw o}},l=new WeakMap,c=(o,g,I=n)=>{const v=l.get(o);if((v==null?void 0:v[0])===g)return v[1];const w=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o));return te(w,!0),l.set(o,[g,w]),Reflect.ownKeys(o).forEach(j=>{if(Object.getOwnPropertyDescriptor(w,j))return;const O=Reflect.get(o,j),A={value:O,enumerable:!0,configurable:!0};if(x.has(O))te(O,!1);else if(O instanceof Promise)delete A.value,A.get=()=>I(O);else if(C.has(O)){const[y,H]=C.get(O);A.value=c(y,H(),I)}Object.defineProperty(w,j,A)}),Object.preventExtensions(w)},d=new WeakMap,f=[1,1],W=o=>{if(!F(o))throw new Error("object required");const g=d.get(o);if(g)return g;let I=f[0];const v=new Set,w=(i,a=++f[0])=>{I!==a&&(I=a,v.forEach(r=>r(i,a)))};let j=f[1];const O=(i=++f[1])=>(j!==i&&!v.size&&(j=i,y.forEach(([a])=>{const r=a[1](i);r>I&&(I=r)})),I),A=i=>(a,r)=>{const h=[...a];h[1]=[i,...h[1]],w(h,r)},y=new Map,H=(i,a)=>{if((z?"production":void 0)!=="production"&&y.has(i))throw new Error("prop listener already exists");if(v.size){const r=a[3](A(i));y.set(i,[a,r])}else y.set(i,[a])},Z=i=>{var a;const r=y.get(i);r&&(y.delete(i),(a=r[1])==null||a.call(r))},ue=i=>(v.add(i),v.size===1&&y.forEach(([r,h],U)=>{if((z?"production":void 0)!=="production"&&h)throw new Error("remove already exists");const k=r[3](A(U));y.set(U,[r,k])}),()=>{v.delete(i),v.size===0&&y.forEach(([r,h],U)=>{h&&(h(),y.set(U,[r]))})}),q=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o)),R=t(q,{deleteProperty(i,a){const r=Reflect.get(i,a);Z(a);const h=Reflect.deleteProperty(i,a);return h&&w(["delete",[a],r]),h},set(i,a,r,h){const U=Reflect.has(i,a),k=Reflect.get(i,a,h);if(U&&(e(k,r)||d.has(r)&&e(k,d.get(r))))return!0;Z(a),F(r)&&(r=ge(r)||r);let V=r;if(r instanceof Promise)r.then(L=>{r.status="fulfilled",r.value=L,w(["resolve",[a],L])}).catch(L=>{r.status="rejected",r.reason=L,w(["reject",[a],L])});else{!C.has(r)&&s(r)&&(V=W(r));const L=!x.has(V)&&C.get(V);L&&H(a,L)}return Reflect.set(i,a,V,h),w(["set",[a],r,k]),!0}});d.set(o,R);const fe=[q,O,c,ue];return C.set(R,fe),Reflect.ownKeys(o).forEach(i=>{const a=Object.getOwnPropertyDescriptor(o,i);"value"in a&&(R[i]=o[i],delete a.value,delete a.writable),Object.defineProperty(q,i,a)}),R})=>[W,C,x,e,t,s,n,l,c,d,f],[ve]=ye();function P(e={}){return ve(e)}function D(e,t,s){const n=C.get(e);(z?"production":void 0)!=="production"&&!n&&console.warn("Please use proxy object");let l;const c=[],d=n[3];let f=!1;const o=d(g=>{c.push(g),l||(l=Promise.resolve().then(()=>{l=void 0,f&&t(c.splice(0))}))});return f=!0,()=>{f=!1,o()}}function we(e,t){const s=C.get(e);(z?"production":void 0)!=="production"&&!s&&console.warn("Please use proxy object");const[n,l,c]=s;return c(n,l(),t)}const u=P({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),de={state:u,subscribe(e){return D(u,()=>e(u))},push(e,t){e!==u.view&&(u.view=e,t&&(u.data=t),u.history.push(e))},reset(e){u.view=e,u.history=[e]},replace(e){u.history.length>1&&(u.history[u.history.length-1]=e,u.view=e)},goBack(){if(u.history.length>1){u.history.pop();const[e]=u.history.slice(-1);u.view=e}},setData(e){u.data=e}},m={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return m.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const e=navigator.userAgent.toLowerCase();return m.isMobile()&&(e.includes("iphone")||e.includes("ipad"))},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},isArray(e){return Array.isArray(e)&&e.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(e,t,s){if(m.isHttpUrl(e))return this.formatUniversalUrl(e,t,s);let n=e;n.includes("://")||(n=e.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},formatUniversalUrl(e,t,s){if(!m.isHttpUrl(e))return this.formatNativeUrl(e,t,s);let n=e;if(n.startsWith("https://t.me")){const c=Buffer.from(t).toString("base64").replace(/[=]/g,"");n.endsWith("/")&&(n=n.slice(0,-1)),this.setWalletConnectDeepLink(n,s);const d=new URL(n);return d.searchParams.set("startapp",c),d.toString()}n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},async wait(e){return new Promise(t=>{setTimeout(t,e)})},openHref(e,t){const s=this.isTelegram()?"_blank":t;window.open(e,s,"noreferrer noopener")},setWalletConnectDeepLink(e,t){try{localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(e){try{const[t]=e.split("?");localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(m.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(m.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var e;const t=(e=de.state.data)==null?void 0:e.Wallet;if(!t)throw new Error('Missing "Wallet" view data');return t}},be=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),p=P({enabled:be,userSessionId:"",events:[],connectedWalletId:void 0}),Ie={state:p,subscribe(e){return D(p.events,()=>e(we(p.events[p.events.length-1])))},initialize(){p.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(p.userSessionId=crypto.randomUUID())},setConnectedWalletId(e){p.connectedWalletId=e},click(e){if(p.enabled){const t={type:"CLICK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},track(e){if(p.enabled){const t={type:"TRACK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},view(e){if(p.enabled){const t={type:"VIEW",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}}},_=P({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),b={state:_,subscribe(e){return D(_,()=>e(_))},setChains(e){_.chains=e},setWalletConnectUri(e){_.walletConnectUri=e},setIsCustomDesktop(e){_.isCustomDesktop=e},setIsCustomMobile(e){_.isCustomMobile=e},setIsDataLoaded(e){_.isDataLoaded=e},setIsUiLoaded(e){_.isUiLoaded=e},setIsAuth(e){_.isAuth=e}},B=P({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),$={state:B,subscribe(e){return D(B,()=>e(B))},setConfig(e){var t,s;Ie.initialize(),b.setChains(e.chains),b.setIsAuth(!!e.enableAuthMode),b.setIsCustomMobile(!!((t=e.mobileWallets)!=null&&t.length)),b.setIsCustomDesktop(!!((s=e.desktopWallets)!=null&&s.length)),m.setModalVersionInStorage(),Object.assign(B,e)}};var _e=Object.defineProperty,se=Object.getOwnPropertySymbols,Ee=Object.prototype.hasOwnProperty,Oe=Object.prototype.propertyIsEnumerable,ne=(e,t,s)=>t in e?_e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,We=(e,t)=>{for(var s in t||(t={}))Ee.call(t,s)&&ne(e,s,t[s]);if(se)for(var s of se(t))Oe.call(t,s)&&ne(e,s,t[s]);return e};const G="https://explorer-api.walletconnect.com",Q="wcm",X="js-2.7.0";async function K(e,t){const s=We({sdkType:Q,sdkVersion:X},t),n=new URL(e,G);return n.searchParams.append("projectId",$.state.projectId),Object.entries(s).forEach(([c,d])=>{d&&n.searchParams.append(c,String(d))}),(await fetch(n)).json()}const M={async getDesktopListings(e){return K("/w3m/v1/getDesktopListings",e)},async getMobileListings(e){return K("/w3m/v1/getMobileListings",e)},async getInjectedListings(e){return K("/w3m/v1/getInjectedListings",e)},async getAllListings(e){return K("/w3m/v1/getAllListings",e)},getWalletImageUrl(e){return`${G}/w3m/v1/getWalletImage/${e}?projectId=${$.state.projectId}&sdkType=${Q}&sdkVersion=${X}`},getAssetImageUrl(e){return`${G}/w3m/v1/getAssetImage/${e}?projectId=${$.state.projectId}&sdkType=${Q}&sdkVersion=${X}`}};var Le=Object.defineProperty,oe=Object.getOwnPropertySymbols,Ce=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable,re=(e,t,s)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ae=(e,t)=>{for(var s in t||(t={}))Ce.call(t,s)&&re(e,s,t[s]);if(oe)for(var s of oe(t))Pe.call(t,s)&&re(e,s,t[s]);return e};const ae=m.isMobile(),E=P({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),Ne={state:E,async getRecomendedWallets(){const{explorerRecommendedWalletIds:e,explorerExcludedWalletIds:t}=$.state;if(e==="NONE"||t==="ALL"&&!e)return E.recomendedWallets;if(m.isArray(e)){const n={recommendedIds:e.join(",")},{listings:l}=await M.getAllListings(n),c=Object.values(l);c.sort((d,f)=>{const W=e.indexOf(d.id),o=e.indexOf(f.id);return W-o}),E.recomendedWallets=c}else{const{chains:s,isAuth:n}=b.state,l=s==null?void 0:s.join(","),c=m.isArray(t),d={page:1,sdks:n?"auth_v1":void 0,entries:m.RECOMMENDED_WALLET_AMOUNT,chains:l,version:2,excludedIds:c?t.join(","):void 0},{listings:f}=ae?await M.getMobileListings(d):await M.getDesktopListings(d);E.recomendedWallets=Object.values(f)}return E.recomendedWallets},async getWallets(e){const t=Ae({},e),{explorerRecommendedWalletIds:s,explorerExcludedWalletIds:n}=$.state,{recomendedWallets:l}=E;if(n==="ALL")return E.wallets;l.length?t.excludedIds=l.map(I=>I.id).join(","):m.isArray(s)&&(t.excludedIds=s.join(",")),m.isArray(n)&&(t.excludedIds=[t.excludedIds,n].filter(Boolean).join(",")),b.state.isAuth&&(t.sdks="auth_v1");const{page:c,search:d}=e,{listings:f,total:W}=ae?await M.getMobileListings(t):await M.getDesktopListings(t),o=Object.values(f),g=d?"search":"wallets";return E[g]={listings:[...E[g].listings,...o],total:W,page:c??1},{listings:o,total:W}},getWalletImageUrl(e){return M.getWalletImageUrl(e)},getAssetImageUrl(e){return M.getAssetImageUrl(e)},resetSearch(){E.search={listings:[],total:0,page:1}}},T=P({open:!1}),J={state:T,subscribe(e){return D(T,()=>e(T))},async open(e){return new Promise(t=>{const{isUiLoaded:s,isDataLoaded:n}=b.state;if(m.removeWalletConnectDeepLink(),b.setWalletConnectUri(e==null?void 0:e.uri),b.setChains(e==null?void 0:e.chains),de.reset("ConnectWallet"),s&&n)T.open=!0,t();else{const l=setInterval(()=>{const c=b.state;c.isUiLoaded&&c.isDataLoaded&&(clearInterval(l),T.open=!0,t())},200)}})},close(){T.open=!1}};var Me=Object.defineProperty,ie=Object.getOwnPropertySymbols,Se=Object.prototype.hasOwnProperty,De=Object.prototype.propertyIsEnumerable,le=(e,t,s)=>t in e?Me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,je=(e,t)=>{for(var s in t||(t={}))Se.call(t,s)&&le(e,s,t[s]);if(ie)for(var s of ie(t))De.call(t,s)&&le(e,s,t[s]);return e};function Ue(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const N=P({themeMode:Ue()?"dark":"light"}),ce={state:N,subscribe(e){return D(N,()=>e(N))},setThemeConfig(e){const{themeMode:t,themeVariables:s}=e;t&&(N.themeMode=t),s&&(N.themeVariables=je({},s))}},S=P({open:!1,message:"",variant:"success"}),Re={state:S,subscribe(e){return D(S,()=>e(S))},openToast(e,t){S.open=!0,S.message=e,S.variant=t},closeToast(){S.open=!1}};class Te{constructor(t){this.openModal=J.open,this.closeModal=J.close,this.subscribeModal=J.subscribe,this.setTheme=ce.setThemeConfig,ce.setThemeConfig(t),$.setConfig(t),this.initUi()}async initUi(){if(typeof window<"u"){await pe(()=>import("./index-wat9_83N.js"),__vite__mapDeps([0,1,2]));const t=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",t),b.setIsUiLoaded(!0)}}}const Ve=Object.freeze(Object.defineProperty({__proto__:null,WalletConnectModal:Te},Symbol.toStringTag,{value:"Module"}));export{m as C,Ne as E,J as M,b as O,de as R,ce as T,Re as a,Ie as b,$ as c,Ve as i}; diff --git a/buddybook/assets/index-Dt_CGZqf.css b/buddybook/assets/index-Dt_CGZqf.css new file mode 100644 index 0000000..65e8ada --- /dev/null +++ b/buddybook/assets/index-Dt_CGZqf.css @@ -0,0 +1 @@ +#root{max-width:1280px;margin:0 auto;padding:2rem;text-align:center}.logo{height:6em;padding:1.5em;will-change:filter;transition:filter .3s}.logo:hover{filter:drop-shadow(0 0 2em #646cffaa)}.logo.react:hover{filter:drop-shadow(0 0 2em #61dafbaa)}@keyframes logo-spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@media (prefers-reduced-motion: no-preference){a:nth-of-type(2) .logo{animation:logo-spin infinite 20s linear}}.card{padding:2em}.read-the-docs{color:#888}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}:root{--background: 0 0% 100%;--foreground: 0 0% 3.9%;--card: 0 0% 100%;--card-foreground: 0 0% 3.9%;--popover: 0 0% 100%;--popover-foreground: 0 0% 3.9%;--primary: 0 0% 9%;--primary-foreground: 0 0% 98%;--secondary: 0 0% 96.1%;--secondary-foreground: 0 0% 9%;--muted: 0 0% 96.1%;--muted-foreground: 0 0% 45.1%;--accent: 0 0% 96.1%;--accent-foreground: 0 0% 9%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 0 0% 98%;--border: 0 0% 89.8%;--input: 0 0% 89.8%;--ring: 0 0% 3.9%;--chart-1: 12 76% 61%;--chart-2: 173 58% 39%;--chart-3: 197 37% 24%;--chart-4: 43 74% 66%;--chart-5: 27 87% 67%;--radius: .5rem }*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground))}.container{padding-left:1rem;padding-right:1rem}@media (min-width: 768px){.container{padding-left:1.5rem;padding-right:1.5rem}}@media (min-width: 1024px){.container{padding-left:2rem;padding-right:2rem}}h1{font-size:1.5rem;line-height:2rem;font-weight:700}@media (min-width: 768px){h1{font-size:2.25rem;line-height:2.5rem}}h2{font-size:1.25rem;line-height:1.75rem;font-weight:600}@media (min-width: 768px){h2{font-size:1.875rem;line-height:2.25rem}}h3{font-size:1.125rem;line-height:1.75rem;font-weight:600}@media (min-width: 768px){h3{font-size:1.5rem;line-height:2rem}}.container{width:100%}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.prose{color:var(--tw-prose-body);max-width:65ch}.prose :where(p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where([class~=lead]):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-lead);font-size:1.25em;line-height:1.6;margin-top:1.2em;margin-bottom:1.2em}.prose :where(a):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-links);text-decoration:underline;font-weight:500}.prose :where(strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-bold);font-weight:600}.prose :where(a strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(blockquote strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(thead th strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(ol):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal;margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em}.prose :where(ol[type=A]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=A s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=I]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type=I s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type="1"]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal}.prose :where(ul):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:disc;margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{font-weight:400;color:var(--tw-prose-counters)}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-bullets)}.prose :where(dt):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);font-weight:600;margin-top:1.25em}.prose :where(hr):not(:where([class~=not-prose],[class~=not-prose] *)){border-color:var(--tw-prose-hr);border-top-width:1px;margin-top:3em;margin-bottom:3em}.prose :where(blockquote):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:500;font-style:italic;color:var(--tw-prose-quotes);border-inline-start-width:.25rem;border-inline-start-color:var(--tw-prose-quote-borders);quotes:"“""”""‘""’";margin-top:1.6em;margin-bottom:1.6em;padding-inline-start:1em}.prose :where(blockquote p:first-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:open-quote}.prose :where(blockquote p:last-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:close-quote}.prose :where(h1):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);font-weight:800;font-size:2.25em;margin-top:0;margin-bottom:.8888889em;line-height:1.1111111}.prose :where(h1 strong):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:900;color:inherit}.prose :where(h2):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);font-weight:700;font-size:1.5em;margin-top:2em;margin-bottom:1em;line-height:1.3333333}.prose :where(h2 strong):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:800;color:inherit}.prose :where(h3):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);font-weight:600;font-size:1.25em;margin-top:1.6em;margin-bottom:.6em;line-height:1.6}.prose :where(h3 strong):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:700;color:inherit}.prose :where(h4):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);font-weight:600;margin-top:1.5em;margin-bottom:.5em;line-height:1.5}.prose :where(h4 strong):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:700;color:inherit}.prose :where(img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(picture):not(:where([class~=not-prose],[class~=not-prose] *)){display:block;margin-top:2em;margin-bottom:2em}.prose :where(video):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(kbd):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:500;font-family:inherit;color:var(--tw-prose-kbd);box-shadow:0 0 0 1px rgb(var(--tw-prose-kbd-shadows) / 10%),0 3px rgb(var(--tw-prose-kbd-shadows) / 10%);font-size:.875em;border-radius:.3125rem;padding-top:.1875em;padding-inline-end:.375em;padding-bottom:.1875em;padding-inline-start:.375em}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-code);font-weight:600;font-size:.875em}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:"`"}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:"`"}.prose :where(a code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h1 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h2 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.875em}.prose :where(h3 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.9em}.prose :where(h4 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(blockquote code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(thead th code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(pre):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-pre-code);background-color:var(--tw-prose-pre-bg);overflow-x:auto;font-weight:400;font-size:.875em;line-height:1.7142857;margin-top:1.7142857em;margin-bottom:1.7142857em;border-radius:.375rem;padding-top:.8571429em;padding-inline-end:1.1428571em;padding-bottom:.8571429em;padding-inline-start:1.1428571em}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)){background-color:transparent;border-width:0;border-radius:0;padding:0;font-weight:inherit;color:inherit;font-size:inherit;font-family:inherit;line-height:inherit}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:none}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:none}.prose :where(table):not(:where([class~=not-prose],[class~=not-prose] *)){width:100%;table-layout:auto;margin-top:2em;margin-bottom:2em;font-size:.875em;line-height:1.7142857}.prose :where(thead):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-th-borders)}.prose :where(thead th):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);font-weight:600;vertical-align:bottom;padding-inline-end:.5714286em;padding-bottom:.5714286em;padding-inline-start:.5714286em}.prose :where(tbody tr):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-td-borders)}.prose :where(tbody tr:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:0}.prose :where(tbody td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:baseline}.prose :where(tfoot):not(:where([class~=not-prose],[class~=not-prose] *)){border-top-width:1px;border-top-color:var(--tw-prose-th-borders)}.prose :where(tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:top}.prose :where(th,td):not(:where([class~=not-prose],[class~=not-prose] *)){text-align:start}.prose :where(figure>*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(figcaption):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-captions);font-size:.875em;line-height:1.4285714;margin-top:.8571429em}.prose{--tw-prose-body: #374151;--tw-prose-headings: #111827;--tw-prose-lead: #4b5563;--tw-prose-links: #111827;--tw-prose-bold: #111827;--tw-prose-counters: #6b7280;--tw-prose-bullets: #d1d5db;--tw-prose-hr: #e5e7eb;--tw-prose-quotes: #111827;--tw-prose-quote-borders: #e5e7eb;--tw-prose-captions: #6b7280;--tw-prose-kbd: #111827;--tw-prose-kbd-shadows: 17 24 39;--tw-prose-code: #111827;--tw-prose-pre-code: #e5e7eb;--tw-prose-pre-bg: #1f2937;--tw-prose-th-borders: #d1d5db;--tw-prose-td-borders: #e5e7eb;--tw-prose-invert-body: #d1d5db;--tw-prose-invert-headings: #fff;--tw-prose-invert-lead: #9ca3af;--tw-prose-invert-links: #fff;--tw-prose-invert-bold: #fff;--tw-prose-invert-counters: #9ca3af;--tw-prose-invert-bullets: #4b5563;--tw-prose-invert-hr: #374151;--tw-prose-invert-quotes: #f3f4f6;--tw-prose-invert-quote-borders: #374151;--tw-prose-invert-captions: #9ca3af;--tw-prose-invert-kbd: #fff;--tw-prose-invert-kbd-shadows: 255 255 255;--tw-prose-invert-code: #fff;--tw-prose-invert-pre-code: #d1d5db;--tw-prose-invert-pre-bg: rgb(0 0 0 / 50%);--tw-prose-invert-th-borders: #4b5563;--tw-prose-invert-td-borders: #374151;font-size:1rem;line-height:1.75}.prose :where(picture>img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(li):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;margin-bottom:.5em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(.prose>ul>li p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(.prose>ul>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ul>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(.prose>ol>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ol>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(ul ul,ul ol,ol ul,ol ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(dl):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where(dd):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;padding-inline-start:1.625em}.prose :where(hr+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(h2+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(h3+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(h4+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(thead th:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(thead th:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(tbody td,tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){padding-top:.5714286em;padding-inline-end:.5714286em;padding-bottom:.5714286em;padding-inline-start:.5714286em}.prose :where(tbody td:first-child,tfoot td:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(tbody td:last-child,tfoot td:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(figure):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(.prose>:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(.prose>:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:0}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.left-\[50\%\]{left:50%}.right-4{right:1rem}.top-4{top:1rem}.top-\[50\%\]{top:50%}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.ml-2{margin-left:.5rem}.ml-8{margin-left:2rem}.mr-2{margin-right:.5rem}.mr-4{margin-right:1rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.\!block{display:block!important}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.h-10{height:2.5rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-4{height:1rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[50vh\]{height:50vh}.h-full{height:100%}.max-h-\[90vh\]{max-height:90vh}.min-h-\[60px\]{min-height:60px}.min-h-screen{min-height:100vh}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-4{width:1rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[95vw\]{width:95vw}.w-full{width:100%}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-7xl{max-width:80rem}.max-w-\[120px\]{max-width:120px}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-none{max-width:none}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-grow{flex-grow:1}.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-all{word-break:break-all}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l{border-left-width:1px}.border-l-2{border-left-width:2px}.border-t{border-top-width:1px}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity))}.border-input{border-color:hsl(var(--input))}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-background{background-color:hsl(var(--background))}.bg-black\/80{background-color:#000c}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity))}.bg-muted{background-color:hsl(var(--muted))}.bg-primary{background-color:hsl(var(--primary))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity))}.bg-secondary{background-color:hsl(var(--secondary))}.bg-transparent{background-color:transparent}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity))}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\[1px\]{padding:1px}.px-0{padding-left:0;padding-right:0}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pt-0{padding-top:0}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.text-card-foreground{color:hsl(var(--card-foreground))}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-foreground{color:hsl(var(--foreground))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.underline-offset-4{text-underline-offset:4px}.opacity-70{opacity:.7}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline{outline-style:solid}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.duration-200{animation-duration:.2s}.dark\:prose-invert:is(.dark *){--tw-prose-body: var(--tw-prose-invert-body);--tw-prose-headings: var(--tw-prose-invert-headings);--tw-prose-lead: var(--tw-prose-invert-lead);--tw-prose-links: var(--tw-prose-invert-links);--tw-prose-bold: var(--tw-prose-invert-bold);--tw-prose-counters: var(--tw-prose-invert-counters);--tw-prose-bullets: var(--tw-prose-invert-bullets);--tw-prose-hr: var(--tw-prose-invert-hr);--tw-prose-quotes: var(--tw-prose-invert-quotes);--tw-prose-quote-borders: var(--tw-prose-invert-quote-borders);--tw-prose-captions: var(--tw-prose-invert-captions);--tw-prose-kbd: var(--tw-prose-invert-kbd);--tw-prose-kbd-shadows: var(--tw-prose-invert-kbd-shadows);--tw-prose-code: var(--tw-prose-invert-code);--tw-prose-pre-code: var(--tw-prose-invert-pre-code);--tw-prose-pre-bg: var(--tw-prose-invert-pre-bg);--tw-prose-th-borders: var(--tw-prose-invert-th-borders);--tw-prose-td-borders: var(--tw-prose-invert-td-borders)}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.file\:text-foreground::file-selector-button{color:hsl(var(--foreground))}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}@media (min-width: 640px){.sm\:h-\[60vh\]{height:60vh}.sm\:w-auto{width:auto}.sm\:max-w-md{max-width:28rem}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-start{justify-content:flex-start}.sm\:justify-end{justify-content:flex-end}.sm\:justify-between{justify-content:space-between}.sm\:gap-4{gap:1rem}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:p-4{padding:1rem}.sm\:p-6{padding:1.5rem}.sm\:text-left{text-align:left}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}.sm\:text-3xl{font-size:1.875rem;line-height:2.25rem}.sm\:text-base{font-size:1rem;line-height:1.5rem}.sm\:text-xl{font-size:1.25rem;line-height:1.75rem}}@media (min-width: 768px){.md\:inline{display:inline}.md\:h-3{height:.75rem}.md\:w-3{width:.75rem}.md\:w-auto{width:auto}.md\:max-w-none{max-width:none}.md\:flex-row{flex-direction:row}.md\:justify-start{justify-content:flex-start}.md\:justify-end{justify-content:flex-end}.md\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.md\:space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.md\:space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.md\:p-6{padding:1.5rem}.md\:py-4{padding-top:1rem;padding-bottom:1rem}.md\:py-8{padding-top:2rem;padding-bottom:2rem}.md\:text-2xl{font-size:1.5rem;line-height:2rem}.md\:text-4xl{font-size:2.25rem;line-height:2.5rem}.md\:text-base{font-size:1rem;line-height:1.5rem}.md\:text-sm{font-size:.875rem;line-height:1.25rem}}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:size-4 svg{width:1rem;height:1rem}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0} diff --git a/buddybook/assets/index-Dz_NkDRB.js b/buddybook/assets/index-Dz_NkDRB.js new file mode 100644 index 0000000..14fd86c --- /dev/null +++ b/buddybook/assets/index-Dz_NkDRB.js @@ -0,0 +1 @@ +import{e as p}from"./events-BzDGR98G.js";function _(n,r){for(var i=0;ie[s]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}var l={},g={},f={};Object.defineProperty(f,"__esModule",{value:!0});f.getLowerCase=void 0;function m(n){return n&&n.toLowerCase()}f.getLowerCase=m;Object.defineProperty(g,"__esModule",{value:!0});g.SafeAppProvider=void 0;const w=p,u=f;class k extends w.EventEmitter{constructor(r,i){super(),this.submittedTxs=new Map,this.safe=r,this.sdk=i}async connect(){this.emit("connect",{chainId:this.chainId})}async disconnect(){}get chainId(){return this.safe.chainId}async request(r){const{method:i,params:e=[]}=r;switch(i){case"eth_accounts":return[this.safe.safeAddress];case"net_version":case"eth_chainId":return`0x${this.chainId.toString(16)}`;case"personal_sign":{const[t,a]=e;if(this.safe.safeAddress.toLowerCase()!==a.toLowerCase())throw new Error("The address or message hash is invalid");const h=await this.sdk.txs.signMessage(t);return("signature"in h?h.signature:void 0)||"0x"}case"eth_sign":{const[t,a]=e;if(this.safe.safeAddress.toLowerCase()!==t.toLowerCase()||!a.startsWith("0x"))throw new Error("The address or message hash is invalid");const h=await this.sdk.txs.signMessage(a);return("signature"in h?h.signature:void 0)||"0x"}case"eth_signTypedData":case"eth_signTypedData_v4":{const[t,a]=e,h=typeof a=="string"?JSON.parse(a):a;if(this.safe.safeAddress.toLowerCase()!==t.toLowerCase())throw new Error("The address is invalid");const c=await this.sdk.txs.signTypedMessage(h);return("signature"in c?c.signature:void 0)||"0x"}case"eth_sendTransaction":const s={...e[0],value:e[0].value||"0",data:e[0].data||"0x"};typeof s.gas=="string"&&s.gas.startsWith("0x")&&(s.gas=parseInt(s.gas,16));const o=await this.sdk.txs.send({txs:[s],params:{safeTxGas:s.gas}});return this.submittedTxs.set(o.safeTxHash,{from:this.safe.safeAddress,hash:o.safeTxHash,gas:0,gasPrice:"0x00",nonce:0,input:s.data,value:s.value,to:s.to,blockHash:null,blockNumber:null,transactionIndex:null}),o.safeTxHash;case"eth_blockNumber":return(await this.sdk.eth.getBlockByNumber(["latest"])).number;case"eth_getBalance":return this.sdk.eth.getBalance([(0,u.getLowerCase)(e[0]),e[1]]);case"eth_getCode":return this.sdk.eth.getCode([(0,u.getLowerCase)(e[0]),e[1]]);case"eth_getTransactionCount":return this.sdk.eth.getTransactionCount([(0,u.getLowerCase)(e[0]),e[1]]);case"eth_getStorageAt":return this.sdk.eth.getStorageAt([(0,u.getLowerCase)(e[0]),e[1],e[2]]);case"eth_getBlockByNumber":return this.sdk.eth.getBlockByNumber([e[0],e[1]]);case"eth_getBlockByHash":return this.sdk.eth.getBlockByHash([e[0],e[1]]);case"eth_getTransactionByHash":let d=e[0];try{d=(await this.sdk.txs.getBySafeTxHash(d)).txHash||d}catch{}return this.submittedTxs.has(d)?this.submittedTxs.get(d):this.sdk.eth.getTransactionByHash([d]).then(t=>(t&&(t.hash=e[0]),t));case"eth_getTransactionReceipt":{let t=e[0];try{t=(await this.sdk.txs.getBySafeTxHash(t)).txHash||t}catch{}return this.sdk.eth.getTransactionReceipt([t]).then(a=>(a&&(a.transactionHash=e[0]),a))}case"eth_estimateGas":return this.sdk.eth.getEstimateGas(e[0]);case"eth_call":return this.sdk.eth.call([e[0],e[1]]);case"eth_getLogs":return this.sdk.eth.getPastLogs([e[0]]);case"eth_gasPrice":return this.sdk.eth.getGasPrice();case"wallet_getPermissions":return this.sdk.wallet.getPermissions();case"wallet_requestPermissions":return this.sdk.wallet.requestPermissions(e[0]);case"safe_setSettings":return this.sdk.eth.setSafeSettings([e[0]]);default:throw Error(`"${r.method}" not implemented`)}}send(r,i){r||i("Undefined request"),this.request(r).then(e=>i(null,{jsonrpc:"2.0",id:r.id,result:e})).catch(e=>i(e,null))}}g.SafeAppProvider=k;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.SafeAppProvider=void 0;var r=g;Object.defineProperty(n,"SafeAppProvider",{enumerable:!0,get:function(){return r.SafeAppProvider}})})(l);const T=_({__proto__:null},[l]);export{T as i}; diff --git a/buddybook/assets/index-FH8NN1-S.js b/buddybook/assets/index-FH8NN1-S.js new file mode 100644 index 0000000..0b33e2a --- /dev/null +++ b/buddybook/assets/index-FH8NN1-S.js @@ -0,0 +1,7 @@ +import{d as x,g as Hs,j as xc,l as Tc,h as Pc}from"./index-B-6Lwopd.js";import{r as $c}from"./inherits_browser-BwZ6FBWK.js";import{s as Oc,r as Ke,a as an,j as Bc,b as Dc}from"./hooks.module-D7M4pAco.js";import{e as ta}from"./events-BzDGR98G.js";var ra={},br={},cn={};Object.defineProperty(cn,"__esModule",{value:!0});cn.walletLogo=void 0;const jc=(t,e)=>{let r;switch(t){case"standard":return r=e,`data:image/svg+xml,%3Csvg width='${e}' height='${r}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `;case"circle":return r=e,`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${e}' height='${r}' viewBox='0 0 999.81 999.81'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052fe;%7D.cls-2%7Bfill:%23fefefe;%7D.cls-3%7Bfill:%230152fe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M655-115.9h56c.83,1.59,2.36.88,3.56,1a478,478,0,0,1,75.06,10.42C891.4-81.76,978.33-32.58,1049.19,44q116.7,126,131.94,297.61c.38,4.14-.34,8.53,1.78,12.45v59c-1.58.84-.91,2.35-1,3.56a482.05,482.05,0,0,1-10.38,74.05c-24,106.72-76.64,196.76-158.83,268.93s-178.18,112.82-287.2,122.6c-4.83.43-9.86-.25-14.51,1.77H654c-1-1.68-2.69-.91-4.06-1a496.89,496.89,0,0,1-105.9-18.59c-93.54-27.42-172.78-77.59-236.91-150.94Q199.34,590.1,184.87,426.58c-.47-5.19.25-10.56-1.77-15.59V355c1.68-1,.91-2.7,1-4.06a498.12,498.12,0,0,1,18.58-105.9c26-88.75,72.64-164.9,140.6-227.57q126-116.27,297.21-131.61C645.32-114.57,650.35-113.88,655-115.9Zm377.92,500c0-192.44-156.31-349.49-347.56-350.15-194.13-.68-350.94,155.13-352.29,347.42-1.37,194.55,155.51,352.1,348.56,352.47C876.15,734.23,1032.93,577.84,1032.93,384.11Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-2' d='M1032.93,384.11c0,193.73-156.78,350.12-351.29,349.74-193-.37-349.93-157.92-348.56-352.47C334.43,189.09,491.24,33.28,685.37,34,876.62,34.62,1032.94,191.67,1032.93,384.11ZM683,496.81q43.74,0,87.48,0c15.55,0,25.32-9.72,25.33-25.21q0-87.48,0-175c0-15.83-9.68-25.46-25.59-25.46H595.77c-15.88,0-25.57,9.64-25.58,25.46q0,87.23,0,174.45c0,16.18,9.59,25.7,25.84,25.71Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-3' d='M683,496.81H596c-16.25,0-25.84-9.53-25.84-25.71q0-87.23,0-174.45c0-15.82,9.7-25.46,25.58-25.46H770.22c15.91,0,25.59,9.63,25.59,25.46q0,87.47,0,175c0,15.49-9.78,25.2-25.33,25.21Q726.74,496.84,683,496.81Z' transform='translate(-183.1 115.9)'/%3E%3C/svg%3E`;case"text":return r=(.1*e).toFixed(2),`data:image/svg+xml,%3Csvg width='${e}' height='${r}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogo":return r=(.25*e).toFixed(2),`data:image/svg+xml,%3Csvg width='${e}' height='${r}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;case"textLight":return r=(.1*e).toFixed(2),`data:image/svg+xml,%3Csvg width='${e}' height='${r}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogoLight":return r=(.25*e).toFixed(2),`data:image/svg+xml,%3Csvg width='${e}' height='${r}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;default:return r=e,`data:image/svg+xml,%3Csvg width='${e}' height='${r}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `}};cn.walletLogo=jc;var ln={};Object.defineProperty(ln,"__esModule",{value:!0});ln.LINK_API_URL=void 0;ln.LINK_API_URL="https://www.walletlink.org";var A={},Us={exports:{}};Us.exports;(function(t){(function(e,r){function n(b,o){if(!b)throw new Error(o||"Assertion failed")}function i(b,o){b.super_=o;var l=function(){};l.prototype=o.prototype,b.prototype=new l,b.prototype.constructor=b}function s(b,o,l){if(s.isBN(b))return b;this.negative=0,this.words=null,this.length=0,this.red=null,b!==null&&((o==="le"||o==="be")&&(l=o,o=10),this._init(b||0,o||10,l||"be"))}typeof e=="object"?e.exports=s:r.BN=s,s.BN=s,s.wordSize=26;var c;try{typeof window<"u"&&typeof window.Buffer<"u"?c=window.Buffer:c=$c.Buffer}catch{}s.isBN=function(o){return o instanceof s?!0:o!==null&&typeof o=="object"&&o.constructor.wordSize===s.wordSize&&Array.isArray(o.words)},s.max=function(o,l){return o.cmp(l)>0?o:l},s.min=function(o,l){return o.cmp(l)<0?o:l},s.prototype._init=function(o,l,f){if(typeof o=="number")return this._initNumber(o,l,f);if(typeof o=="object")return this._initArray(o,l,f);l==="hex"&&(l=16),n(l===(l|0)&&l>=2&&l<=36),o=o.toString().replace(/\s+/g,"");var g=0;o[0]==="-"&&(g++,this.negative=1),g=0;g-=3)w=o[g]|o[g-1]<<8|o[g-2]<<16,this.words[m]|=w<<_&67108863,this.words[m+1]=w>>>26-_&67108863,_+=24,_>=26&&(_-=26,m++);else if(f==="le")for(g=0,m=0;g>>26-_&67108863,_+=24,_>=26&&(_-=26,m++);return this._strip()};function u(b,o){var l=b.charCodeAt(o);if(l>=48&&l<=57)return l-48;if(l>=65&&l<=70)return l-55;if(l>=97&&l<=102)return l-87;n(!1,"Invalid character in "+b)}function d(b,o,l){var f=u(b,l);return l-1>=o&&(f|=u(b,l-1)<<4),f}s.prototype._parseHex=function(o,l,f){this.length=Math.ceil((o.length-l)/6),this.words=new Array(this.length);for(var g=0;g=l;g-=2)_=d(o,l,g)<=18?(m-=18,w+=1,this.words[w]|=_>>>26):m+=8;else{var p=o.length-l;for(g=p%2===0?l+1:l;g=18?(m-=18,w+=1,this.words[w]|=_>>>26):m+=8}this._strip()};function h(b,o,l,f){for(var g=0,m=0,w=Math.min(b.length,l),_=o;_=49?m=p-49+10:p>=17?m=p-17+10:m=p,n(p>=0&&m1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=S}catch{s.prototype.inspect=S}else s.prototype.inspect=S;function S(){return(this.red?""}var E=["","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"],M=[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],k=[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];s.prototype.toString=function(o,l){o=o||10,l=l|0||1;var f;if(o===16||o==="hex"){f="";for(var g=0,m=0,w=0;w>>24-g&16777215,g+=2,g>=26&&(g-=26,w--),m!==0||w!==this.length-1?f=E[6-p.length]+p+f:f=p+f}for(m!==0&&(f=m.toString(16)+f);f.length%l!==0;)f="0"+f;return this.negative!==0&&(f="-"+f),f}if(o===(o|0)&&o>=2&&o<=36){var a=M[o],v=k[o];f="";var N=this.clone();for(N.negative=0;!N.isZero();){var I=N.modrn(v).toString(o);N=N.idivn(v),N.isZero()?f=I+f:f=E[a-I.length]+I+f}for(this.isZero()&&(f="0"+f);f.length%l!==0;)f="0"+f;return this.negative!==0&&(f="-"+f),f}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var o=this.words[0];return this.length===2?o+=this.words[1]*67108864:this.length===3&&this.words[2]===1?o+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-o:o},s.prototype.toJSON=function(){return this.toString(16,2)},c&&(s.prototype.toBuffer=function(o,l){return this.toArrayLike(c,o,l)}),s.prototype.toArray=function(o,l){return this.toArrayLike(Array,o,l)};var T=function(o,l){return o.allocUnsafe?o.allocUnsafe(l):new o(l)};s.prototype.toArrayLike=function(o,l,f){this._strip();var g=this.byteLength(),m=f||Math.max(1,g);n(g<=m,"byte array longer than desired length"),n(m>0,"Requested array length <= 0");var w=T(o,m),_=l==="le"?"LE":"BE";return this["_toArrayLike"+_](w,g),w},s.prototype._toArrayLikeLE=function(o,l){for(var f=0,g=0,m=0,w=0;m>8&255),f>16&255),w===6?(f>24&255),g=0,w=0):(g=_>>>24,w+=2)}if(f=0&&(o[f--]=_>>8&255),f>=0&&(o[f--]=_>>16&255),w===6?(f>=0&&(o[f--]=_>>24&255),g=0,w=0):(g=_>>>24,w+=2)}if(f>=0)for(o[f--]=g;f>=0;)o[f--]=0},Math.clz32?s.prototype._countBits=function(o){return 32-Math.clz32(o)}:s.prototype._countBits=function(o){var l=o,f=0;return l>=4096&&(f+=13,l>>>=13),l>=64&&(f+=7,l>>>=7),l>=8&&(f+=4,l>>>=4),l>=2&&(f+=2,l>>>=2),f+l},s.prototype._zeroBits=function(o){if(o===0)return 26;var l=o,f=0;return l&8191||(f+=13,l>>>=13),l&127||(f+=7,l>>>=7),l&15||(f+=4,l>>>=4),l&3||(f+=2,l>>>=2),l&1||f++,f},s.prototype.bitLength=function(){var o=this.words[this.length-1],l=this._countBits(o);return(this.length-1)*26+l};function O(b){for(var o=new Array(b.bitLength()),l=0;l>>g&1}return o}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var o=0,l=0;lo.length?this.clone().ior(o):o.clone().ior(this)},s.prototype.uor=function(o){return this.length>o.length?this.clone().iuor(o):o.clone().iuor(this)},s.prototype.iuand=function(o){var l;this.length>o.length?l=o:l=this;for(var f=0;fo.length?this.clone().iand(o):o.clone().iand(this)},s.prototype.uand=function(o){return this.length>o.length?this.clone().iuand(o):o.clone().iuand(this)},s.prototype.iuxor=function(o){var l,f;this.length>o.length?(l=this,f=o):(l=o,f=this);for(var g=0;go.length?this.clone().ixor(o):o.clone().ixor(this)},s.prototype.uxor=function(o){return this.length>o.length?this.clone().iuxor(o):o.clone().iuxor(this)},s.prototype.inotn=function(o){n(typeof o=="number"&&o>=0);var l=Math.ceil(o/26)|0,f=o%26;this._expand(l),f>0&&l--;for(var g=0;g0&&(this.words[g]=~this.words[g]&67108863>>26-f),this._strip()},s.prototype.notn=function(o){return this.clone().inotn(o)},s.prototype.setn=function(o,l){n(typeof o=="number"&&o>=0);var f=o/26|0,g=o%26;return this._expand(f+1),l?this.words[f]=this.words[f]|1<o.length?(f=this,g=o):(f=o,g=this);for(var m=0,w=0;w>>26;for(;m!==0&&w>>26;if(this.length=f.length,m!==0)this.words[this.length]=m,this.length++;else if(f!==this)for(;wo.length?this.clone().iadd(o):o.clone().iadd(this)},s.prototype.isub=function(o){if(o.negative!==0){o.negative=0;var l=this.iadd(o);return o.negative=1,l._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(o),this.negative=1,this._normSign();var f=this.cmp(o);if(f===0)return this.negative=0,this.length=1,this.words[0]=0,this;var g,m;f>0?(g=this,m=o):(g=o,m=this);for(var w=0,_=0;_>26,this.words[_]=l&67108863;for(;w!==0&&_>26,this.words[_]=l&67108863;if(w===0&&_>>26,N=p&67108863,I=Math.min(a,o.length-1),$=Math.max(0,a-b.length+1);$<=I;$++){var ze=a-$|0;g=b.words[ze]|0,m=o.words[$]|0,w=g*m+N,v+=w/67108864|0,N=w&67108863}l.words[a]=N|0,p=v|0}return p!==0?l.words[a]=p|0:l.length--,l._strip()}var L=function(o,l,f){var g=o.words,m=l.words,w=f.words,_=0,p,a,v,N=g[0]|0,I=N&8191,$=N>>>13,ze=g[1]|0,G=ze&8191,Z=ze>>>13,ki=g[2]|0,te=ki&8191,re=ki>>>13,Ri=g[3]|0,ne=Ri&8191,se=Ri>>>13,Ii=g[4]|0,ie=Ii&8191,oe=Ii>>>13,Ci=g[5]|0,ae=Ci&8191,ce=Ci>>>13,Ai=g[6]|0,le=Ai&8191,ue=Ai>>>13,Ni=g[7]|0,de=Ni&8191,he=Ni>>>13,Li=g[8]|0,fe=Li&8191,ge=Li>>>13,xi=g[9]|0,pe=xi&8191,me=xi>>>13,Ti=m[0]|0,ve=Ti&8191,we=Ti>>>13,Pi=m[1]|0,ye=Pi&8191,be=Pi>>>13,$i=m[2]|0,_e=$i&8191,Ee=$i>>>13,Oi=m[3]|0,Se=Oi&8191,Me=Oi>>>13,Bi=m[4]|0,ke=Bi&8191,Re=Bi>>>13,Di=m[5]|0,Ie=Di&8191,Ce=Di>>>13,ji=m[6]|0,Ae=ji&8191,Ne=ji>>>13,Fi=m[7]|0,Le=Fi&8191,xe=Fi>>>13,Hi=m[8]|0,Te=Hi&8191,Pe=Hi>>>13,Ui=m[9]|0,$e=Ui&8191,Oe=Ui>>>13;f.negative=o.negative^l.negative,f.length=19,p=Math.imul(I,ve),a=Math.imul(I,we),a=a+Math.imul($,ve)|0,v=Math.imul($,we);var Xn=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(Xn>>>26)|0,Xn&=67108863,p=Math.imul(G,ve),a=Math.imul(G,we),a=a+Math.imul(Z,ve)|0,v=Math.imul(Z,we),p=p+Math.imul(I,ye)|0,a=a+Math.imul(I,be)|0,a=a+Math.imul($,ye)|0,v=v+Math.imul($,be)|0;var Yn=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(Yn>>>26)|0,Yn&=67108863,p=Math.imul(te,ve),a=Math.imul(te,we),a=a+Math.imul(re,ve)|0,v=Math.imul(re,we),p=p+Math.imul(G,ye)|0,a=a+Math.imul(G,be)|0,a=a+Math.imul(Z,ye)|0,v=v+Math.imul(Z,be)|0,p=p+Math.imul(I,_e)|0,a=a+Math.imul(I,Ee)|0,a=a+Math.imul($,_e)|0,v=v+Math.imul($,Ee)|0;var es=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(es>>>26)|0,es&=67108863,p=Math.imul(ne,ve),a=Math.imul(ne,we),a=a+Math.imul(se,ve)|0,v=Math.imul(se,we),p=p+Math.imul(te,ye)|0,a=a+Math.imul(te,be)|0,a=a+Math.imul(re,ye)|0,v=v+Math.imul(re,be)|0,p=p+Math.imul(G,_e)|0,a=a+Math.imul(G,Ee)|0,a=a+Math.imul(Z,_e)|0,v=v+Math.imul(Z,Ee)|0,p=p+Math.imul(I,Se)|0,a=a+Math.imul(I,Me)|0,a=a+Math.imul($,Se)|0,v=v+Math.imul($,Me)|0;var ts=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(ts>>>26)|0,ts&=67108863,p=Math.imul(ie,ve),a=Math.imul(ie,we),a=a+Math.imul(oe,ve)|0,v=Math.imul(oe,we),p=p+Math.imul(ne,ye)|0,a=a+Math.imul(ne,be)|0,a=a+Math.imul(se,ye)|0,v=v+Math.imul(se,be)|0,p=p+Math.imul(te,_e)|0,a=a+Math.imul(te,Ee)|0,a=a+Math.imul(re,_e)|0,v=v+Math.imul(re,Ee)|0,p=p+Math.imul(G,Se)|0,a=a+Math.imul(G,Me)|0,a=a+Math.imul(Z,Se)|0,v=v+Math.imul(Z,Me)|0,p=p+Math.imul(I,ke)|0,a=a+Math.imul(I,Re)|0,a=a+Math.imul($,ke)|0,v=v+Math.imul($,Re)|0;var rs=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(rs>>>26)|0,rs&=67108863,p=Math.imul(ae,ve),a=Math.imul(ae,we),a=a+Math.imul(ce,ve)|0,v=Math.imul(ce,we),p=p+Math.imul(ie,ye)|0,a=a+Math.imul(ie,be)|0,a=a+Math.imul(oe,ye)|0,v=v+Math.imul(oe,be)|0,p=p+Math.imul(ne,_e)|0,a=a+Math.imul(ne,Ee)|0,a=a+Math.imul(se,_e)|0,v=v+Math.imul(se,Ee)|0,p=p+Math.imul(te,Se)|0,a=a+Math.imul(te,Me)|0,a=a+Math.imul(re,Se)|0,v=v+Math.imul(re,Me)|0,p=p+Math.imul(G,ke)|0,a=a+Math.imul(G,Re)|0,a=a+Math.imul(Z,ke)|0,v=v+Math.imul(Z,Re)|0,p=p+Math.imul(I,Ie)|0,a=a+Math.imul(I,Ce)|0,a=a+Math.imul($,Ie)|0,v=v+Math.imul($,Ce)|0;var ns=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(ns>>>26)|0,ns&=67108863,p=Math.imul(le,ve),a=Math.imul(le,we),a=a+Math.imul(ue,ve)|0,v=Math.imul(ue,we),p=p+Math.imul(ae,ye)|0,a=a+Math.imul(ae,be)|0,a=a+Math.imul(ce,ye)|0,v=v+Math.imul(ce,be)|0,p=p+Math.imul(ie,_e)|0,a=a+Math.imul(ie,Ee)|0,a=a+Math.imul(oe,_e)|0,v=v+Math.imul(oe,Ee)|0,p=p+Math.imul(ne,Se)|0,a=a+Math.imul(ne,Me)|0,a=a+Math.imul(se,Se)|0,v=v+Math.imul(se,Me)|0,p=p+Math.imul(te,ke)|0,a=a+Math.imul(te,Re)|0,a=a+Math.imul(re,ke)|0,v=v+Math.imul(re,Re)|0,p=p+Math.imul(G,Ie)|0,a=a+Math.imul(G,Ce)|0,a=a+Math.imul(Z,Ie)|0,v=v+Math.imul(Z,Ce)|0,p=p+Math.imul(I,Ae)|0,a=a+Math.imul(I,Ne)|0,a=a+Math.imul($,Ae)|0,v=v+Math.imul($,Ne)|0;var ss=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(ss>>>26)|0,ss&=67108863,p=Math.imul(de,ve),a=Math.imul(de,we),a=a+Math.imul(he,ve)|0,v=Math.imul(he,we),p=p+Math.imul(le,ye)|0,a=a+Math.imul(le,be)|0,a=a+Math.imul(ue,ye)|0,v=v+Math.imul(ue,be)|0,p=p+Math.imul(ae,_e)|0,a=a+Math.imul(ae,Ee)|0,a=a+Math.imul(ce,_e)|0,v=v+Math.imul(ce,Ee)|0,p=p+Math.imul(ie,Se)|0,a=a+Math.imul(ie,Me)|0,a=a+Math.imul(oe,Se)|0,v=v+Math.imul(oe,Me)|0,p=p+Math.imul(ne,ke)|0,a=a+Math.imul(ne,Re)|0,a=a+Math.imul(se,ke)|0,v=v+Math.imul(se,Re)|0,p=p+Math.imul(te,Ie)|0,a=a+Math.imul(te,Ce)|0,a=a+Math.imul(re,Ie)|0,v=v+Math.imul(re,Ce)|0,p=p+Math.imul(G,Ae)|0,a=a+Math.imul(G,Ne)|0,a=a+Math.imul(Z,Ae)|0,v=v+Math.imul(Z,Ne)|0,p=p+Math.imul(I,Le)|0,a=a+Math.imul(I,xe)|0,a=a+Math.imul($,Le)|0,v=v+Math.imul($,xe)|0;var is=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(is>>>26)|0,is&=67108863,p=Math.imul(fe,ve),a=Math.imul(fe,we),a=a+Math.imul(ge,ve)|0,v=Math.imul(ge,we),p=p+Math.imul(de,ye)|0,a=a+Math.imul(de,be)|0,a=a+Math.imul(he,ye)|0,v=v+Math.imul(he,be)|0,p=p+Math.imul(le,_e)|0,a=a+Math.imul(le,Ee)|0,a=a+Math.imul(ue,_e)|0,v=v+Math.imul(ue,Ee)|0,p=p+Math.imul(ae,Se)|0,a=a+Math.imul(ae,Me)|0,a=a+Math.imul(ce,Se)|0,v=v+Math.imul(ce,Me)|0,p=p+Math.imul(ie,ke)|0,a=a+Math.imul(ie,Re)|0,a=a+Math.imul(oe,ke)|0,v=v+Math.imul(oe,Re)|0,p=p+Math.imul(ne,Ie)|0,a=a+Math.imul(ne,Ce)|0,a=a+Math.imul(se,Ie)|0,v=v+Math.imul(se,Ce)|0,p=p+Math.imul(te,Ae)|0,a=a+Math.imul(te,Ne)|0,a=a+Math.imul(re,Ae)|0,v=v+Math.imul(re,Ne)|0,p=p+Math.imul(G,Le)|0,a=a+Math.imul(G,xe)|0,a=a+Math.imul(Z,Le)|0,v=v+Math.imul(Z,xe)|0,p=p+Math.imul(I,Te)|0,a=a+Math.imul(I,Pe)|0,a=a+Math.imul($,Te)|0,v=v+Math.imul($,Pe)|0;var os=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(os>>>26)|0,os&=67108863,p=Math.imul(pe,ve),a=Math.imul(pe,we),a=a+Math.imul(me,ve)|0,v=Math.imul(me,we),p=p+Math.imul(fe,ye)|0,a=a+Math.imul(fe,be)|0,a=a+Math.imul(ge,ye)|0,v=v+Math.imul(ge,be)|0,p=p+Math.imul(de,_e)|0,a=a+Math.imul(de,Ee)|0,a=a+Math.imul(he,_e)|0,v=v+Math.imul(he,Ee)|0,p=p+Math.imul(le,Se)|0,a=a+Math.imul(le,Me)|0,a=a+Math.imul(ue,Se)|0,v=v+Math.imul(ue,Me)|0,p=p+Math.imul(ae,ke)|0,a=a+Math.imul(ae,Re)|0,a=a+Math.imul(ce,ke)|0,v=v+Math.imul(ce,Re)|0,p=p+Math.imul(ie,Ie)|0,a=a+Math.imul(ie,Ce)|0,a=a+Math.imul(oe,Ie)|0,v=v+Math.imul(oe,Ce)|0,p=p+Math.imul(ne,Ae)|0,a=a+Math.imul(ne,Ne)|0,a=a+Math.imul(se,Ae)|0,v=v+Math.imul(se,Ne)|0,p=p+Math.imul(te,Le)|0,a=a+Math.imul(te,xe)|0,a=a+Math.imul(re,Le)|0,v=v+Math.imul(re,xe)|0,p=p+Math.imul(G,Te)|0,a=a+Math.imul(G,Pe)|0,a=a+Math.imul(Z,Te)|0,v=v+Math.imul(Z,Pe)|0,p=p+Math.imul(I,$e)|0,a=a+Math.imul(I,Oe)|0,a=a+Math.imul($,$e)|0,v=v+Math.imul($,Oe)|0;var as=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(as>>>26)|0,as&=67108863,p=Math.imul(pe,ye),a=Math.imul(pe,be),a=a+Math.imul(me,ye)|0,v=Math.imul(me,be),p=p+Math.imul(fe,_e)|0,a=a+Math.imul(fe,Ee)|0,a=a+Math.imul(ge,_e)|0,v=v+Math.imul(ge,Ee)|0,p=p+Math.imul(de,Se)|0,a=a+Math.imul(de,Me)|0,a=a+Math.imul(he,Se)|0,v=v+Math.imul(he,Me)|0,p=p+Math.imul(le,ke)|0,a=a+Math.imul(le,Re)|0,a=a+Math.imul(ue,ke)|0,v=v+Math.imul(ue,Re)|0,p=p+Math.imul(ae,Ie)|0,a=a+Math.imul(ae,Ce)|0,a=a+Math.imul(ce,Ie)|0,v=v+Math.imul(ce,Ce)|0,p=p+Math.imul(ie,Ae)|0,a=a+Math.imul(ie,Ne)|0,a=a+Math.imul(oe,Ae)|0,v=v+Math.imul(oe,Ne)|0,p=p+Math.imul(ne,Le)|0,a=a+Math.imul(ne,xe)|0,a=a+Math.imul(se,Le)|0,v=v+Math.imul(se,xe)|0,p=p+Math.imul(te,Te)|0,a=a+Math.imul(te,Pe)|0,a=a+Math.imul(re,Te)|0,v=v+Math.imul(re,Pe)|0,p=p+Math.imul(G,$e)|0,a=a+Math.imul(G,Oe)|0,a=a+Math.imul(Z,$e)|0,v=v+Math.imul(Z,Oe)|0;var cs=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(cs>>>26)|0,cs&=67108863,p=Math.imul(pe,_e),a=Math.imul(pe,Ee),a=a+Math.imul(me,_e)|0,v=Math.imul(me,Ee),p=p+Math.imul(fe,Se)|0,a=a+Math.imul(fe,Me)|0,a=a+Math.imul(ge,Se)|0,v=v+Math.imul(ge,Me)|0,p=p+Math.imul(de,ke)|0,a=a+Math.imul(de,Re)|0,a=a+Math.imul(he,ke)|0,v=v+Math.imul(he,Re)|0,p=p+Math.imul(le,Ie)|0,a=a+Math.imul(le,Ce)|0,a=a+Math.imul(ue,Ie)|0,v=v+Math.imul(ue,Ce)|0,p=p+Math.imul(ae,Ae)|0,a=a+Math.imul(ae,Ne)|0,a=a+Math.imul(ce,Ae)|0,v=v+Math.imul(ce,Ne)|0,p=p+Math.imul(ie,Le)|0,a=a+Math.imul(ie,xe)|0,a=a+Math.imul(oe,Le)|0,v=v+Math.imul(oe,xe)|0,p=p+Math.imul(ne,Te)|0,a=a+Math.imul(ne,Pe)|0,a=a+Math.imul(se,Te)|0,v=v+Math.imul(se,Pe)|0,p=p+Math.imul(te,$e)|0,a=a+Math.imul(te,Oe)|0,a=a+Math.imul(re,$e)|0,v=v+Math.imul(re,Oe)|0;var ls=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(ls>>>26)|0,ls&=67108863,p=Math.imul(pe,Se),a=Math.imul(pe,Me),a=a+Math.imul(me,Se)|0,v=Math.imul(me,Me),p=p+Math.imul(fe,ke)|0,a=a+Math.imul(fe,Re)|0,a=a+Math.imul(ge,ke)|0,v=v+Math.imul(ge,Re)|0,p=p+Math.imul(de,Ie)|0,a=a+Math.imul(de,Ce)|0,a=a+Math.imul(he,Ie)|0,v=v+Math.imul(he,Ce)|0,p=p+Math.imul(le,Ae)|0,a=a+Math.imul(le,Ne)|0,a=a+Math.imul(ue,Ae)|0,v=v+Math.imul(ue,Ne)|0,p=p+Math.imul(ae,Le)|0,a=a+Math.imul(ae,xe)|0,a=a+Math.imul(ce,Le)|0,v=v+Math.imul(ce,xe)|0,p=p+Math.imul(ie,Te)|0,a=a+Math.imul(ie,Pe)|0,a=a+Math.imul(oe,Te)|0,v=v+Math.imul(oe,Pe)|0,p=p+Math.imul(ne,$e)|0,a=a+Math.imul(ne,Oe)|0,a=a+Math.imul(se,$e)|0,v=v+Math.imul(se,Oe)|0;var us=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(us>>>26)|0,us&=67108863,p=Math.imul(pe,ke),a=Math.imul(pe,Re),a=a+Math.imul(me,ke)|0,v=Math.imul(me,Re),p=p+Math.imul(fe,Ie)|0,a=a+Math.imul(fe,Ce)|0,a=a+Math.imul(ge,Ie)|0,v=v+Math.imul(ge,Ce)|0,p=p+Math.imul(de,Ae)|0,a=a+Math.imul(de,Ne)|0,a=a+Math.imul(he,Ae)|0,v=v+Math.imul(he,Ne)|0,p=p+Math.imul(le,Le)|0,a=a+Math.imul(le,xe)|0,a=a+Math.imul(ue,Le)|0,v=v+Math.imul(ue,xe)|0,p=p+Math.imul(ae,Te)|0,a=a+Math.imul(ae,Pe)|0,a=a+Math.imul(ce,Te)|0,v=v+Math.imul(ce,Pe)|0,p=p+Math.imul(ie,$e)|0,a=a+Math.imul(ie,Oe)|0,a=a+Math.imul(oe,$e)|0,v=v+Math.imul(oe,Oe)|0;var ds=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(ds>>>26)|0,ds&=67108863,p=Math.imul(pe,Ie),a=Math.imul(pe,Ce),a=a+Math.imul(me,Ie)|0,v=Math.imul(me,Ce),p=p+Math.imul(fe,Ae)|0,a=a+Math.imul(fe,Ne)|0,a=a+Math.imul(ge,Ae)|0,v=v+Math.imul(ge,Ne)|0,p=p+Math.imul(de,Le)|0,a=a+Math.imul(de,xe)|0,a=a+Math.imul(he,Le)|0,v=v+Math.imul(he,xe)|0,p=p+Math.imul(le,Te)|0,a=a+Math.imul(le,Pe)|0,a=a+Math.imul(ue,Te)|0,v=v+Math.imul(ue,Pe)|0,p=p+Math.imul(ae,$e)|0,a=a+Math.imul(ae,Oe)|0,a=a+Math.imul(ce,$e)|0,v=v+Math.imul(ce,Oe)|0;var hs=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(hs>>>26)|0,hs&=67108863,p=Math.imul(pe,Ae),a=Math.imul(pe,Ne),a=a+Math.imul(me,Ae)|0,v=Math.imul(me,Ne),p=p+Math.imul(fe,Le)|0,a=a+Math.imul(fe,xe)|0,a=a+Math.imul(ge,Le)|0,v=v+Math.imul(ge,xe)|0,p=p+Math.imul(de,Te)|0,a=a+Math.imul(de,Pe)|0,a=a+Math.imul(he,Te)|0,v=v+Math.imul(he,Pe)|0,p=p+Math.imul(le,$e)|0,a=a+Math.imul(le,Oe)|0,a=a+Math.imul(ue,$e)|0,v=v+Math.imul(ue,Oe)|0;var fs=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(fs>>>26)|0,fs&=67108863,p=Math.imul(pe,Le),a=Math.imul(pe,xe),a=a+Math.imul(me,Le)|0,v=Math.imul(me,xe),p=p+Math.imul(fe,Te)|0,a=a+Math.imul(fe,Pe)|0,a=a+Math.imul(ge,Te)|0,v=v+Math.imul(ge,Pe)|0,p=p+Math.imul(de,$e)|0,a=a+Math.imul(de,Oe)|0,a=a+Math.imul(he,$e)|0,v=v+Math.imul(he,Oe)|0;var gs=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(gs>>>26)|0,gs&=67108863,p=Math.imul(pe,Te),a=Math.imul(pe,Pe),a=a+Math.imul(me,Te)|0,v=Math.imul(me,Pe),p=p+Math.imul(fe,$e)|0,a=a+Math.imul(fe,Oe)|0,a=a+Math.imul(ge,$e)|0,v=v+Math.imul(ge,Oe)|0;var ps=(_+p|0)+((a&8191)<<13)|0;_=(v+(a>>>13)|0)+(ps>>>26)|0,ps&=67108863,p=Math.imul(pe,$e),a=Math.imul(pe,Oe),a=a+Math.imul(me,$e)|0,v=Math.imul(me,Oe);var ms=(_+p|0)+((a&8191)<<13)|0;return _=(v+(a>>>13)|0)+(ms>>>26)|0,ms&=67108863,w[0]=Xn,w[1]=Yn,w[2]=es,w[3]=ts,w[4]=rs,w[5]=ns,w[6]=ss,w[7]=is,w[8]=os,w[9]=as,w[10]=cs,w[11]=ls,w[12]=us,w[13]=ds,w[14]=hs,w[15]=fs,w[16]=gs,w[17]=ps,w[18]=ms,_!==0&&(w[19]=_,f.length++),f};Math.imul||(L=B);function R(b,o,l){l.negative=o.negative^b.negative,l.length=b.length+o.length;for(var f=0,g=0,m=0;m>>26)|0,g+=w>>>26,w&=67108863}l.words[m]=_,f=w,w=g}return f!==0?l.words[m]=f:l.length--,l._strip()}function z(b,o,l){return R(b,o,l)}s.prototype.mulTo=function(o,l){var f,g=this.length+o.length;return this.length===10&&o.length===10?f=L(this,o,l):g<63?f=B(this,o,l):g<1024?f=R(this,o,l):f=z(this,o,l),f},s.prototype.mul=function(o){var l=new s(null);return l.words=new Array(this.length+o.length),this.mulTo(o,l)},s.prototype.mulf=function(o){var l=new s(null);return l.words=new Array(this.length+o.length),z(this,o,l)},s.prototype.imul=function(o){return this.clone().mulTo(o,this)},s.prototype.imuln=function(o){var l=o<0;l&&(o=-o),n(typeof o=="number"),n(o<67108864);for(var f=0,g=0;g>=26,f+=m/67108864|0,f+=w>>>26,this.words[g]=w&67108863}return f!==0&&(this.words[g]=f,this.length++),l?this.ineg():this},s.prototype.muln=function(o){return this.clone().imuln(o)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(o){var l=O(o);if(l.length===0)return new s(1);for(var f=this,g=0;g=0);var l=o%26,f=(o-l)/26,g=67108863>>>26-l<<26-l,m;if(l!==0){var w=0;for(m=0;m>>26-l}w&&(this.words[m]=w,this.length++)}if(f!==0){for(m=this.length-1;m>=0;m--)this.words[m+f]=this.words[m];for(m=0;m=0);var g;l?g=(l-l%26)/26:g=0;var m=o%26,w=Math.min((o-m)/26,this.length),_=67108863^67108863>>>m<w)for(this.length-=w,a=0;a=0&&(v!==0||a>=g);a--){var N=this.words[a]|0;this.words[a]=v<<26-m|N>>>m,v=N&_}return p&&v!==0&&(p.words[p.length++]=v),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(o,l,f){return n(this.negative===0),this.iushrn(o,l,f)},s.prototype.shln=function(o){return this.clone().ishln(o)},s.prototype.ushln=function(o){return this.clone().iushln(o)},s.prototype.shrn=function(o){return this.clone().ishrn(o)},s.prototype.ushrn=function(o){return this.clone().iushrn(o)},s.prototype.testn=function(o){n(typeof o=="number"&&o>=0);var l=o%26,f=(o-l)/26,g=1<=0);var l=o%26,f=(o-l)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=f)return this;if(l!==0&&f++,this.length=Math.min(f,this.length),l!==0){var g=67108863^67108863>>>l<=67108864;l++)this.words[l]-=67108864,l===this.length-1?this.words[l+1]=1:this.words[l+1]++;return this.length=Math.max(this.length,l+1),this},s.prototype.isubn=function(o){if(n(typeof o=="number"),n(o<67108864),o<0)return this.iaddn(-o);if(this.negative!==0)return this.negative=0,this.iaddn(o),this.negative=1,this;if(this.words[0]-=o,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var l=0;l>26)-(p/67108864|0),this.words[m+f]=w&67108863}for(;m>26,this.words[m+f]=w&67108863;if(_===0)return this._strip();for(n(_===-1),_=0,m=0;m>26,this.words[m]=w&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(o,l){var f=this.length-o.length,g=this.clone(),m=o,w=m.words[m.length-1]|0,_=this._countBits(w);f=26-_,f!==0&&(m=m.ushln(f),g.iushln(f),w=m.words[m.length-1]|0);var p=g.length-m.length,a;if(l!=="mod"){a=new s(null),a.length=p+1,a.words=new Array(a.length);for(var v=0;v=0;I--){var $=(g.words[m.length+I]|0)*67108864+(g.words[m.length+I-1]|0);for($=Math.min($/w|0,67108863),g._ishlnsubmul(m,$,I);g.negative!==0;)$--,g.negative=0,g._ishlnsubmul(m,1,I),g.isZero()||(g.negative^=1);a&&(a.words[I]=$)}return a&&a._strip(),g._strip(),l!=="div"&&f!==0&&g.iushrn(f),{div:a||null,mod:g}},s.prototype.divmod=function(o,l,f){if(n(!o.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var g,m,w;return this.negative!==0&&o.negative===0?(w=this.neg().divmod(o,l),l!=="mod"&&(g=w.div.neg()),l!=="div"&&(m=w.mod.neg(),f&&m.negative!==0&&m.iadd(o)),{div:g,mod:m}):this.negative===0&&o.negative!==0?(w=this.divmod(o.neg(),l),l!=="mod"&&(g=w.div.neg()),{div:g,mod:w.mod}):this.negative&o.negative?(w=this.neg().divmod(o.neg(),l),l!=="div"&&(m=w.mod.neg(),f&&m.negative!==0&&m.isub(o)),{div:w.div,mod:m}):o.length>this.length||this.cmp(o)<0?{div:new s(0),mod:this}:o.length===1?l==="div"?{div:this.divn(o.words[0]),mod:null}:l==="mod"?{div:null,mod:new s(this.modrn(o.words[0]))}:{div:this.divn(o.words[0]),mod:new s(this.modrn(o.words[0]))}:this._wordDiv(o,l)},s.prototype.div=function(o){return this.divmod(o,"div",!1).div},s.prototype.mod=function(o){return this.divmod(o,"mod",!1).mod},s.prototype.umod=function(o){return this.divmod(o,"mod",!0).mod},s.prototype.divRound=function(o){var l=this.divmod(o);if(l.mod.isZero())return l.div;var f=l.div.negative!==0?l.mod.isub(o):l.mod,g=o.ushrn(1),m=o.andln(1),w=f.cmp(g);return w<0||m===1&&w===0?l.div:l.div.negative!==0?l.div.isubn(1):l.div.iaddn(1)},s.prototype.modrn=function(o){var l=o<0;l&&(o=-o),n(o<=67108863);for(var f=(1<<26)%o,g=0,m=this.length-1;m>=0;m--)g=(f*g+(this.words[m]|0))%o;return l?-g:g},s.prototype.modn=function(o){return this.modrn(o)},s.prototype.idivn=function(o){var l=o<0;l&&(o=-o),n(o<=67108863);for(var f=0,g=this.length-1;g>=0;g--){var m=(this.words[g]|0)+f*67108864;this.words[g]=m/o|0,f=m%o}return this._strip(),l?this.ineg():this},s.prototype.divn=function(o){return this.clone().idivn(o)},s.prototype.egcd=function(o){n(o.negative===0),n(!o.isZero());var l=this,f=o.clone();l.negative!==0?l=l.umod(o):l=l.clone();for(var g=new s(1),m=new s(0),w=new s(0),_=new s(1),p=0;l.isEven()&&f.isEven();)l.iushrn(1),f.iushrn(1),++p;for(var a=f.clone(),v=l.clone();!l.isZero();){for(var N=0,I=1;!(l.words[0]&I)&&N<26;++N,I<<=1);if(N>0)for(l.iushrn(N);N-- >0;)(g.isOdd()||m.isOdd())&&(g.iadd(a),m.isub(v)),g.iushrn(1),m.iushrn(1);for(var $=0,ze=1;!(f.words[0]&ze)&&$<26;++$,ze<<=1);if($>0)for(f.iushrn($);$-- >0;)(w.isOdd()||_.isOdd())&&(w.iadd(a),_.isub(v)),w.iushrn(1),_.iushrn(1);l.cmp(f)>=0?(l.isub(f),g.isub(w),m.isub(_)):(f.isub(l),w.isub(g),_.isub(m))}return{a:w,b:_,gcd:f.iushln(p)}},s.prototype._invmp=function(o){n(o.negative===0),n(!o.isZero());var l=this,f=o.clone();l.negative!==0?l=l.umod(o):l=l.clone();for(var g=new s(1),m=new s(0),w=f.clone();l.cmpn(1)>0&&f.cmpn(1)>0;){for(var _=0,p=1;!(l.words[0]&p)&&_<26;++_,p<<=1);if(_>0)for(l.iushrn(_);_-- >0;)g.isOdd()&&g.iadd(w),g.iushrn(1);for(var a=0,v=1;!(f.words[0]&v)&&a<26;++a,v<<=1);if(a>0)for(f.iushrn(a);a-- >0;)m.isOdd()&&m.iadd(w),m.iushrn(1);l.cmp(f)>=0?(l.isub(f),g.isub(m)):(f.isub(l),m.isub(g))}var N;return l.cmpn(1)===0?N=g:N=m,N.cmpn(0)<0&&N.iadd(o),N},s.prototype.gcd=function(o){if(this.isZero())return o.abs();if(o.isZero())return this.abs();var l=this.clone(),f=o.clone();l.negative=0,f.negative=0;for(var g=0;l.isEven()&&f.isEven();g++)l.iushrn(1),f.iushrn(1);do{for(;l.isEven();)l.iushrn(1);for(;f.isEven();)f.iushrn(1);var m=l.cmp(f);if(m<0){var w=l;l=f,f=w}else if(m===0||f.cmpn(1)===0)break;l.isub(f)}while(!0);return f.iushln(g)},s.prototype.invm=function(o){return this.egcd(o).a.umod(o)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(o){return this.words[0]&o},s.prototype.bincn=function(o){n(typeof o=="number");var l=o%26,f=(o-l)/26,g=1<>>26,_&=67108863,this.words[w]=_}return m!==0&&(this.words[w]=m,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(o){var l=o<0;if(this.negative!==0&&!l)return-1;if(this.negative===0&&l)return 1;this._strip();var f;if(this.length>1)f=1;else{l&&(o=-o),n(o<=67108863,"Number is too big");var g=this.words[0]|0;f=g===o?0:go.length)return 1;if(this.length=0;f--){var g=this.words[f]|0,m=o.words[f]|0;if(g!==m){gm&&(l=1);break}}return l},s.prototype.gtn=function(o){return this.cmpn(o)===1},s.prototype.gt=function(o){return this.cmp(o)===1},s.prototype.gten=function(o){return this.cmpn(o)>=0},s.prototype.gte=function(o){return this.cmp(o)>=0},s.prototype.ltn=function(o){return this.cmpn(o)===-1},s.prototype.lt=function(o){return this.cmp(o)===-1},s.prototype.lten=function(o){return this.cmpn(o)<=0},s.prototype.lte=function(o){return this.cmp(o)<=0},s.prototype.eqn=function(o){return this.cmpn(o)===0},s.prototype.eq=function(o){return this.cmp(o)===0},s.red=function(o){return new H(o)},s.prototype.toRed=function(o){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),o.convertTo(this)._forceRed(o)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(o){return this.red=o,this},s.prototype.forceRed=function(o){return n(!this.red,"Already a number in reduction context"),this._forceRed(o)},s.prototype.redAdd=function(o){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,o)},s.prototype.redIAdd=function(o){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,o)},s.prototype.redSub=function(o){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,o)},s.prototype.redISub=function(o){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,o)},s.prototype.redShl=function(o){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,o)},s.prototype.redMul=function(o){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,o),this.red.mul(this,o)},s.prototype.redIMul=function(o){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,o),this.red.imul(this,o)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(o){return n(this.red&&!o.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,o)};var C={k256:null,p224:null,p192:null,p25519:null};function P(b,o){this.name=b,this.p=new s(o,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}P.prototype._tmp=function(){var o=new s(null);return o.words=new Array(Math.ceil(this.n/13)),o},P.prototype.ireduce=function(o){var l=o,f;do this.split(l,this.tmp),l=this.imulK(l),l=l.iadd(this.tmp),f=l.bitLength();while(f>this.n);var g=f0?l.isub(this.p):l.strip!==void 0?l.strip():l._strip(),l},P.prototype.split=function(o,l){o.iushrn(this.n,0,l)},P.prototype.imulK=function(o){return o.imul(this.k)};function J(){P.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(J,P),J.prototype.split=function(o,l){for(var f=4194303,g=Math.min(o.length,9),m=0;m>>22,w=_}w>>>=22,o.words[m-10]=w,w===0&&o.length>10?o.length-=10:o.length-=9},J.prototype.imulK=function(o){o.words[o.length]=0,o.words[o.length+1]=0,o.length+=2;for(var l=0,f=0;f>>=26,o.words[f]=m,l=g}return l!==0&&(o.words[o.length++]=l),o},s._prime=function(o){if(C[o])return C[o];var l;if(o==="k256")l=new J;else if(o==="p224")l=new We;else if(o==="p192")l=new Qe;else if(o==="p25519")l=new Y;else throw new Error("Unknown prime "+o);return C[o]=l,l};function H(b){if(typeof b=="string"){var o=s._prime(b);this.m=o.p,this.prime=o}else n(b.gtn(1),"modulus must be greater than 1"),this.m=b,this.prime=null}H.prototype._verify1=function(o){n(o.negative===0,"red works only with positives"),n(o.red,"red works only with red numbers")},H.prototype._verify2=function(o,l){n((o.negative|l.negative)===0,"red works only with positives"),n(o.red&&o.red===l.red,"red works only with red numbers")},H.prototype.imod=function(o){return this.prime?this.prime.ireduce(o)._forceRed(this):(y(o,o.umod(this.m)._forceRed(this)),o)},H.prototype.neg=function(o){return o.isZero()?o.clone():this.m.sub(o)._forceRed(this)},H.prototype.add=function(o,l){this._verify2(o,l);var f=o.add(l);return f.cmp(this.m)>=0&&f.isub(this.m),f._forceRed(this)},H.prototype.iadd=function(o,l){this._verify2(o,l);var f=o.iadd(l);return f.cmp(this.m)>=0&&f.isub(this.m),f},H.prototype.sub=function(o,l){this._verify2(o,l);var f=o.sub(l);return f.cmpn(0)<0&&f.iadd(this.m),f._forceRed(this)},H.prototype.isub=function(o,l){this._verify2(o,l);var f=o.isub(l);return f.cmpn(0)<0&&f.iadd(this.m),f},H.prototype.shl=function(o,l){return this._verify1(o),this.imod(o.ushln(l))},H.prototype.imul=function(o,l){return this._verify2(o,l),this.imod(o.imul(l))},H.prototype.mul=function(o,l){return this._verify2(o,l),this.imod(o.mul(l))},H.prototype.isqr=function(o){return this.imul(o,o.clone())},H.prototype.sqr=function(o){return this.mul(o,o)},H.prototype.sqrt=function(o){if(o.isZero())return o.clone();var l=this.m.andln(3);if(n(l%2===1),l===3){var f=this.m.add(new s(1)).iushrn(2);return this.pow(o,f)}for(var g=this.m.subn(1),m=0;!g.isZero()&&g.andln(1)===0;)m++,g.iushrn(1);n(!g.isZero());var w=new s(1).toRed(this),_=w.redNeg(),p=this.m.subn(1).iushrn(1),a=this.m.bitLength();for(a=new s(2*a*a).toRed(this);this.pow(a,p).cmp(_)!==0;)a.redIAdd(_);for(var v=this.pow(a,g),N=this.pow(o,g.addn(1).iushrn(1)),I=this.pow(o,g),$=m;I.cmp(w)!==0;){for(var ze=I,G=0;ze.cmp(w)!==0;G++)ze=ze.redSqr();n(G<$);var Z=this.pow(v,new s(1).iushln($-G-1));N=N.redMul(Z),v=Z.redSqr(),I=I.redMul(v),$=G}return N},H.prototype.invm=function(o){var l=o._invmp(this.m);return l.negative!==0?(l.negative=0,this.imod(l).redNeg()):this.imod(l)},H.prototype.pow=function(o,l){if(l.isZero())return new s(1).toRed(this);if(l.cmpn(1)===0)return o.clone();var f=4,g=new Array(1<=0;m--){for(var v=l.words[m],N=a-1;N>=0;N--){var I=v>>N&1;if(w!==g[0]&&(w=this.sqr(w)),I===0&&_===0){p=0;continue}_<<=1,_|=I,p++,!(p!==f&&(m!==0||N!==0))&&(w=this.mul(w,g[_]),p=0,_=0)}a=26}return w},H.prototype.convertTo=function(o){var l=o.umod(this.m);return l===o?l.clone():l},H.prototype.convertFrom=function(o){var l=o.clone();return l.red=null,l},s.mont=function(o){return new q(o)};function q(b){H.call(this,b),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new s(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(q,H),q.prototype.convertTo=function(o){return this.imod(o.ushln(this.shift))},q.prototype.convertFrom=function(o){var l=this.imod(o.mul(this.rinv));return l.red=null,l},q.prototype.imul=function(o,l){if(o.isZero()||l.isZero())return o.words[0]=0,o.length=1,o;var f=o.imul(l),g=f.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),m=f.isub(g).iushrn(this.shift),w=m;return m.cmp(this.m)>=0?w=m.isub(this.m):m.cmpn(0)<0&&(w=m.iadd(this.m)),w._forceRed(this)},q.prototype.mul=function(o,l){if(o.isZero()||l.isZero())return new s(0)._forceRed(this);var f=o.mul(l),g=f.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),m=f.isub(g).iushrn(this.shift),w=m;return m.cmp(this.m)>=0?w=m.isub(this.m):m.cmpn(0)<0&&(w=m.iadd(this.m)),w._forceRed(this)},q.prototype.invm=function(o){var l=this.imod(o._invmp(this.m).mul(this.r2));return l._forceRed(this)}})(t,x)})(Us);var un=Us.exports,Sr={},St={};Object.defineProperty(St,"__esModule",{value:!0});St.errorValues=St.standardErrorCodes=void 0;St.standardErrorCodes={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}};St.errorValues={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}};var dn={},hn={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.serialize=t.getErrorCode=t.isValidCode=t.getMessageFromCode=t.JSON_RPC_SERVER_ERROR_MESSAGE=void 0;const e=St,r="Unspecified error message.";t.JSON_RPC_SERVER_ERROR_MESSAGE="Unspecified server error.";function n(E,M=r){if(E&&Number.isInteger(E)){const k=E.toString();if(y(e.errorValues,k))return e.errorValues[k].message;if(d(E))return t.JSON_RPC_SERVER_ERROR_MESSAGE}return M}t.getMessageFromCode=n;function i(E){if(!Number.isInteger(E))return!1;const M=E.toString();return!!(e.errorValues[M]||d(E))}t.isValidCode=i;function s(E){var M;if(typeof E=="number")return E;if(c(E))return(M=E.code)!==null&&M!==void 0?M:E.errorCode}t.getErrorCode=s;function c(E){return typeof E=="object"&&E!==null&&(typeof E.code=="number"||typeof E.errorCode=="number")}function u(E,{shouldIncludeStack:M=!1}={}){const k={};if(E&&typeof E=="object"&&!Array.isArray(E)&&y(E,"code")&&i(E.code)){const T=E;k.code=T.code,T.message&&typeof T.message=="string"?(k.message=T.message,y(T,"data")&&(k.data=T.data)):(k.message=n(k.code),k.data={originalError:h(E)})}else k.code=e.standardErrorCodes.rpc.internal,k.message=S(E,"message")?E.message:r,k.data={originalError:h(E)};return M&&(k.stack=S(E,"stack")?E.stack:void 0),k}t.serialize=u;function d(E){return E>=-32099&&E<=-32e3}function h(E){return E&&typeof E=="object"&&!Array.isArray(E)?Object.assign({},E):E}function y(E,M){return Object.prototype.hasOwnProperty.call(E,M)}function S(E,M){return typeof E=="object"&&E!==null&&M in E&&typeof E[M]=="string"}})(hn);Object.defineProperty(dn,"__esModule",{value:!0});dn.standardErrors=void 0;const He=St,na=hn;dn.standardErrors={rpc:{parse:t=>rt(He.standardErrorCodes.rpc.parse,t),invalidRequest:t=>rt(He.standardErrorCodes.rpc.invalidRequest,t),invalidParams:t=>rt(He.standardErrorCodes.rpc.invalidParams,t),methodNotFound:t=>rt(He.standardErrorCodes.rpc.methodNotFound,t),internal:t=>rt(He.standardErrorCodes.rpc.internal,t),server:t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:e}=t;if(!Number.isInteger(e)||e>-32005||e<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return rt(e,t)},invalidInput:t=>rt(He.standardErrorCodes.rpc.invalidInput,t),resourceNotFound:t=>rt(He.standardErrorCodes.rpc.resourceNotFound,t),resourceUnavailable:t=>rt(He.standardErrorCodes.rpc.resourceUnavailable,t),transactionRejected:t=>rt(He.standardErrorCodes.rpc.transactionRejected,t),methodNotSupported:t=>rt(He.standardErrorCodes.rpc.methodNotSupported,t),limitExceeded:t=>rt(He.standardErrorCodes.rpc.limitExceeded,t)},provider:{userRejectedRequest:t=>Wt(He.standardErrorCodes.provider.userRejectedRequest,t),unauthorized:t=>Wt(He.standardErrorCodes.provider.unauthorized,t),unsupportedMethod:t=>Wt(He.standardErrorCodes.provider.unsupportedMethod,t),disconnected:t=>Wt(He.standardErrorCodes.provider.disconnected,t),chainDisconnected:t=>Wt(He.standardErrorCodes.provider.chainDisconnected,t),unsupportedChain:t=>Wt(He.standardErrorCodes.provider.unsupportedChain,t),custom:t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:e,message:r,data:n}=t;if(!r||typeof r!="string")throw new Error('"message" must be a nonempty string');return new oa(e,r,n)}}};function rt(t,e){const[r,n]=sa(e);return new ia(t,r||(0,na.getMessageFromCode)(t),n)}function Wt(t,e){const[r,n]=sa(e);return new oa(t,r||(0,na.getMessageFromCode)(t),n)}function sa(t){if(t){if(typeof t=="string")return[t];if(typeof t=="object"&&!Array.isArray(t)){const{message:e,data:r}=t;if(e&&typeof e!="string")throw new Error("Must specify string message.");return[e||void 0,r]}}return[]}let ia=class extends Error{constructor(e,r,n){if(!Number.isInteger(e))throw new Error('"code" must be an integer.');if(!r||typeof r!="string")throw new Error('"message" must be a nonempty string.');super(r),this.code=e,n!==void 0&&(this.data=n)}},oa=class extends ia{constructor(e,r,n){if(!Fc(e))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(e,r,n)}};function Fc(t){return Number.isInteger(t)&&t>=1e3&&t<=4999}var fn={},cr={};Object.defineProperty(cr,"__esModule",{value:!0});cr.isErrorResponse=void 0;function Hc(t){return t.errorMessage!==void 0}cr.isErrorResponse=Hc;var lr={};Object.defineProperty(lr,"__esModule",{value:!0});lr.LIB_VERSION=void 0;lr.LIB_VERSION="3.9.3";Object.defineProperty(fn,"__esModule",{value:!0});fn.serializeError=void 0;const Uc=cr,Vc=lr,Wc=St,zc=hn;function qc(t,e){const r=(0,zc.serialize)(Jc(t),{shouldIncludeStack:!0}),n=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");n.searchParams.set("version",Vc.LIB_VERSION),n.searchParams.set("code",r.code.toString());const i=Gc(r.data,e);return i&&n.searchParams.set("method",i),n.searchParams.set("message",r.message),Object.assign(Object.assign({},r),{docUrl:n.href})}fn.serializeError=qc;function Jc(t){return typeof t=="string"?{message:t,code:Wc.standardErrorCodes.rpc.internal}:(0,Uc.isErrorResponse)(t)?Object.assign(Object.assign({},t),{message:t.errorMessage,code:t.errorCode,data:{method:t.method}}):t}function Gc(t,e){const r=t==null?void 0:t.method;if(r)return r;if(e!==void 0){if(typeof e=="string")return e;if(Array.isArray(e)){if(e.length>0)return e[0].method}else return e.method}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.standardErrors=t.standardErrorCodes=t.serializeError=t.getMessageFromCode=t.getErrorCode=void 0;const e=St;Object.defineProperty(t,"standardErrorCodes",{enumerable:!0,get:function(){return e.standardErrorCodes}});const r=dn;Object.defineProperty(t,"standardErrors",{enumerable:!0,get:function(){return r.standardErrors}});const n=fn;Object.defineProperty(t,"serializeError",{enumerable:!0,get:function(){return n.serializeError}});const i=hn;Object.defineProperty(t,"getErrorCode",{enumerable:!0,get:function(){return i.getErrorCode}}),Object.defineProperty(t,"getMessageFromCode",{enumerable:!0,get:function(){return i.getMessageFromCode}})})(Sr);var De={};Object.defineProperty(De,"__esModule",{value:!0});De.ProviderType=De.RegExpString=De.IntNumber=De.BigIntString=De.AddressString=De.HexString=De.OpaqueType=void 0;function Mr(){return t=>t}De.OpaqueType=Mr;De.HexString=Mr();De.AddressString=Mr();De.BigIntString=Mr();function Zc(t){return Math.floor(t)}De.IntNumber=Zc;De.RegExpString=Mr();var Vi;(function(t){t.CoinbaseWallet="CoinbaseWallet",t.MetaMask="MetaMask",t.Unselected=""})(Vi||(De.ProviderType=Vi={}));var Qc=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(A,"__esModule",{value:!0});A.isMobileWeb=A.getLocation=A.isInIFrame=A.createQrUrl=A.getFavicon=A.range=A.isBigNumber=A.ensureParsedJSONObject=A.ensureBN=A.ensureRegExpString=A.ensureIntNumber=A.ensureBuffer=A.ensureAddressString=A.ensureEvenLengthHexString=A.ensureHexString=A.isHexString=A.prepend0x=A.strip0x=A.has0xPrefix=A.hexStringFromIntNumber=A.intNumberFromHexString=A.bigIntStringFromBN=A.hexStringFromBuffer=A.hexStringToUint8Array=A.uint8ArrayToHex=A.randomBytesHex=void 0;const Rt=Qc(un),Ht=Sr,ot=De,aa=/^[0-9]*$/,ca=/^[a-f0-9]*$/;function Kc(t){return la(crypto.getRandomValues(new Uint8Array(t)))}A.randomBytesHex=Kc;function la(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}A.uint8ArrayToHex=la;function Xc(t){return new Uint8Array(t.match(/.{1,2}/g).map(e=>parseInt(e,16)))}A.hexStringToUint8Array=Xc;function Yc(t,e=!1){const r=t.toString("hex");return(0,ot.HexString)(e?`0x${r}`:r)}A.hexStringFromBuffer=Yc;function el(t){return(0,ot.BigIntString)(t.toString(10))}A.bigIntStringFromBN=el;function tl(t){return(0,ot.IntNumber)(new Rt.default(Rr(t,!1),16).toNumber())}A.intNumberFromHexString=tl;function rl(t){return(0,ot.HexString)(`0x${new Rt.default(t).toString(16)}`)}A.hexStringFromIntNumber=rl;function Vs(t){return t.startsWith("0x")||t.startsWith("0X")}A.has0xPrefix=Vs;function gn(t){return Vs(t)?t.slice(2):t}A.strip0x=gn;function ua(t){return Vs(t)?`0x${t.slice(2)}`:`0x${t}`}A.prepend0x=ua;function kr(t){if(typeof t!="string")return!1;const e=gn(t).toLowerCase();return ca.test(e)}A.isHexString=kr;function da(t,e=!1){if(typeof t=="string"){const r=gn(t).toLowerCase();if(ca.test(r))return(0,ot.HexString)(e?`0x${r}`:r)}throw Ht.standardErrors.rpc.invalidParams(`"${String(t)}" is not a hexadecimal string`)}A.ensureHexString=da;function Rr(t,e=!1){let r=da(t,!1);return r.length%2===1&&(r=(0,ot.HexString)(`0${r}`)),e?(0,ot.HexString)(`0x${r}`):r}A.ensureEvenLengthHexString=Rr;function nl(t){if(typeof t=="string"){const e=gn(t).toLowerCase();if(kr(e)&&e.length===40)return(0,ot.AddressString)(ua(e))}throw Ht.standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(t)}`)}A.ensureAddressString=nl;function sl(t){if(Buffer.isBuffer(t))return t;if(typeof t=="string"){if(kr(t)){const e=Rr(t,!1);return Buffer.from(e,"hex")}return Buffer.from(t,"utf8")}throw Ht.standardErrors.rpc.invalidParams(`Not binary data: ${String(t)}`)}A.ensureBuffer=sl;function ha(t){if(typeof t=="number"&&Number.isInteger(t))return(0,ot.IntNumber)(t);if(typeof t=="string"){if(aa.test(t))return(0,ot.IntNumber)(Number(t));if(kr(t))return(0,ot.IntNumber)(new Rt.default(Rr(t,!1),16).toNumber())}throw Ht.standardErrors.rpc.invalidParams(`Not an integer: ${String(t)}`)}A.ensureIntNumber=ha;function il(t){if(t instanceof RegExp)return(0,ot.RegExpString)(t.toString());throw Ht.standardErrors.rpc.invalidParams(`Not a RegExp: ${String(t)}`)}A.ensureRegExpString=il;function ol(t){if(t!==null&&(Rt.default.isBN(t)||fa(t)))return new Rt.default(t.toString(10),10);if(typeof t=="number")return new Rt.default(ha(t));if(typeof t=="string"){if(aa.test(t))return new Rt.default(t,10);if(kr(t))return new Rt.default(Rr(t,!1),16)}throw Ht.standardErrors.rpc.invalidParams(`Not an integer: ${String(t)}`)}A.ensureBN=ol;function al(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw Ht.standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(t)}`)}A.ensureParsedJSONObject=al;function fa(t){if(t==null||typeof t.constructor!="function")return!1;const{constructor:e}=t;return typeof e.config=="function"&&typeof e.EUCLID=="number"}A.isBigNumber=fa;function cl(t,e){return Array.from({length:e-t},(r,n)=>t+n)}A.range=cl;function ll(){const t=document.querySelector('link[sizes="192x192"]')||document.querySelector('link[sizes="180x180"]')||document.querySelector('link[rel="icon"]')||document.querySelector('link[rel="shortcut icon"]'),{protocol:e,host:r}=document.location,n=t?t.getAttribute("href"):null;return!n||n.startsWith("javascript:")||n.startsWith("vbscript:")?null:n.startsWith("http://")||n.startsWith("https://")||n.startsWith("data:")?n:n.startsWith("//")?e+n:`${e}//${r}${n}`}A.getFavicon=ll;function ul(t,e,r,n,i,s){const c=n?"parent-id":"id",u=new URLSearchParams({[c]:t,secret:e,server:r,v:i,chainId:s.toString()}).toString();return`${r}/#/link?${u}`}A.createQrUrl=ul;function ga(){try{return window.frameElement!==null}catch{return!1}}A.isInIFrame=ga;function dl(){try{return ga()&&window.top?window.top.location:window.location}catch{return window.location}}A.getLocation=dl;function hl(){var t;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((t=window==null?void 0:window.navigator)===null||t===void 0?void 0:t.userAgent)}A.isMobileWeb=hl;var pn={};Object.defineProperty(pn,"__esModule",{value:!0});pn.ScopedLocalStorage=void 0;class fl{constructor(e){this.scope=e}setItem(e,r){localStorage.setItem(this.scopedKey(e),r)}getItem(e){return localStorage.getItem(this.scopedKey(e))}removeItem(e){localStorage.removeItem(this.scopedKey(e))}clear(){const e=this.scopedKey(""),r=[];for(let n=0;nlocalStorage.removeItem(n))}scopedKey(e){return`${this.scope}:${e}`}}pn.ScopedLocalStorage=fl;var rr={},Ir={},Cr={},ur={};Object.defineProperty(ur,"__esModule",{value:!0});ur.EVENTS=void 0;ur.EVENTS={STARTED_CONNECTING:"walletlink_sdk.started.connecting",CONNECTED_STATE_CHANGE:"walletlink_sdk.connected",DISCONNECTED:"walletlink_sdk.disconnected",METADATA_DESTROYED:"walletlink_sdk_metadata_destroyed",LINKED:"walletlink_sdk.linked",FAILURE:"walletlink_sdk.generic_failure",SESSION_CONFIG_RECEIVED:"walletlink_sdk.session_config_event_received",ETH_ACCOUNTS_STATE:"walletlink_sdk.eth_accounts_state",SESSION_STATE_CHANGE:"walletlink_sdk.session_state_change",UNLINKED_ERROR_STATE:"walletlink_sdk.unlinked_error_state",SKIPPED_CLEARING_SESSION:"walletlink_sdk.skipped_clearing_session",GENERAL_ERROR:"walletlink_sdk.general_error",WEB3_REQUEST:"walletlink_sdk.web3.request",WEB3_REQUEST_PUBLISHED:"walletlink_sdk.web3.request_published",WEB3_RESPONSE:"walletlink_sdk.web3.response",METHOD_NOT_IMPLEMENTED:"walletlink_sdk.method_not_implemented",UNKNOWN_ADDRESS_ENCOUNTERED:"walletlink_sdk.unknown_address_encountered"};var it={};Object.defineProperty(it,"__esModule",{value:!0});it.RelayAbstract=it.APP_VERSION_KEY=it.LOCAL_STORAGE_ADDRESSES_KEY=it.WALLET_USER_NAME_KEY=void 0;const Wi=Sr;it.WALLET_USER_NAME_KEY="walletUsername";it.LOCAL_STORAGE_ADDRESSES_KEY="Addresses";it.APP_VERSION_KEY="AppVersion";class gl{async makeEthereumJSONRPCRequest(e,r){if(!r)throw new Error("Error: No jsonRpcUrl provided");return window.fetch(r,{method:"POST",body:JSON.stringify(e),mode:"cors",headers:{"Content-Type":"application/json"}}).then(n=>n.json()).then(n=>{if(!n)throw Wi.standardErrors.rpc.parse({});const i=n,{error:s}=i;if(s)throw(0,Wi.serializeError)(s,e.method);return i})}}it.RelayAbstract=gl;var dr={};Object.defineProperty(dr,"__esModule",{value:!0});dr.Session=void 0;const zi=Oc,qi=A,Ji="session:id",Gi="session:secret",Zi="session:linked";class Ws{constructor(e,r,n,i){this._storage=e,this._id=r||(0,qi.randomBytesHex)(16),this._secret=n||(0,qi.randomBytesHex)(32),this._key=new zi.sha256().update(`${this._id}, ${this._secret} WalletLink`).digest("hex"),this._linked=!!i}static load(e){const r=e.getItem(Ji),n=e.getItem(Zi),i=e.getItem(Gi);return r&&i?new Ws(e,r,i,n==="1"):null}static hash(e){return new zi.sha256().update(e).digest("hex")}get id(){return this._id}get secret(){return this._secret}get key(){return this._key}get linked(){return this._linked}set linked(e){this._linked=e,this.persistLinked()}save(){return this._storage.setItem(Ji,this._id),this._storage.setItem(Gi,this._secret),this.persistLinked(),this}persistLinked(){this._storage.setItem(Zi,this._linked?"1":"0")}}dr.Session=Ws;var mn={},vn={};Object.defineProperty(vn,"__esModule",{value:!0});vn.Cipher=void 0;const Wr=A;class pl{constructor(e){this.secret=e}async encrypt(e){const r=this.secret;if(r.length!==64)throw Error("secret must be 256 bits");const n=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.importKey("raw",(0,Wr.hexStringToUint8Array)(r),{name:"aes-gcm"},!1,["encrypt","decrypt"]),s=new TextEncoder,c=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},i,s.encode(e)),u=16,d=c.slice(c.byteLength-u),h=c.slice(0,c.byteLength-u),y=new Uint8Array(d),S=new Uint8Array(h),E=new Uint8Array([...n,...y,...S]);return(0,Wr.uint8ArrayToHex)(E)}async decrypt(e){const r=this.secret;if(r.length!==64)throw Error("secret must be 256 bits");return new Promise((n,i)=>{(async function(){const s=await crypto.subtle.importKey("raw",(0,Wr.hexStringToUint8Array)(r),{name:"aes-gcm"},!1,["encrypt","decrypt"]),c=(0,Wr.hexStringToUint8Array)(e),u=c.slice(0,12),d=c.slice(12,28),h=c.slice(28),y=new Uint8Array([...h,...d]),S={name:"AES-GCM",iv:new Uint8Array(u)};try{const E=await window.crypto.subtle.decrypt(S,s,y),M=new TextDecoder;n(M.decode(E))}catch(E){i(E)}})()})}}vn.Cipher=pl;var wn={};Object.defineProperty(wn,"__esModule",{value:!0});wn.WalletLinkHTTP=void 0;class ml{constructor(e,r,n){this.linkAPIUrl=e,this.sessionId=r;const i=`${r}:${n}`;this.auth=`Basic ${btoa(i)}`}async markUnseenEventsAsSeen(e){return Promise.all(e.map(r=>fetch(`${this.linkAPIUrl}/events/${r.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(r=>console.error("Unabled to mark event as failed:",r))}async fetchUnseenEvents(){var e;const r=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(r.ok){const{events:n,error:i}=await r.json();if(i)throw new Error(`Check unseen events failed: ${i}`);const s=(e=n==null?void 0:n.filter(c=>c.event==="Web3Response").map(c=>({type:"Event",sessionId:this.sessionId,eventId:c.id,event:c.event,data:c.data})))!==null&&e!==void 0?e:[];return this.markUnseenEventsAsSeen(s),s}throw new Error(`Check unseen events failed: ${r.status}`)}}wn.WalletLinkHTTP=ml;var nr={};Object.defineProperty(nr,"__esModule",{value:!0});nr.WalletLinkWebSocket=nr.ConnectionState=void 0;var Kt;(function(t){t[t.DISCONNECTED=0]="DISCONNECTED",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED"})(Kt||(nr.ConnectionState=Kt={}));class vl{setConnectionStateListener(e){this.connectionStateListener=e}setIncomingDataListener(e){this.incomingDataListener=e}constructor(e,r=WebSocket){this.WebSocketClass=r,this.webSocket=null,this.pendingData=[],this.url=e.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");return new Promise((e,r)=>{var n;let i;try{this.webSocket=i=new this.WebSocketClass(this.url)}catch(s){r(s);return}(n=this.connectionStateListener)===null||n===void 0||n.call(this,Kt.CONNECTING),i.onclose=s=>{var c;this.clearWebSocket(),r(new Error(`websocket error ${s.code}: ${s.reason}`)),(c=this.connectionStateListener)===null||c===void 0||c.call(this,Kt.DISCONNECTED)},i.onopen=s=>{var c;e(),(c=this.connectionStateListener)===null||c===void 0||c.call(this,Kt.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(d=>this.sendData(d)),this.pendingData=[])},i.onmessage=s=>{var c,u;if(s.data==="h")(c=this.incomingDataListener)===null||c===void 0||c.call(this,{type:"Heartbeat"});else try{const d=JSON.parse(s.data);(u=this.incomingDataListener)===null||u===void 0||u.call(this,d)}catch{}}})}disconnect(){var e;const{webSocket:r}=this;if(r){this.clearWebSocket(),(e=this.connectionStateListener)===null||e===void 0||e.call(this,Kt.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{r.close()}catch{}}}sendData(e){const{webSocket:r}=this;if(!r){this.pendingData.push(e),this.connect();return}r.send(e)}clearWebSocket(){const{webSocket:e}=this;e&&(this.webSocket=null,e.onclose=null,e.onerror=null,e.onmessage=null,e.onopen=null)}}nr.WalletLinkWebSocket=vl;Object.defineProperty(mn,"__esModule",{value:!0});mn.WalletLinkConnection=void 0;const zt=De,wl=vn,ht=ur,Qi=it,qt=dr,yl=wn,zr=nr,Ki=1e4,bl=6e4;class _l{constructor({session:e,linkAPIUrl:r,listener:n,diagnostic:i,WebSocketClass:s=WebSocket}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=(0,zt.IntNumber)(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=u=>{if(!u)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",h=>u.JsonRpcUrl&&this.handleChainUpdated(h,u.JsonRpcUrl)]]).forEach((h,y)=>{const S=u[y];S!==void 0&&h(S)})},this.handleDestroyed=u=>{var d,h;u==="1"&&((d=this.listener)===null||d===void 0||d.resetAndReload(),(h=this.diagnostic)===null||h===void 0||h.log(ht.EVENTS.METADATA_DESTROYED,{alreadyDestroyed:this.isDestroyed,sessionIdHash:qt.Session.hash(this.session.id)}))},this.handleAccountUpdated=async u=>{var d,h;try{const y=await this.cipher.decrypt(u);(d=this.listener)===null||d===void 0||d.accountUpdated(y)}catch{(h=this.diagnostic)===null||h===void 0||h.log(ht.EVENTS.GENERAL_ERROR,{message:"Had error decrypting",value:"selectedAddress"})}},this.handleMetadataUpdated=async(u,d)=>{var h,y;try{const S=await this.cipher.decrypt(d);(h=this.listener)===null||h===void 0||h.metadataUpdated(u,S)}catch{(y=this.diagnostic)===null||y===void 0||y.log(ht.EVENTS.GENERAL_ERROR,{message:"Had error decrypting",value:u})}},this.handleWalletUsernameUpdated=async u=>{this.handleMetadataUpdated(Qi.WALLET_USER_NAME_KEY,u)},this.handleAppVersionUpdated=async u=>{this.handleMetadataUpdated(Qi.APP_VERSION_KEY,u)},this.handleChainUpdated=async(u,d)=>{var h,y;try{const S=await this.cipher.decrypt(u),E=await this.cipher.decrypt(d);(h=this.listener)===null||h===void 0||h.chainUpdated(S,E)}catch{(y=this.diagnostic)===null||y===void 0||y.log(ht.EVENTS.GENERAL_ERROR,{message:"Had error decrypting",value:"chainId|jsonRpcUrl"})}},this.session=e,this.cipher=new wl.Cipher(e.secret),this.diagnostic=i,this.listener=n;const c=new zr.WalletLinkWebSocket(`${r}/rpc`,s);c.setConnectionStateListener(async u=>{var d;(d=this.diagnostic)===null||d===void 0||d.log(ht.EVENTS.CONNECTED_STATE_CHANGE,{state:u,sessionIdHash:qt.Session.hash(e.id)});let h=!1;switch(u){case zr.ConnectionState.DISCONNECTED:if(!this.destroyed){const y=async()=>{await new Promise(S=>setTimeout(S,5e3)),this.destroyed||c.connect().catch(()=>{y()})};y()}break;case zr.ConnectionState.CONNECTED:try{await this.authenticate(),this.sendIsLinked(),this.sendGetSessionConfig(),h=!0}catch{}this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},Ki),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();break;case zr.ConnectionState.CONNECTING:break}this.connected!==h&&(this.connected=h)}),c.setIncomingDataListener(u=>{var d,h,y;switch(u.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const S=u.type==="IsLinkedOK"?u.linked:void 0;(d=this.diagnostic)===null||d===void 0||d.log(ht.EVENTS.LINKED,{sessionIdHash:qt.Session.hash(e.id),linked:S,type:u.type,onlineGuests:u.onlineGuests}),this.linked=S||u.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{(h=this.diagnostic)===null||h===void 0||h.log(ht.EVENTS.SESSION_CONFIG_RECEIVED,{sessionIdHash:qt.Session.hash(e.id),metadata_keys:u&&u.metadata?Object.keys(u.metadata):void 0}),this.handleSessionMetadataUpdated(u.metadata);break}case"Event":{this.handleIncomingEvent(u);break}}u.id!==void 0&&((y=this.requestResolutions.get(u.id))===null||y===void 0||y(u))}),this.ws=c,this.http=new yl.WalletLinkHTTP(r,e.id,e.key)}connect(){var e;if(this.destroyed)throw new Error("instance is destroyed");(e=this.diagnostic)===null||e===void 0||e.log(ht.EVENTS.STARTED_CONNECTING,{sessionIdHash:qt.Session.hash(this.session.id)}),this.ws.connect()}destroy(){var e;this.destroyed=!0,this.ws.disconnect(),(e=this.diagnostic)===null||e===void 0||e.log(ht.EVENTS.DISCONNECTED,{sessionIdHash:qt.Session.hash(this.session.id)}),this.listener=void 0}get isDestroyed(){return this.destroyed}get connected(){return this._connected}set connected(e){var r,n;this._connected=e,e&&((r=this.onceConnected)===null||r===void 0||r.call(this)),(n=this.listener)===null||n===void 0||n.connectedUpdated(e)}setOnceConnected(e){return new Promise(r=>{this.connected?e().then(r):this.onceConnected=()=>{e().then(r),this.onceConnected=void 0}})}get linked(){return this._linked}set linked(e){var r,n;this._linked=e,e&&((r=this.onceLinked)===null||r===void 0||r.call(this)),(n=this.listener)===null||n===void 0||n.linkedUpdated(e)}setOnceLinked(e){return new Promise(r=>{this.linked?e().then(r):this.onceLinked=()=>{e().then(r),this.onceLinked=void 0}})}async handleIncomingEvent(e){var r,n;if(!(e.type!=="Event"||e.event!=="Web3Response"))try{const i=await this.cipher.decrypt(e.data),s=JSON.parse(i);if(s.type!=="WEB3_RESPONSE")return;(r=this.listener)===null||r===void 0||r.handleWeb3ResponseMessage(s)}catch{(n=this.diagnostic)===null||n===void 0||n.log(ht.EVENTS.GENERAL_ERROR,{message:"Had error decrypting",value:"incomingEvent"})}}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(e=>setTimeout(e,250));try{await this.fetchUnseenEventsAPI()}catch(e){console.error("Unable to check for unseen events",e)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(r=>this.handleIncomingEvent(r))}async setSessionMetadata(e,r){const n={type:"SetSessionConfig",id:(0,zt.IntNumber)(this.nextReqId++),sessionId:this.session.id,metadata:{[e]:r}};return this.setOnceConnected(async()=>{const i=await this.makeRequest(n);if(i.type==="Fail")throw new Error(i.error||"failed to set session metadata")})}async publishEvent(e,r,n=!1){const i=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},r),{origin:location.origin,relaySource:window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),s={type:"PublishEvent",id:(0,zt.IntNumber)(this.nextReqId++),sessionId:this.session.id,event:e,data:i,callWebhook:n};return this.setOnceLinked(async()=>{const c=await this.makeRequest(s);if(c.type==="Fail")throw new Error(c.error||"failed to publish event");return c.eventId})}sendData(e){this.ws.sendData(JSON.stringify(e))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>Ki*2){this.ws.disconnect();return}try{this.ws.sendData("h")}catch{}}async makeRequest(e,r=bl){const n=e.id;this.sendData(e);let i;return Promise.race([new Promise((s,c)=>{i=window.setTimeout(()=>{c(new Error(`request ${n} timed out`))},r)}),new Promise(s=>{this.requestResolutions.set(n,c=>{clearTimeout(i),s(c),this.requestResolutions.delete(n)})})])}async authenticate(){const e={type:"HostSession",id:(0,zt.IntNumber)(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key},r=await this.makeRequest(e);if(r.type==="Fail")throw new Error(r.error||"failed to authentcate")}sendIsLinked(){const e={type:"IsLinked",id:(0,zt.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(e)}sendGetSessionConfig(){const e={type:"GetSessionConfig",id:(0,zt.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(e)}}mn.WalletLinkConnection=_l;var Ar={},Nr={},zs={};Object.defineProperty(zs,"__esModule",{value:!0});zs.default='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';var El=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nr,"__esModule",{value:!0});Nr.injectCssReset=void 0;const Sl=El(zs);function Ml(){const t=document.createElement("style");t.type="text/css",t.appendChild(document.createTextNode(Sl.default)),document.documentElement.appendChild(t)}Nr.injectCssReset=Ml;var yn={},bn={};function pa(t){var e,r,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t))for(e=0;e65536?(n[0]=240|(i&1835008)>>>18,n[1]=128|(i&258048)>>>12,n[2]=128|(i&4032)>>>6,n[3]=128|i&63):i>2048?(n[0]=224|(i&61440)>>>12,n[1]=128|(i&4032)>>>6,n[2]=128|i&63):i>128?(n[0]=192|(i&1984)>>>6,n[1]=128|i&63):n[0]=i,this.parsedData.push(n)}this.parsedData=Array.prototype.concat.apply([],this.parsedData),this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}ma.prototype={getLength:function(t){return this.parsedData.length},write:function(t){for(var e=0,r=this.parsedData.length;e=7&&this.setupTypeNumber(t),this.dataCache==null&&(this.dataCache=wt.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,e)},setupPositionProbePattern:function(t,e){for(var r=-1;r<=7;r++)if(!(t+r<=-1||this.moduleCount<=t+r))for(var n=-1;n<=7;n++)e+n<=-1||this.moduleCount<=e+n||(0<=r&&r<=6&&(n==0||n==6)||0<=n&&n<=6&&(r==0||r==6)||2<=r&&r<=4&&2<=n&&n<=4?this.modules[t+r][e+n]=!0:this.modules[t+r][e+n]=!1)},getBestMaskPattern:function(){for(var t=0,e=0,r=0;r<8;r++){this.makeImpl(!0,r);var n=K.getLostPoint(this);(r==0||t>n)&&(t=n,e=r)}return e},createMovieClip:function(t,e,r){var n=t.createEmptyMovieClip(e,r),i=1;this.make();for(var s=0;s>r&1)==1;this.modules[Math.floor(r/3)][r%3+this.moduleCount-8-3]=n}for(var r=0;r<18;r++){var n=!t&&(e>>r&1)==1;this.modules[r%3+this.moduleCount-8-3][Math.floor(r/3)]=n}},setupTypeInfo:function(t,e){for(var r=this.errorCorrectLevel<<3|e,n=K.getBCHTypeInfo(r),i=0;i<15;i++){var s=!t&&(n>>i&1)==1;i<6?this.modules[i][8]=s:i<8?this.modules[i+1][8]=s:this.modules[this.moduleCount-15+i][8]=s}for(var i=0;i<15;i++){var s=!t&&(n>>i&1)==1;i<8?this.modules[8][this.moduleCount-i-1]=s:i<9?this.modules[8][15-i-1+1]=s:this.modules[8][15-i-1]=s}this.modules[this.moduleCount-8][8]=!t},mapData:function(t,e){for(var r=-1,n=this.moduleCount-1,i=7,s=0,c=this.moduleCount-1;c>0;c-=2)for(c==6&&c--;;){for(var u=0;u<2;u++)if(this.modules[n][c-u]==null){var d=!1;s>>i&1)==1);var h=K.getMask(e,n,c-u);h&&(d=!d),this.modules[n][c-u]=d,i--,i==-1&&(s++,i=7)}if(n+=r,n<0||this.moduleCount<=n){n-=r,r=-r;break}}}};wt.PAD0=236;wt.PAD1=17;wt.createData=function(t,e,r){for(var n=vt.getRSBlocks(t,e),i=new va,s=0;su*8)throw new Error("code length overflow. ("+i.getLengthInBits()+">"+u*8+")");for(i.getLengthInBits()+4<=u*8&&i.put(0,4);i.getLengthInBits()%8!=0;)i.putBit(!1);for(;!(i.getLengthInBits()>=u*8||(i.put(wt.PAD0,8),i.getLengthInBits()>=u*8));)i.put(wt.PAD1,8);return wt.createBytes(i,n)};wt.createBytes=function(t,e){for(var r=0,n=0,i=0,s=new Array(e.length),c=new Array(e.length),u=0;u=0?M.get(k):0}}for(var T=0,y=0;y=0;)e^=K.G15<=0;)e^=K.G18<>>=1;return e},getPatternPosition:function(t){return K.PATTERN_POSITION_TABLE[t-1]},getMask:function(t,e,r){switch(t){case Mt.PATTERN000:return(e+r)%2==0;case Mt.PATTERN001:return e%2==0;case Mt.PATTERN010:return r%3==0;case Mt.PATTERN011:return(e+r)%3==0;case Mt.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2==0;case Mt.PATTERN101:return e*r%2+e*r%3==0;case Mt.PATTERN110:return(e*r%2+e*r%3)%2==0;case Mt.PATTERN111:return(e*r%3+(e+r)%2)%2==0;default:throw new Error("bad maskPattern:"+t)}},getErrorCorrectPolynomial:function(t){for(var e=new Xt([1],0),r=0;r5&&(r+=3+s-5)}for(var n=0;n=256;)t-=255;return Fe.EXP_TABLE[t]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var Ue=0;Ue<8;Ue++)Fe.EXP_TABLE[Ue]=1<>>7-t%8&1)==1},put:function(t,e){for(var r=0;r>>e-r-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(t){var e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var vs=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]];function wa(t){if(this.options={padding:4,width:256,height:256,typeNumber:4,color:"#000000",background:"#ffffff",ecl:"M",image:{svg:"",width:0,height:0}},typeof t=="string"&&(t={content:t}),t)for(var e in t)this.options[e]=t[e];if(typeof this.options.content!="string")throw new Error("Expected 'content' as string!");if(this.options.content.length===0)throw new Error("Expected 'content' to be non-empty!");if(!(this.options.padding>=0))throw new Error("Expected 'padding' value to be non-negative!");if(!(this.options.width>0)||!(this.options.height>0))throw new Error("Expected 'width' or 'height' value to be higher than zero!");function r(d){switch(d){case"L":return It.L;case"M":return It.M;case"Q":return It.Q;case"H":return It.H;default:throw new Error("Unknwon error correction level: "+d)}}function n(d,h){for(var y=i(d),S=1,E=0,M=0,k=vs.length;M<=k;M++){var T=vs[M];if(!T)throw new Error("Content too long: expected "+E+" but got "+y);switch(h){case"L":E=T[0];break;case"M":E=T[1];break;case"Q":E=T[2];break;case"H":E=T[3];break;default:throw new Error("Unknwon error correction level: "+h)}if(y<=E)break;S++}if(S>vs.length)throw new Error("Content too long");return S}function i(d){var h=encodeURI(d).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return h.length+(h.length!=d?3:0)}var s=this.options.content,c=n(s,this.options.ecl),u=r(this.options.ecl);this.qrcode=new wt(c,u),this.qrcode.addData(s),this.qrcode.make()}wa.prototype.svg=function(t){var e=this.options||{},r=this.qrcode.modules;typeof t>"u"&&(t={container:e.container||"svg"});for(var n=typeof e.pretty<"u"?!!e.pretty:!0,i=n?" ":"",s=n?`\r +`:"",c=e.width,u=e.height,d=r.length,h=c/(d+2*e.padding),y=u/(d+2*e.padding),S=typeof e.join<"u"?!!e.join:!1,E=typeof e.swap<"u"?!!e.swap:!1,M=typeof e.xmlDeclaration<"u"?!!e.xmlDeclaration:!0,k=typeof e.predefined<"u"?!!e.predefined:!1,T=k?i+''+s:"",O=i+''+s,B="",L="",R=0;R'+s:B+=i+''+s}}S&&(B=i+'');let H="";if(this.options.image!==void 0&&this.options.image.svg){const b=c*this.options.image.width/100,o=u*this.options.image.height/100,l=c/2-b/2,f=u/2-o/2;H+=``,H+=this.options.image.svg+s,H+=""}var q="";switch(t.container){case"svg":M&&(q+=''+s),q+=''+s,q+=T+O+B,q+=H,q+="";break;case"svg-viewbox":M&&(q+=''+s),q+=''+s,q+=T+O+B,q+=H,q+="";break;case"g":q+=''+s,q+=T+O+B,q+=H,q+="";break;default:q+=(T+O+B+H).replace(/^\s+/,"");break}return q};var Al=wa,Nl=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.QRCode=void 0;const Ll=Ke,eo=an,xl=Nl(Al),Tl=t=>{const[e,r]=(0,eo.useState)("");return(0,eo.useEffect)(()=>{var n,i;const s=new xl.default({content:t.content,background:t.bgColor||"#ffffff",color:t.fgColor||"#000000",container:"svg",ecl:"M",width:(n=t.width)!==null&&n!==void 0?n:256,height:(i=t.height)!==null&&i!==void 0?i:256,padding:0,image:t.image}),c=Buffer.from(s.svg(),"utf8").toString("base64");r(`data:image/svg+xml;base64,${c}`)},[t.bgColor,t.content,t.fgColor,t.height,t.image,t.width]),e?(0,Ll.h)("img",{src:e,alt:"QR Code"}):null};Mn.QRCode=Tl;var kn={},qs={};Object.defineProperty(qs,"__esModule",{value:!0});qs.default=".-cbwsdk-css-reset .-cbwsdk-spinner{display:inline-block}.-cbwsdk-css-reset .-cbwsdk-spinner svg{display:inline-block;animation:2s linear infinite -cbwsdk-spinner-svg}.-cbwsdk-css-reset .-cbwsdk-spinner svg circle{animation:1.9s ease-in-out infinite both -cbwsdk-spinner-circle;display:block;fill:rgba(0,0,0,0);stroke-dasharray:283;stroke-dashoffset:280;stroke-linecap:round;stroke-width:10px;transform-origin:50% 50%}@keyframes -cbwsdk-spinner-svg{0%{transform:rotateZ(0deg)}100%{transform:rotateZ(360deg)}}@keyframes -cbwsdk-spinner-circle{0%,25%{stroke-dashoffset:280;transform:rotate(0)}50%,75%{stroke-dashoffset:75;transform:rotate(45deg)}100%{stroke-dashoffset:280;transform:rotate(360deg)}}";var Pl=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(kn,"__esModule",{value:!0});kn.Spinner=void 0;const Jr=Ke,$l=Pl(qs),Ol=t=>{var e;const r=(e=t.size)!==null&&e!==void 0?e:64,n=t.color||"#000";return(0,Jr.h)("div",{class:"-cbwsdk-spinner"},(0,Jr.h)("style",null,$l.default),(0,Jr.h)("svg",{viewBox:"0 0 100 100",xmlns:"http://www.w3.org/2000/svg",style:{width:r,height:r}},(0,Jr.h)("circle",{style:{cx:50,cy:50,r:45,stroke:n}})))};kn.Spinner=Ol;var Js={};Object.defineProperty(Js,"__esModule",{value:!0});Js.default=".-cbwsdk-css-reset .-cbwsdk-connect-content{height:430px;width:700px;border-radius:12px;padding:30px}.-cbwsdk-css-reset .-cbwsdk-connect-content.light{background:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content.dark{background:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-connect-content-header{display:flex;align-items:center;justify-content:space-between;margin:0 0 30px}.-cbwsdk-css-reset .-cbwsdk-connect-content-heading{font-style:normal;font-weight:500;font-size:28px;line-height:36px;margin:0}.-cbwsdk-css-reset .-cbwsdk-connect-content-heading.light{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-connect-content-heading.dark{color:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content-layout{display:flex;flex-direction:row}.-cbwsdk-css-reset .-cbwsdk-connect-content-column-left{margin-right:30px;display:flex;flex-direction:column;justify-content:space-between}.-cbwsdk-css-reset .-cbwsdk-connect-content-column-right{flex:25%;margin-right:34px}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-wrapper{width:220px;height:220px;border-radius:12px;display:flex;justify-content:center;align-items:center;background:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting{position:absolute;top:0;bottom:0;left:0;right:0;display:flex;flex-direction:column;align-items:center;justify-content:center}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.light{background-color:rgba(255,255,255,.95)}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.light>p{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.dark{background-color:rgba(10,11,13,.9)}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.dark>p{color:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting>p{font-size:12px;font-weight:bold;margin-top:16px}.-cbwsdk-css-reset .-cbwsdk-connect-content-update-app{border-radius:8px;font-size:14px;line-height:20px;padding:12px;width:339px}.-cbwsdk-css-reset .-cbwsdk-connect-content-update-app.light{background:#eef0f3;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-connect-content-update-app.dark{background:#1e2025;color:#8a919e}.-cbwsdk-css-reset .-cbwsdk-cancel-button{-webkit-appearance:none;border:none;background:none;cursor:pointer;padding:0;margin:0}.-cbwsdk-css-reset .-cbwsdk-cancel-button-x{position:relative;display:block;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-wallet-steps{padding:0 0 0 16px;margin:0;width:100%;list-style:decimal}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item{list-style-type:decimal;display:list-item;font-style:normal;font-weight:400;font-size:16px;line-height:24px;margin-top:20px}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item.light{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item.dark{color:#fff}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item-wrapper{display:flex;align-items:center}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-pad-left{margin-left:6px}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon{display:flex;border-radius:50%;height:24px;width:24px}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon svg{margin:auto;display:block}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon.light{background:#0052ff}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon.dark{background:#588af5}.-cbwsdk-css-reset .-cbwsdk-connect-item{align-items:center;display:flex;flex-direction:row;padding:16px 24px;gap:12px;cursor:pointer;border-radius:100px;font-weight:600}.-cbwsdk-css-reset .-cbwsdk-connect-item.light{background:#f5f8ff;color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-connect-item.dark{background:#001033;color:#588af5}.-cbwsdk-css-reset .-cbwsdk-connect-item-copy-wrapper{margin:0 4px 0 8px}.-cbwsdk-css-reset .-cbwsdk-connect-item-title{margin:0 0 0;font-size:16px;line-height:24px;font-weight:500}.-cbwsdk-css-reset .-cbwsdk-connect-item-description{font-weight:400;font-size:14px;line-height:20px;margin:0}";var ya=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(sr,"__esModule",{value:!0});sr.CoinbaseWalletSteps=sr.ConnectContent=void 0;const Dt=ya(Lr),V=Ke,Bl=A,Dl=lr,jl=_n,Fl=En,Hl=Sn,Ul=Mn,Vl=kn,Wl=ya(Js),ws={title:"Coinbase Wallet app",description:"Connect with your self-custody wallet",steps:ba},zl=t=>t==="light"?"#FFFFFF":"#0A0B0D";function ql(t){const{theme:e}=t,r=(0,Bl.createQrUrl)(t.sessionId,t.sessionSecret,t.linkAPIUrl,t.isParentConnection,t.version,t.chainId),n=ws.steps;return(0,V.h)("div",{"data-testid":"connect-content",className:(0,Dt.default)("-cbwsdk-connect-content",e)},(0,V.h)("style",null,Wl.default),(0,V.h)("div",{className:"-cbwsdk-connect-content-header"},(0,V.h)("h2",{className:(0,Dt.default)("-cbwsdk-connect-content-heading",e)},"Scan to connect with our mobile app"),t.onCancel&&(0,V.h)("button",{type:"button",className:"-cbwsdk-cancel-button",onClick:t.onCancel},(0,V.h)(jl.CloseIcon,{fill:e==="light"?"#0A0B0D":"#FFFFFF"}))),(0,V.h)("div",{className:"-cbwsdk-connect-content-layout"},(0,V.h)("div",{className:"-cbwsdk-connect-content-column-left"},(0,V.h)(Jl,{title:ws.title,description:ws.description,theme:e})),(0,V.h)("div",{className:"-cbwsdk-connect-content-column-right"},(0,V.h)("div",{className:"-cbwsdk-connect-content-qr-wrapper"},(0,V.h)(Ul.QRCode,{content:r,width:200,height:200,fgColor:"#000",bgColor:"transparent"}),(0,V.h)("input",{type:"hidden",name:"cbw-cbwsdk-version",value:Dl.LIB_VERSION}),(0,V.h)("input",{type:"hidden",value:r})),(0,V.h)(n,{theme:e}),!t.isConnected&&(0,V.h)("div",{"data-testid":"connecting-spinner",className:(0,Dt.default)("-cbwsdk-connect-content-qr-connecting",e)},(0,V.h)(Vl.Spinner,{size:36,color:e==="dark"?"#FFF":"#000"}),(0,V.h)("p",null,"Connecting...")))))}sr.ConnectContent=ql;function Jl({title:t,description:e,theme:r}){return(0,V.h)("div",{className:(0,Dt.default)("-cbwsdk-connect-item",r)},(0,V.h)("div",null,(0,V.h)(Fl.CoinbaseWalletRound,null)),(0,V.h)("div",{className:"-cbwsdk-connect-item-copy-wrapper"},(0,V.h)("h3",{className:"-cbwsdk-connect-item-title"},t),(0,V.h)("p",{className:"-cbwsdk-connect-item-description"},e)))}function ba({theme:t}){return(0,V.h)("ol",{className:"-cbwsdk-wallet-steps"},(0,V.h)("li",{className:(0,Dt.default)("-cbwsdk-wallet-steps-item",t)},(0,V.h)("div",{className:"-cbwsdk-wallet-steps-item-wrapper"},"Open Coinbase Wallet app")),(0,V.h)("li",{className:(0,Dt.default)("-cbwsdk-wallet-steps-item",t)},(0,V.h)("div",{className:"-cbwsdk-wallet-steps-item-wrapper"},(0,V.h)("span",null,"Tap ",(0,V.h)("strong",null,"Scan")," "),(0,V.h)("span",{className:(0,Dt.default)("-cbwsdk-wallet-steps-pad-left","-cbwsdk-wallet-steps-icon",t)},(0,V.h)(Hl.QRCodeIcon,{fill:zl(t)})))))}sr.CoinbaseWalletSteps=ba;var Rn={},In={};Object.defineProperty(In,"__esModule",{value:!0});In.ArrowLeftIcon=void 0;const to=Ke;function Gl(t){return(0,to.h)("svg",Object.assign({width:"16",height:"16",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg"},t),(0,to.h)("path",{d:"M8.60675 0.155884L7.37816 1.28209L12.7723 7.16662H0V8.83328H12.6548L6.82149 14.6666L8 15.8451L15.8201 8.02501L8.60675 0.155884Z"}))}In.ArrowLeftIcon=Gl;var Cn={};Object.defineProperty(Cn,"__esModule",{value:!0});Cn.LaptopIcon=void 0;const ys=Ke;function Zl(t){return(0,ys.h)("svg",Object.assign({width:"14",height:"14",viewBox:"0 0 14 14",xmlns:"http://www.w3.org/2000/svg"},t),(0,ys.h)("path",{d:"M1.8001 2.2002H12.2001V9.40019H1.8001V2.2002ZM3.4001 3.8002V7.80019H10.6001V3.8002H3.4001Z"}),(0,ys.h)("path",{d:"M13.4001 10.2002H0.600098C0.600098 11.0838 1.31644 11.8002 2.2001 11.8002H11.8001C12.6838 11.8002 13.4001 11.0838 13.4001 10.2002Z"}))}Cn.LaptopIcon=Zl;var An={};Object.defineProperty(An,"__esModule",{value:!0});An.SafeIcon=void 0;const ro=Ke;function Ql(t){return(0,ro.h)("svg",Object.assign({width:"14",height:"14",viewBox:"0 0 14 14",xmlns:"http://www.w3.org/2000/svg"},t),(0,ro.h)("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M0.600098 0.600098V11.8001H13.4001V0.600098H0.600098ZM7.0001 9.2001C5.3441 9.2001 4.0001 7.8561 4.0001 6.2001C4.0001 4.5441 5.3441 3.2001 7.0001 3.2001C8.6561 3.2001 10.0001 4.5441 10.0001 6.2001C10.0001 7.8561 8.6561 9.2001 7.0001 9.2001ZM0.600098 12.6001H3.8001V13.4001H0.600098V12.6001ZM10.2001 12.6001H13.4001V13.4001H10.2001V12.6001ZM8.8001 6.2001C8.8001 7.19421 7.99421 8.0001 7.0001 8.0001C6.00598 8.0001 5.2001 7.19421 5.2001 6.2001C5.2001 5.20598 6.00598 4.4001 7.0001 4.4001C7.99421 4.4001 8.8001 5.20598 8.8001 6.2001Z"}))}An.SafeIcon=Ql;var Gs={};Object.defineProperty(Gs,"__esModule",{value:!0});Gs.default=".-cbwsdk-css-reset .-cbwsdk-try-extension{display:flex;margin-top:12px;height:202px;width:700px;border-radius:12px;padding:30px}.-cbwsdk-css-reset .-cbwsdk-try-extension.light{background:#fff}.-cbwsdk-css-reset .-cbwsdk-try-extension.dark{background:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-try-extension-column-half{flex:50%}.-cbwsdk-css-reset .-cbwsdk-try-extension-heading{font-style:normal;font-weight:500;font-size:25px;line-height:32px;margin:0;max-width:204px}.-cbwsdk-css-reset .-cbwsdk-try-extension-heading.light{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-try-extension-heading.dark{color:#fff}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta{appearance:none;border:none;background:none;color:#0052ff;cursor:pointer;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta.light{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta.dark{color:#588af5}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta-wrapper{display:flex;align-items:center;margin-top:12px}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta-icon{display:block;margin-left:4px;height:14px}.-cbwsdk-css-reset .-cbwsdk-try-extension-list{display:flex;flex-direction:column;justify-content:center;align-items:center;margin:0;padding:0;list-style:none;height:100%}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item{display:flex;align-items:center;flex-flow:nowrap;margin-top:24px}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item:first-of-type{margin-top:0}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon-wrapper{display:block}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon{display:flex;height:32px;width:32px;border-radius:50%}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon svg{margin:auto;display:block}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon.light{background:#eef0f3}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon.dark{background:#1e2025}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-copy{display:block;font-weight:400;font-size:14px;line-height:20px;padding-left:12px}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-copy.light{color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-copy.dark{color:#8a919e}";var _a=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Rn,"__esModule",{value:!0});Rn.TryExtensionContent=void 0;const Nt=_a(Lr),Be=Ke,bs=an,Kl=In,Xl=Cn,Yl=An,eu=_a(Gs);function tu({theme:t}){const[e,r]=(0,bs.useState)(!1),n=(0,bs.useCallback)(()=>{window.open("https://api.wallet.coinbase.com/rpc/v2/desktop/chrome","_blank")},[]),i=(0,bs.useCallback)(()=>{e?window.location.reload():(n(),r(!0))},[n,e]);return(0,Be.h)("div",{class:(0,Nt.default)("-cbwsdk-try-extension",t)},(0,Be.h)("style",null,eu.default),(0,Be.h)("div",{class:"-cbwsdk-try-extension-column-half"},(0,Be.h)("h3",{class:(0,Nt.default)("-cbwsdk-try-extension-heading",t)},"Or try the Coinbase Wallet browser extension"),(0,Be.h)("div",{class:"-cbwsdk-try-extension-cta-wrapper"},(0,Be.h)("button",{class:(0,Nt.default)("-cbwsdk-try-extension-cta",t),onClick:i},e?"Refresh":"Install"),(0,Be.h)("div",null,!e&&(0,Be.h)(Kl.ArrowLeftIcon,{class:"-cbwsdk-try-extension-cta-icon",fill:t==="light"?"#0052FF":"#588AF5"})))),(0,Be.h)("div",{class:"-cbwsdk-try-extension-column-half"},(0,Be.h)("ul",{class:"-cbwsdk-try-extension-list"},(0,Be.h)("li",{class:"-cbwsdk-try-extension-list-item"},(0,Be.h)("div",{class:"-cbwsdk-try-extension-list-item-icon-wrapper"},(0,Be.h)("span",{class:(0,Nt.default)("-cbwsdk-try-extension-list-item-icon",t)},(0,Be.h)(Xl.LaptopIcon,{fill:t==="light"?"#0A0B0D":"#FFFFFF"}))),(0,Be.h)("div",{class:(0,Nt.default)("-cbwsdk-try-extension-list-item-copy",t)},"Connect with dapps with just one click on your desktop browser")),(0,Be.h)("li",{class:"-cbwsdk-try-extension-list-item"},(0,Be.h)("div",{class:"-cbwsdk-try-extension-list-item-icon-wrapper"},(0,Be.h)("span",{class:(0,Nt.default)("-cbwsdk-try-extension-list-item-icon",t)},(0,Be.h)(Yl.SafeIcon,{fill:t==="light"?"#0A0B0D":"#FFFFFF"}))),(0,Be.h)("div",{class:(0,Nt.default)("-cbwsdk-try-extension-list-item-copy",t)},"Add an additional layer of security by using a supported Ledger hardware wallet")))))}Rn.TryExtensionContent=tu;var Zs={};Object.defineProperty(Zs,"__esModule",{value:!0});Zs.default=".-cbwsdk-css-reset .-cbwsdk-connect-dialog{z-index:2147483647;position:fixed;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop{z-index:2147483647;position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop.light{background-color:rgba(0,0,0,.5)}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop.dark{background-color:rgba(50,53,61,.4)}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-box{display:flex;position:relative;flex-direction:column;transform:scale(1);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-box-hidden{opacity:0;transform:scale(0.85)}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-container{display:block}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-container-hidden{display:none}";var Ea=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(bn,"__esModule",{value:!0});bn.ConnectDialog=void 0;const _s=Ea(Lr),Lt=Ke,Es=an,ru=sr,nu=Rn,su=Ea(Zs),iu=t=>{const{isOpen:e,darkMode:r}=t,[n,i]=(0,Es.useState)(!e),[s,c]=(0,Es.useState)(!e);(0,Es.useEffect)(()=>{const d=[window.setTimeout(()=>{c(!e)},10)];return e?i(!1):d.push(window.setTimeout(()=>{i(!0)},360)),()=>{d.forEach(window.clearTimeout)}},[e]);const u=r?"dark":"light";return(0,Lt.h)("div",{class:(0,_s.default)("-cbwsdk-connect-dialog-container",n&&"-cbwsdk-connect-dialog-container-hidden")},(0,Lt.h)("style",null,su.default),(0,Lt.h)("div",{class:(0,_s.default)("-cbwsdk-connect-dialog-backdrop",u,s&&"-cbwsdk-connect-dialog-backdrop-hidden")}),(0,Lt.h)("div",{class:"-cbwsdk-connect-dialog"},(0,Lt.h)("div",{class:(0,_s.default)("-cbwsdk-connect-dialog-box",s&&"-cbwsdk-connect-dialog-box-hidden")},t.connectDisabled?null:(0,Lt.h)(ru.ConnectContent,{theme:u,version:t.version,sessionId:t.sessionId,sessionSecret:t.sessionSecret,linkAPIUrl:t.linkAPIUrl,isConnected:t.isConnected,isParentConnection:t.isParentConnection,chainId:t.chainId,onCancel:t.onCancel}),(0,Lt.h)(nu.TryExtensionContent,{theme:u}))))};bn.ConnectDialog=iu;Object.defineProperty(yn,"__esModule",{value:!0});yn.LinkFlow=void 0;const Ss=Ke,ou=bn;class au{constructor(e){this.connected=!1,this.chainId=1,this.isOpen=!1,this.onCancel=null,this.root=null,this.connectDisabled=!1,this.darkMode=e.darkMode,this.version=e.version,this.sessionId=e.sessionId,this.sessionSecret=e.sessionSecret,this.linkAPIUrl=e.linkAPIUrl,this.isParentConnection=e.isParentConnection}attach(e){this.root=document.createElement("div"),this.root.className="-cbwsdk-link-flow-root",e.appendChild(this.root),this.render()}setConnected(e){this.connected!==e&&(this.connected=e,this.render())}setChainId(e){this.chainId!==e&&(this.chainId=e,this.render())}detach(){var e;this.root&&((0,Ss.render)(null,this.root),(e=this.root.parentElement)===null||e===void 0||e.removeChild(this.root))}setConnectDisabled(e){this.connectDisabled=e}open(e){this.isOpen=!0,this.onCancel=e.onCancel,this.render()}close(){this.isOpen=!1,this.onCancel=null,this.render()}render(){this.root&&(0,Ss.render)((0,Ss.h)(ou.ConnectDialog,{darkMode:this.darkMode,version:this.version,sessionId:this.sessionId,sessionSecret:this.sessionSecret,linkAPIUrl:this.linkAPIUrl,isOpen:this.isOpen,isConnected:this.connected,isParentConnection:this.isParentConnection,chainId:this.chainId,onCancel:this.onCancel,connectDisabled:this.connectDisabled}),this.root)}}yn.LinkFlow=au;var Qs={},Ks={};Object.defineProperty(Ks,"__esModule",{value:!0});Ks.default=".-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}";(function(t){var e=x&&x.__importDefault||function(S){return S&&S.__esModule?S:{default:S}};Object.defineProperty(t,"__esModule",{value:!0}),t.SnackbarInstance=t.SnackbarContainer=t.Snackbar=void 0;const r=e(Lr),n=Ke,i=an,s=e(Ks),c="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",u="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=";class d{constructor(E){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=E.darkMode}attach(E){this.root=document.createElement("div"),this.root.className="-cbwsdk-snackbar-root",E.appendChild(this.root),this.render()}presentItem(E){const M=this.nextItemKey++;return this.items.set(M,E),this.render(),()=>{this.items.delete(M),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&(0,n.render)((0,n.h)("div",null,(0,n.h)(t.SnackbarContainer,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([E,M])=>(0,n.h)(t.SnackbarInstance,Object.assign({},M,{key:E}))))),this.root)}}t.Snackbar=d;const h=S=>(0,n.h)("div",{class:(0,r.default)("-cbwsdk-snackbar-container")},(0,n.h)("style",null,s.default),(0,n.h)("div",{class:"-cbwsdk-snackbar"},S.children));t.SnackbarContainer=h;const y=({autoExpand:S,message:E,menuItems:M})=>{const[k,T]=(0,i.useState)(!0),[O,B]=(0,i.useState)(S??!1);(0,i.useEffect)(()=>{const R=[window.setTimeout(()=>{T(!1)},1),window.setTimeout(()=>{B(!0)},1e4)];return()=>{R.forEach(window.clearTimeout)}});const L=()=>{B(!O)};return(0,n.h)("div",{class:(0,r.default)("-cbwsdk-snackbar-instance",k&&"-cbwsdk-snackbar-instance-hidden",O&&"-cbwsdk-snackbar-instance-expanded")},(0,n.h)("div",{class:"-cbwsdk-snackbar-instance-header",onClick:L},(0,n.h)("img",{src:c,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",(0,n.h)("div",{class:"-cbwsdk-snackbar-instance-header-message"},E),(0,n.h)("div",{class:"-gear-container"},!O&&(0,n.h)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,n.h)("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),(0,n.h)("img",{src:u,class:"-gear-icon",title:"Expand"}))),M&&M.length>0&&(0,n.h)("div",{class:"-cbwsdk-snackbar-instance-menu"},M.map((R,z)=>(0,n.h)("div",{class:(0,r.default)("-cbwsdk-snackbar-instance-menu-item",R.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:R.onClick,key:z},(0,n.h)("svg",{width:R.svgWidth,height:R.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,n.h)("path",{"fill-rule":R.defaultFillRule,"clip-rule":R.defaultClipRule,d:R.path,fill:"#AAAAAA"})),(0,n.h)("span",{class:(0,r.default)("-cbwsdk-snackbar-instance-menu-item-info",R.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},R.info)))))};t.SnackbarInstance=y})(Qs);Object.defineProperty(Ar,"__esModule",{value:!0});Ar.WalletLinkRelayUI=void 0;const cu=Nr,lu=yn,uu=Qs;class du{constructor(e){this.standalone=null,this.attached=!1,this.snackbar=new uu.Snackbar({darkMode:e.darkMode}),this.linkFlow=new lu.LinkFlow({darkMode:e.darkMode,version:e.version,sessionId:e.session.id,sessionSecret:e.session.secret,linkAPIUrl:e.linkAPIUrl,isParentConnection:!1})}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const e=document.documentElement,r=document.createElement("div");r.className="-cbwsdk-css-reset",e.appendChild(r),this.linkFlow.attach(r),this.snackbar.attach(r),this.attached=!0,(0,cu.injectCssReset)()}setConnected(e){this.linkFlow.setConnected(e)}setChainId(e){this.linkFlow.setChainId(e)}setConnectDisabled(e){this.linkFlow.setConnectDisabled(e)}addEthereumChain(){}watchAsset(){}switchEthereumChain(){}requestEthereumAccounts(e){this.linkFlow.open({onCancel:e.onCancel})}hideRequestEthereumAccounts(){this.linkFlow.close()}signEthereumMessage(){}signEthereumTransaction(){}submitEthereumTransaction(){}ethereumAddressFromSignedMessage(){}showConnecting(e){let r;return e.isUnlinkedErrorState?r={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]}:r={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:e.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]},this.snackbar.presentItem(r)}reloadUI(){document.location.reload()}inlineAccountsResponse(){return!1}inlineAddEthereumChain(){return!1}inlineWatchAsset(){return!1}inlineSwitchEthereumChain(){return!1}setStandalone(e){this.standalone=e}isStandalone(){var e;return(e=this.standalone)!==null&&e!==void 0?e:!1}}Ar.WalletLinkRelayUI=du;Object.defineProperty(Cr,"__esModule",{value:!0});Cr.WalletLinkRelay=void 0;const Jt=Sr,hu=De,Q=A,xt=ur,no=it,kt=dr,fu=mn,Tt=cr,gu=Ar;class Et extends no.RelayAbstract{constructor(e){var r;super(),this.accountsCallback=null,this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.chainCallback=null,this.dappDefaultChain=1,this.appName="",this.appLogoUrl=null,this.linkedUpdated=c=>{var u;this.isLinked=c;const d=this.storage.getItem(no.LOCAL_STORAGE_ADDRESSES_KEY);if(c&&(this.session.linked=c),this.isUnlinkedErrorState=!1,d){const h=d.split(" "),y=this.storage.getItem("IsStandaloneSigning")==="true";if(h[0]!==""&&!c&&this.session.linked&&!y){this.isUnlinkedErrorState=!0;const S=this.getSessionIdHash();(u=this.diagnostic)===null||u===void 0||u.log(xt.EVENTS.UNLINKED_ERROR_STATE,{sessionIdHash:S})}}},this.metadataUpdated=(c,u)=>{this.storage.setItem(c,u)},this.chainUpdated=(c,u)=>{this.chainCallbackParams.chainId===c&&this.chainCallbackParams.jsonRpcUrl===u||(this.chainCallbackParams={chainId:c,jsonRpcUrl:u},this.chainCallback&&this.chainCallback(c,u))},this.accountUpdated=c=>{this.accountsCallback&&this.accountsCallback([c]),Et.accountRequestCallbackIds.size>0&&(Array.from(Et.accountRequestCallbackIds.values()).forEach(u=>{const d={type:"WEB3_RESPONSE",id:u,response:{method:"requestEthereumAccounts",result:[c]}};this.invokeCallback(Object.assign(Object.assign({},d),{id:u}))}),Et.accountRequestCallbackIds.clear())},this.connectedUpdated=c=>{this.ui.setConnected(c)},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=e.linkAPIUrl,this.storage=e.storage,this.options=e;const{session:n,ui:i,connection:s}=this.subscribe();this._session=n,this.connection=s,this.relayEventManager=e.relayEventManager,this.diagnostic=e.diagnosticLogger,this._reloadOnDisconnect=(r=e.reloadOnDisconnect)!==null&&r!==void 0?r:!0,this.ui=i}subscribe(){const e=kt.Session.load(this.storage)||new kt.Session(this.storage).save(),{linkAPIUrl:r,diagnostic:n}=this,i=new fu.WalletLinkConnection({session:e,linkAPIUrl:r,diagnostic:n,listener:this}),{version:s,darkMode:c}=this.options,u=this.options.uiConstructor({linkAPIUrl:r,version:s,darkMode:c,session:e});return i.connect(),{session:e,ui:u,connection:i}}attachUI(){this.ui.attach()}resetAndReload(){Promise.race([this.connection.setSessionMetadata("__destroyed","1"),new Promise(e=>setTimeout(()=>e(null),1e3))]).then(()=>{var e,r;const n=this.ui.isStandalone();(e=this.diagnostic)===null||e===void 0||e.log(xt.EVENTS.SESSION_STATE_CHANGE,{method:"relay::resetAndReload",sessionMetadataChange:"__destroyed, 1",sessionIdHash:this.getSessionIdHash()}),this.connection.destroy();const i=kt.Session.load(this.storage);if((i==null?void 0:i.id)===this._session.id?this.storage.clear():i&&((r=this.diagnostic)===null||r===void 0||r.log(xt.EVENTS.SKIPPED_CLEARING_SESSION,{sessionIdHash:this.getSessionIdHash(),storedSessionIdHash:kt.Session.hash(i.id)})),this._reloadOnDisconnect){this.ui.reloadUI();return}this.accountsCallback&&this.accountsCallback([],!0);const{session:s,ui:c,connection:u}=this.subscribe();this._session=s,this.connection=u,this.ui=c,n&&this.ui.setStandalone&&this.ui.setStandalone(!0),this.options.headlessMode||this.attachUI()}).catch(e=>{var r;(r=this.diagnostic)===null||r===void 0||r.log(xt.EVENTS.FAILURE,{method:"relay::resetAndReload",message:`failed to reset and reload with ${e}`,sessionIdHash:this.getSessionIdHash()})})}setAppInfo(e,r){this.appName=e,this.appLogoUrl=r}getStorageItem(e){return this.storage.getItem(e)}get session(){return this._session}setStorageItem(e,r){this.storage.setItem(e,r)}signEthereumMessage(e,r,n,i){return this.sendRequest({method:"signEthereumMessage",params:{message:(0,Q.hexStringFromBuffer)(e,!0),address:r,addPrefix:n,typedDataJson:i||null}})}ethereumAddressFromSignedMessage(e,r,n){return this.sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:(0,Q.hexStringFromBuffer)(e,!0),signature:(0,Q.hexStringFromBuffer)(r,!0),addPrefix:n}})}signEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:(0,Q.bigIntStringFromBN)(e.weiValue),data:(0,Q.hexStringFromBuffer)(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?(0,Q.bigIntStringFromBN)(e.gasPriceInWei):null,maxFeePerGas:e.gasPriceInWei?(0,Q.bigIntStringFromBN)(e.gasPriceInWei):null,maxPriorityFeePerGas:e.gasPriceInWei?(0,Q.bigIntStringFromBN)(e.gasPriceInWei):null,gasLimit:e.gasLimit?(0,Q.bigIntStringFromBN)(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:(0,Q.bigIntStringFromBN)(e.weiValue),data:(0,Q.hexStringFromBuffer)(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?(0,Q.bigIntStringFromBN)(e.gasPriceInWei):null,maxFeePerGas:e.maxFeePerGas?(0,Q.bigIntStringFromBN)(e.maxFeePerGas):null,maxPriorityFeePerGas:e.maxPriorityFeePerGas?(0,Q.bigIntStringFromBN)(e.maxPriorityFeePerGas):null,gasLimit:e.gasLimit?(0,Q.bigIntStringFromBN)(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!0}})}submitEthereumTransaction(e,r){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:(0,Q.hexStringFromBuffer)(e,!0),chainId:r}})}scanQRCode(e){return this.sendRequest({method:"scanQRCode",params:{regExp:e}})}getQRCodeUrl(){return(0,Q.createQrUrl)(this._session.id,this._session.secret,this.linkAPIUrl,!1,this.options.version,this.dappDefaultChain)}genericRequest(e,r){return this.sendRequest({method:"generic",params:{action:r,data:e}})}sendGenericMessage(e){return this.sendRequest(e)}sendRequest(e){let r=null;const n=(0,Q.randomBytesHex)(8),i=c=>{this.publishWeb3RequestCanceledEvent(n),this.handleErrorResponse(n,e.method,c),r==null||r()};return{promise:new Promise((c,u)=>{this.ui.isStandalone()||(r=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:i,onResetConnection:this.resetAndReload})),this.relayEventManager.callbacks.set(n,d=>{if(r==null||r(),(0,Tt.isErrorResponse)(d))return u(new Error(d.errorMessage));c(d)}),this.ui.isStandalone()?this.sendRequestStandalone(n,e):this.publishWeb3RequestEvent(n,e)}),cancel:i}}setConnectDisabled(e){this.ui.setConnectDisabled(e)}setAccountsCallback(e){this.accountsCallback=e}setChainCallback(e){this.chainCallback=e}setDappDefaultChainCallback(e){this.dappDefaultChain=e,this.ui instanceof gu.WalletLinkRelayUI&&this.ui.setChainId(e)}publishWeb3RequestEvent(e,r){var n;const i={type:"WEB3_REQUEST",id:e,request:r},s=kt.Session.load(this.storage);(n=this.diagnostic)===null||n===void 0||n.log(xt.EVENTS.WEB3_REQUEST,{eventId:i.id,method:`relay::${r.method}`,sessionIdHash:this.getSessionIdHash(),storedSessionIdHash:s?kt.Session.hash(s.id):"",isSessionMismatched:((s==null?void 0:s.id)!==this._session.id).toString()}),this.publishEvent("Web3Request",i,!0).then(c=>{var u;(u=this.diagnostic)===null||u===void 0||u.log(xt.EVENTS.WEB3_REQUEST_PUBLISHED,{eventId:i.id,method:`relay::${r.method}`,sessionIdHash:this.getSessionIdHash(),storedSessionIdHash:s?kt.Session.hash(s.id):"",isSessionMismatched:((s==null?void 0:s.id)!==this._session.id).toString()})}).catch(c=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:i.id,response:{method:r.method,errorMessage:c.message}})})}publishWeb3RequestCanceledEvent(e){const r={type:"WEB3_REQUEST_CANCELED",id:e};this.publishEvent("Web3RequestCanceled",r,!1).then()}publishEvent(e,r,n){return this.connection.publishEvent(e,r,n)}handleWeb3ResponseMessage(e){var r;const{response:n}=e;if((r=this.diagnostic)===null||r===void 0||r.log(xt.EVENTS.WEB3_RESPONSE,{eventId:e.id,method:`relay::${n.method}`,sessionIdHash:this.getSessionIdHash()}),n.method==="requestEthereumAccounts"){Et.accountRequestCallbackIds.forEach(i=>this.invokeCallback(Object.assign(Object.assign({},e),{id:i}))),Et.accountRequestCallbackIds.clear();return}this.invokeCallback(e)}handleErrorResponse(e,r,n,i){var s;const c=(s=n==null?void 0:n.message)!==null&&s!==void 0?s:(0,Jt.getMessageFromCode)(i);this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:e,response:{method:r,errorMessage:c,errorCode:i}})}invokeCallback(e){const r=this.relayEventManager.callbacks.get(e.id);r&&(r(e.response),this.relayEventManager.callbacks.delete(e.id))}requestEthereumAccounts(){const e={method:"requestEthereumAccounts",params:{appName:this.appName,appLogoUrl:this.appLogoUrl||null}},r=(0,Q.randomBytesHex)(8),n=s=>{this.publishWeb3RequestCanceledEvent(r),this.handleErrorResponse(r,e.method,s)};return{promise:new Promise((s,c)=>{if(this.relayEventManager.callbacks.set(r,u=>{if(this.ui.hideRequestEthereumAccounts(),(0,Tt.isErrorResponse)(u))return c(new Error(u.errorMessage));s(u)}),this.ui.inlineAccountsResponse()){const u=d=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:r,response:{method:"requestEthereumAccounts",result:d}})};this.ui.requestEthereumAccounts({onCancel:n,onAccounts:u})}else{const u=Jt.standardErrors.provider.userRejectedRequest("User denied account authorization");this.ui.requestEthereumAccounts({onCancel:()=>n(u)})}Et.accountRequestCallbackIds.add(r),!this.ui.inlineAccountsResponse()&&!this.ui.isStandalone()&&this.publishWeb3RequestEvent(r,e)}),cancel:n}}selectProvider(e){const r={method:"selectProvider",params:{providerOptions:e}},n=(0,Q.randomBytesHex)(8),i=c=>{this.publishWeb3RequestCanceledEvent(n),this.handleErrorResponse(n,r.method,c)},s=new Promise((c,u)=>{this.relayEventManager.callbacks.set(n,y=>{if((0,Tt.isErrorResponse)(y))return u(new Error(y.errorMessage));c(y)});const d=y=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:n,response:{method:"selectProvider",result:hu.ProviderType.Unselected}})},h=y=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:n,response:{method:"selectProvider",result:y}})};this.ui.selectProvider&&this.ui.selectProvider({onApprove:h,onCancel:d,providerOptions:e})});return{cancel:i,promise:s}}watchAsset(e,r,n,i,s,c){const u={method:"watchAsset",params:{type:e,options:{address:r,symbol:n,decimals:i,image:s},chainId:c}};let d=null;const h=(0,Q.randomBytesHex)(8),y=E=>{this.publishWeb3RequestCanceledEvent(h),this.handleErrorResponse(h,u.method,E),d==null||d()};this.ui.inlineWatchAsset()||(d=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:y,onResetConnection:this.resetAndReload}));const S=new Promise((E,M)=>{this.relayEventManager.callbacks.set(h,O=>{if(d==null||d(),(0,Tt.isErrorResponse)(O))return M(new Error(O.errorMessage));E(O)});const k=O=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:h,response:{method:"watchAsset",result:!1}})},T=()=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:h,response:{method:"watchAsset",result:!0}})};this.ui.inlineWatchAsset()&&this.ui.watchAsset({onApprove:T,onCancel:k,type:e,address:r,symbol:n,decimals:i,image:s,chainId:c}),!this.ui.inlineWatchAsset()&&!this.ui.isStandalone()&&this.publishWeb3RequestEvent(h,u)});return{cancel:y,promise:S}}addEthereumChain(e,r,n,i,s,c){const u={method:"addEthereumChain",params:{chainId:e,rpcUrls:r,blockExplorerUrls:i,chainName:s,iconUrls:n,nativeCurrency:c}};let d=null;const h=(0,Q.randomBytesHex)(8),y=E=>{this.publishWeb3RequestCanceledEvent(h),this.handleErrorResponse(h,u.method,E),d==null||d()};return this.ui.inlineAddEthereumChain(e)||(d=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:y,onResetConnection:this.resetAndReload})),{promise:new Promise((E,M)=>{this.relayEventManager.callbacks.set(h,O=>{if(d==null||d(),(0,Tt.isErrorResponse)(O))return M(new Error(O.errorMessage));E(O)});const k=O=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:h,response:{method:"addEthereumChain",result:{isApproved:!1,rpcUrl:""}}})},T=O=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:h,response:{method:"addEthereumChain",result:{isApproved:!0,rpcUrl:O}}})};this.ui.inlineAddEthereumChain(e)&&this.ui.addEthereumChain({onCancel:k,onApprove:T,chainId:u.params.chainId,rpcUrls:u.params.rpcUrls,blockExplorerUrls:u.params.blockExplorerUrls,chainName:u.params.chainName,iconUrls:u.params.iconUrls,nativeCurrency:u.params.nativeCurrency}),!this.ui.inlineAddEthereumChain(e)&&!this.ui.isStandalone()&&this.publishWeb3RequestEvent(h,u)}),cancel:y}}switchEthereumChain(e,r){const n={method:"switchEthereumChain",params:Object.assign({chainId:e},{address:r})},i=(0,Q.randomBytesHex)(8),s=u=>{this.publishWeb3RequestCanceledEvent(i),this.handleErrorResponse(i,n.method,u)};return{promise:new Promise((u,d)=>{this.relayEventManager.callbacks.set(i,S=>{if((0,Tt.isErrorResponse)(S)&&S.errorCode)return d(Jt.standardErrors.provider.custom({code:S.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if((0,Tt.isErrorResponse)(S))return d(new Error(S.errorMessage));u(S)});const h=S=>{var E;if(S){const M=(E=(0,Jt.getErrorCode)(S))!==null&&E!==void 0?E:Jt.standardErrorCodes.provider.unsupportedChain;this.handleErrorResponse(i,"switchEthereumChain",S instanceof Error?S:Jt.standardErrors.provider.unsupportedChain(e),M)}else this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:i,response:{method:"switchEthereumChain",result:{isApproved:!1,rpcUrl:""}}})},y=S=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:i,response:{method:"switchEthereumChain",result:{isApproved:!0,rpcUrl:S}}})};this.ui.switchEthereumChain({onCancel:h,onApprove:y,chainId:n.params.chainId,address:n.params.address}),!this.ui.inlineSwitchEthereumChain()&&!this.ui.isStandalone()&&this.publishWeb3RequestEvent(i,n)}),cancel:s}}inlineAddEthereumChain(e){return this.ui.inlineAddEthereumChain(e)}getSessionIdHash(){return kt.Session.hash(this._session.id)}sendRequestStandalone(e,r){const n=s=>{this.handleErrorResponse(e,r.method,s)},i=s=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:e,response:s})};switch(r.method){case"signEthereumMessage":this.ui.signEthereumMessage({request:r,onSuccess:i,onCancel:n});break;case"signEthereumTransaction":this.ui.signEthereumTransaction({request:r,onSuccess:i,onCancel:n});break;case"submitEthereumTransaction":this.ui.submitEthereumTransaction({request:r,onSuccess:i,onCancel:n});break;case"ethereumAddressFromSignedMessage":this.ui.ethereumAddressFromSignedMessage({request:r,onSuccess:i});break;default:n();break}}}Cr.WalletLinkRelay=Et;Et.accountRequestCallbackIds=new Set;var xr={},Nn={},Sa={};(function(t){var e=x&&x.__createBinding||(Object.create?function(n,i,s,c){c===void 0&&(c=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,c,u)}:function(n,i,s,c){c===void 0&&(c=s),n[c]=i[s]}),r=x&&x.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(t,"__esModule",{value:!0}),r(Qs,t)})(Sa);var Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});Xs.default=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";var Ma=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nn,"__esModule",{value:!0});Nn.RedirectDialog=void 0;const pu=Ma(Lr),mt=Ke,mu=Nr,vu=Sa,wu=Ma(Xs);class yu{constructor(){this.root=null}attach(){const e=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",e.appendChild(this.root),(0,mu.injectCssReset)()}present(e){this.render(e)}clear(){this.render(null)}render(e){this.root&&((0,mt.render)(null,this.root),e&&(0,mt.render)((0,mt.h)(bu,Object.assign({},e,{onDismiss:()=>{this.clear()}})),this.root))}}Nn.RedirectDialog=yu;const bu=({title:t,buttonText:e,darkMode:r,onButtonClick:n,onDismiss:i})=>{const s=r?"dark":"light";return(0,mt.h)(vu.SnackbarContainer,{darkMode:r},(0,mt.h)("div",{class:"-cbwsdk-redirect-dialog"},(0,mt.h)("style",null,wu.default),(0,mt.h)("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:i}),(0,mt.h)("div",{class:(0,pu.default)("-cbwsdk-redirect-dialog-box",s)},(0,mt.h)("p",null,t),(0,mt.h)("button",{onClick:n},e))))};Object.defineProperty(xr,"__esModule",{value:!0});xr.MobileRelayUI=void 0;const _u=Nn;class Eu{constructor(e){this.attached=!1,this.darkMode=!1,this.redirectDialog=new _u.RedirectDialog,this.darkMode=e.darkMode}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}setConnected(e){}redirectToCoinbaseWallet(e){const r=new URL("https://go.cb-w.com/walletlink");r.searchParams.append("redirect_url",window.location.href),e&&r.searchParams.append("wl_url",e);const n=document.createElement("a");n.target="cbw-opener",n.href=r.href,n.rel="noreferrer noopener",n.click()}openCoinbaseWalletDeeplink(e){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",darkMode:this.darkMode,onButtonClick:()=>{this.redirectToCoinbaseWallet(e)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(e)},99)}showConnecting(e){return()=>{this.redirectDialog.clear()}}hideRequestEthereumAccounts(){this.redirectDialog.clear()}requestEthereumAccounts(){}addEthereumChain(){}watchAsset(){}selectProvider(){}switchEthereumChain(){}signEthereumMessage(){}signEthereumTransaction(){}submitEthereumTransaction(){}ethereumAddressFromSignedMessage(){}reloadUI(){}setStandalone(){}setConnectDisabled(){}inlineAccountsResponse(){return!1}inlineAddEthereumChain(){return!1}inlineWatchAsset(){return!1}inlineSwitchEthereumChain(){return!1}isStandalone(){return!1}}xr.MobileRelayUI=Eu;Object.defineProperty(Ir,"__esModule",{value:!0});Ir.MobileRelay=void 0;const Su=A,Mu=Cr,ku=xr;class Ru extends Mu.WalletLinkRelay{constructor(e){var r;super(e),this._enableMobileWalletLink=(r=e.enableMobileWalletLink)!==null&&r!==void 0?r:!1}requestEthereumAccounts(){return this._enableMobileWalletLink?super.requestEthereumAccounts():{promise:new Promise(()=>{const e=(0,Su.getLocation)();e.href=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(e.href)}`}),cancel:()=>{}}}publishWeb3RequestEvent(e,r){if(super.publishWeb3RequestEvent(e,r),!(this._enableMobileWalletLink&&this.ui instanceof ku.MobileRelayUI))return;let n=!1;switch(r.method){case"requestEthereumAccounts":case"connectAndSignIn":n=!0,this.ui.openCoinbaseWalletDeeplink(this.getQRCodeUrl());break;case"switchEthereumChain":return;default:n=!0,this.ui.openCoinbaseWalletDeeplink();break}n&&window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0})}handleWeb3ResponseMessage(e){super.handleWeb3ResponseMessage(e)}connectAndSignIn(e){if(!this._enableMobileWalletLink)throw new Error("connectAndSignIn is supported only when enableMobileWalletLink is on");return this.sendRequest({method:"connectAndSignIn",params:{appName:this.appName,appLogoUrl:this.appLogoUrl,domain:window.location.hostname,aud:window.location.href,version:"1",type:"eip4361",nonce:e.nonce,iat:new Date().toISOString(),chainId:`eip155:${this.dappDefaultChain}`,statement:e.statement,resources:e.resources}})}}Ir.MobileRelay=Ru;const Iu=Bc,Cu=un;function ka(t){return Buffer.allocUnsafe(t).fill(0)}function Ra(t,e,r){const n=ka(e);return t=Ln(t),r?t.length"u")throw new Error("Not an array?");if(r=La(t),r!=="dynamic"&&r!==0&&e.length>r)throw new Error("Elements exceed array size: "+r);i=[],t=t.slice(0,t.lastIndexOf("[")),typeof e=="string"&&(e=JSON.parse(e));for(s in e)i.push(pt(t,e[s]));if(r==="dynamic"){var c=pt("uint256",e.length);i.unshift(c)}return Buffer.concat(i)}else{if(t==="bytes")return e=new Buffer(e),i=Buffer.concat([pt("uint256",e.length),e]),e.length%32!==0&&(i=Buffer.concat([i,jt.zeros(32-e.length%32)])),i;if(t.startsWith("bytes")){if(r=Yt(t),r<1||r>32)throw new Error("Invalid bytes width: "+r);return jt.setLengthRight(e,32)}else if(t.startsWith("uint")){if(r=Yt(t),r%8||r<8||r>256)throw new Error("Invalid uint width: "+r);if(n=Pt(e),n.bitLength()>r)throw new Error("Supplied uint exceeds width: "+r+" vs "+n.bitLength());if(n<0)throw new Error("Supplied uint is negative");return n.toArrayLike(Buffer,"be",32)}else if(t.startsWith("int")){if(r=Yt(t),r%8||r<8||r>256)throw new Error("Invalid int width: "+r);if(n=Pt(e),n.bitLength()>r)throw new Error("Supplied int exceeds width: "+r+" vs "+n.bitLength());return n.toTwos(256).toArrayLike(Buffer,"be",32)}else if(t.startsWith("ufixed")){if(r=so(t),n=Pt(e),n<0)throw new Error("Supplied ufixed is negative");return pt("uint256",n.mul(new Ot(2).pow(new Ot(r[1]))))}else if(t.startsWith("fixed"))return r=so(t),pt("int256",Pt(e).mul(new Ot(2).pow(new Ot(r[1]))))}throw new Error("Unsupported or invalid type: "+t)}function Tu(t){return t==="string"||t==="bytes"||La(t)==="dynamic"}function Pu(t){return t.lastIndexOf("]")===t.length-1}function $u(t,e){var r=[],n=[],i=32*t.length;for(var s in t){var c=Na(t[s]),u=e[s],d=pt(c,u);Tu(c)?(r.push(pt("uint256",i)),n.push(d),i+=d.length):r.push(d)}return Buffer.concat(r.concat(n))}function xa(t,e){if(t.length!==e.length)throw new Error("Number of types are not matching the values");for(var r,n,i=[],s=0;s32)throw new Error("Invalid bytes width: "+r);i.push(jt.setLengthRight(u,r))}else if(c.startsWith("uint")){if(r=Yt(c),r%8||r<8||r>256)throw new Error("Invalid uint width: "+r);if(n=Pt(u),n.bitLength()>r)throw new Error("Supplied uint exceeds width: "+r+" vs "+n.bitLength());i.push(n.toArrayLike(Buffer,"be",r/8))}else if(c.startsWith("int")){if(r=Yt(c),r%8||r<8||r>256)throw new Error("Invalid int width: "+r);if(n=Pt(u),n.bitLength()>r)throw new Error("Supplied int exceeds width: "+r+" vs "+n.bitLength());i.push(n.toTwos(r).toArrayLike(Buffer,"be",r/8))}else throw new Error("Unsupported or invalid type: "+c)}return Buffer.concat(i)}function Ou(t,e){return jt.keccak(xa(t,e))}var Bu={rawEncode:$u,solidityPack:xa,soliditySHA3:Ou};const lt=Aa,yr=Bu,Ta={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},Ms={encodeData(t,e,r,n=!0){const i=["bytes32"],s=[this.hashType(t,r)];if(n){const c=(u,d,h)=>{if(r[d]!==void 0)return["bytes32",h==null?"0x0000000000000000000000000000000000000000000000000000000000000000":lt.keccak(this.encodeData(d,h,r,n))];if(h===void 0)throw new Error(`missing value for field ${u} of type ${d}`);if(d==="bytes")return["bytes32",lt.keccak(h)];if(d==="string")return typeof h=="string"&&(h=Buffer.from(h,"utf8")),["bytes32",lt.keccak(h)];if(d.lastIndexOf("]")===d.length-1){const y=d.slice(0,d.lastIndexOf("[")),S=h.map(E=>c(u,y,E));return["bytes32",lt.keccak(yr.rawEncode(S.map(([E])=>E),S.map(([,E])=>E)))]}return[d,h]};for(const u of r[t]){const[d,h]=c(u.name,u.type,e[u.name]);i.push(d),s.push(h)}}else for(const c of r[t]){let u=e[c.name];if(u!==void 0)if(c.type==="bytes")i.push("bytes32"),u=lt.keccak(u),s.push(u);else if(c.type==="string")i.push("bytes32"),typeof u=="string"&&(u=Buffer.from(u,"utf8")),u=lt.keccak(u),s.push(u);else if(r[c.type]!==void 0)i.push("bytes32"),u=lt.keccak(this.encodeData(c.type,u,r,n)),s.push(u);else{if(c.type.lastIndexOf("]")===c.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");i.push(c.type),s.push(u)}}return yr.rawEncode(i,s)},encodeType(t,e){let r="",n=this.findTypeDependencies(t,e).filter(i=>i!==t);n=[t].concat(n.sort());for(const i of n){if(!e[i])throw new Error("No type definition specified: "+i);r+=i+"("+e[i].map(({name:c,type:u})=>u+" "+c).join(",")+")"}return r},findTypeDependencies(t,e,r=[]){if(t=t.match(/^\w*/)[0],r.includes(t)||e[t]===void 0)return r;r.push(t);for(const n of e[t])for(const i of this.findTypeDependencies(n.type,e,r))!r.includes(i)&&r.push(i);return r},hashStruct(t,e,r,n=!0){return lt.keccak(this.encodeData(t,e,r,n))},hashType(t,e){return lt.keccak(this.encodeType(t,e))},sanitizeData(t){const e={};for(const r in Ta.properties)t[r]&&(e[r]=t[r]);return e.types&&(e.types=Object.assign({EIP712Domain:[]},e.types)),e},hash(t,e=!0){const r=this.sanitizeData(t),n=[Buffer.from("1901","hex")];return n.push(this.hashStruct("EIP712Domain",r.domain,r.types,e)),r.primaryType!=="EIP712Domain"&&n.push(this.hashStruct(r.primaryType,r.message,r.types,e)),lt.keccak(Buffer.concat(n))}};var Du={TYPED_MESSAGE_SCHEMA:Ta,TypedDataUtils:Ms,hashForSignTypedDataLegacy:function(t){return ju(t.data)},hashForSignTypedData_v3:function(t){return Ms.hash(t.data,!1)},hashForSignTypedData_v4:function(t){return Ms.hash(t.data)}};function ju(t){const e=new Error("Expect argument to be non-empty array");if(typeof t!="object"||!t.length)throw e;const r=t.map(function(s){return s.type==="bytes"?lt.toBuffer(s.value):s.value}),n=t.map(function(s){return s.type}),i=t.map(function(s){if(!s.name)throw e;return s.type+" "+s.name});return yr.soliditySHA3(["bytes32","bytes32"],[yr.soliditySHA3(new Array(t.length).fill("string"),i),yr.soliditySHA3(n,r)])}var ir={};Object.defineProperty(ir,"__esModule",{value:!0});ir.filterFromParam=ir.FilterPolyfill=void 0;const Qt=De,Je=A,Fu=5*60*1e3,$t={jsonrpc:"2.0",id:0};class Hu{constructor(e){this.logFilters=new Map,this.blockFilters=new Set,this.pendingTransactionFilters=new Set,this.cursors=new Map,this.timeouts=new Map,this.nextFilterId=(0,Qt.IntNumber)(1),this.REQUEST_THROTTLE_INTERVAL=1e3,this.lastFetchTimestamp=new Date(0),this.resolvers=[],this.provider=e}async newFilter(e){const r=Pa(e),n=this.makeFilterId(),i=await this.setInitialCursorPosition(n,r.fromBlock);return console.info(`Installing new log filter(${n}):`,r,"initial cursor position:",i),this.logFilters.set(n,r),this.setFilterTimeout(n),(0,Je.hexStringFromIntNumber)(n)}async newBlockFilter(){const e=this.makeFilterId(),r=await this.setInitialCursorPosition(e,"latest");return console.info(`Installing new block filter (${e}) with initial cursor position:`,r),this.blockFilters.add(e),this.setFilterTimeout(e),(0,Je.hexStringFromIntNumber)(e)}async newPendingTransactionFilter(){const e=this.makeFilterId(),r=await this.setInitialCursorPosition(e,"latest");return console.info(`Installing new block filter (${e}) with initial cursor position:`,r),this.pendingTransactionFilters.add(e),this.setFilterTimeout(e),(0,Je.hexStringFromIntNumber)(e)}uninstallFilter(e){const r=(0,Je.intNumberFromHexString)(e);return console.info(`Uninstalling filter (${r})`),this.deleteFilter(r),!0}getFilterChanges(e){const r=(0,Je.intNumberFromHexString)(e);return this.timeouts.has(r)&&this.setFilterTimeout(r),this.logFilters.has(r)?this.getLogFilterChanges(r):this.blockFilters.has(r)?this.getBlockFilterChanges(r):this.pendingTransactionFilters.has(r)?this.getPendingTransactionFilterChanges(r):Promise.resolve(Gr())}async getFilterLogs(e){const r=(0,Je.intNumberFromHexString)(e),n=this.logFilters.get(r);return n?this.sendAsyncPromise(Object.assign(Object.assign({},$t),{method:"eth_getLogs",params:[io(n)]})):Gr()}makeFilterId(){return(0,Qt.IntNumber)(++this.nextFilterId)}sendAsyncPromise(e){return new Promise((r,n)=>{this.provider.sendAsync(e,(i,s)=>{if(i)return n(i);if(Array.isArray(s)||s==null)return n(new Error(`unexpected response received: ${JSON.stringify(s)}`));r(s)})})}deleteFilter(e){console.info(`Deleting filter (${e})`),this.logFilters.delete(e),this.blockFilters.delete(e),this.pendingTransactionFilters.delete(e),this.cursors.delete(e),this.timeouts.delete(e)}async getLogFilterChanges(e){const r=this.logFilters.get(e),n=this.cursors.get(e);if(!n||!r)return Gr();const i=await this.getCurrentBlockHeight(),s=r.toBlock==="latest"?i:r.toBlock;if(n>i||n>Number(r.toBlock))return Zr();console.info(`Fetching logs from ${n} to ${s} for filter ${e}`);const c=await this.sendAsyncPromise(Object.assign(Object.assign({},$t),{method:"eth_getLogs",params:[io(Object.assign(Object.assign({},r),{fromBlock:n,toBlock:s}))]}));if(Array.isArray(c.result)){const u=c.result.map(h=>(0,Je.intNumberFromHexString)(h.blockNumber||"0x0")),d=Math.max(...u);if(d&&d>n){const h=(0,Qt.IntNumber)(d+1);console.info(`Moving cursor position for filter (${e}) from ${n} to ${h}`),this.cursors.set(e,h)}}return c}async getBlockFilterChanges(e){const r=this.cursors.get(e);if(!r)return Gr();const n=await this.getCurrentBlockHeight();if(r>n)return Zr();console.info(`Fetching blocks from ${r} to ${n} for filter (${e})`);const i=(await Promise.all((0,Je.range)(r,n+1).map(c=>this.getBlockHashByNumber((0,Qt.IntNumber)(c))))).filter(c=>!!c),s=(0,Qt.IntNumber)(r+i.length);return console.info(`Moving cursor position for filter (${e}) from ${r} to ${s}`),this.cursors.set(e,s),Object.assign(Object.assign({},$t),{result:i})}async getPendingTransactionFilterChanges(e){return Promise.resolve(Zr())}async setInitialCursorPosition(e,r){const n=await this.getCurrentBlockHeight(),i=typeof r=="number"&&r>n?r:n;return this.cursors.set(e,i),i}setFilterTimeout(e){const r=this.timeouts.get(e);r&&window.clearTimeout(r);const n=window.setTimeout(()=>{console.info(`Filter (${e}) timed out`),this.deleteFilter(e)},Fu);this.timeouts.set(e,n)}async getCurrentBlockHeight(){const e=new Date;if(e.getTime()-this.lastFetchTimestamp.getTime()>this.REQUEST_THROTTLE_INTERVAL){this.lastFetchTimestamp=e;const r=await this._getCurrentBlockHeight();this.currentBlockHeight=r,this.resolvers.forEach(n=>n(r)),this.resolvers=[]}return this.currentBlockHeight?this.currentBlockHeight:new Promise(r=>this.resolvers.push(r))}async _getCurrentBlockHeight(){const{result:e}=await this.sendAsyncPromise(Object.assign(Object.assign({},$t),{method:"eth_blockNumber",params:[]}));return(0,Je.intNumberFromHexString)((0,Je.ensureHexString)(e))}async getBlockHashByNumber(e){const r=await this.sendAsyncPromise(Object.assign(Object.assign({},$t),{method:"eth_getBlockByNumber",params:[(0,Je.hexStringFromIntNumber)(e),!1]}));return r.result&&typeof r.result.hash=="string"?(0,Je.ensureHexString)(r.result.hash):null}}ir.FilterPolyfill=Hu;function Pa(t){return{fromBlock:oo(t.fromBlock),toBlock:oo(t.toBlock),addresses:t.address===void 0?null:Array.isArray(t.address)?t.address:[t.address],topics:t.topics||[]}}ir.filterFromParam=Pa;function io(t){const e={fromBlock:ao(t.fromBlock),toBlock:ao(t.toBlock),topics:t.topics};return t.addresses!==null&&(e.address=t.addresses),e}function oo(t){if(t===void 0||t==="latest"||t==="pending")return"latest";if(t==="earliest")return(0,Qt.IntNumber)(0);if((0,Je.isHexString)(t))return(0,Je.intNumberFromHexString)(t);throw new Error(`Invalid block option: ${String(t)}`)}function ao(t){return t==="latest"?t:(0,Je.hexStringFromIntNumber)(t)}function Gr(){return Object.assign(Object.assign({},$t),{error:{code:-32e3,message:"filter not found"}})}function Zr(){return Object.assign(Object.assign({},$t),{result:[]})}var xn={},$a={},Tn={},Ys=Uu;function Uu(t){t=t||{};var e=t.max||Number.MAX_SAFE_INTEGER,r=typeof t.start<"u"?t.start:Math.floor(Math.random()*e);return function(){return r=r%e,r++}}const co=(t,e)=>function(){const r=e.promiseModule,n=new Array(arguments.length);for(let i=0;i{e.errorFirst?n.push(function(c,u){if(e.multiArgs){const d=new Array(arguments.length-1);for(let h=1;h{e=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},e);const r=i=>{const s=c=>typeof c=="string"?i===c:c.test(i);return e.include?e.include.some(s):!e.exclude.some(s)};let n;typeof t=="function"?n=function(){return e.excludeMain?t.apply(this,arguments):co(t,e).apply(this,arguments)}:n=Object.create(Object.getPrototypeOf(t));for(const i in t){const s=t[i];n[i]=typeof s=="function"&&r(i)?co(s,e):s}return n},Tr={},Pr={};Object.defineProperty(Pr,"__esModule",{value:!0});const Wu=ta;function lo(t,e,r){try{Reflect.apply(t,e,r)}catch(n){setTimeout(()=>{throw n})}}function zu(t){const e=t.length,r=new Array(e);for(let n=0;n0&&([c]=r),c instanceof Error)throw c;const u=new Error(`Unhandled error.${c?` (${c.message})`:""}`);throw u.context=c,u}const s=i[e];if(s===void 0)return!1;if(typeof s=="function")lo(s,this,r);else{const c=s.length,u=zu(s);for(let d=0;dt+e,uo=["sync","latest"];class Ku extends Gu.default{constructor(e){super(),this._blockResetDuration=e.blockResetDuration||20*Zu,this._usePastBlocks=e.usePastBlocks||!1,this._currentBlock=null,this._isRunning=!1,this._onNewListener=this._onNewListener.bind(this),this._onRemoveListener=this._onRemoveListener.bind(this),this._resetCurrentBlock=this._resetCurrentBlock.bind(this),this._setupInternalEvents()}async destroy(){this._cancelBlockResetTimeout(),await this._maybeEnd(),super.removeAllListeners()}isRunning(){return this._isRunning}getCurrentBlock(){return this._currentBlock}async getLatestBlock(){return this._currentBlock?this._currentBlock:await new Promise(r=>this.once("latest",r))}removeAllListeners(e){return e?super.removeAllListeners(e):super.removeAllListeners(),this._setupInternalEvents(),this._onRemoveListener(),this}_setupInternalEvents(){this.removeListener("newListener",this._onNewListener),this.removeListener("removeListener",this._onRemoveListener),this.on("newListener",this._onNewListener),this.on("removeListener",this._onRemoveListener)}_onNewListener(e){uo.includes(e)&&this._maybeStart()}_onRemoveListener(){this._getBlockTrackerEventCount()>0||this._maybeEnd()}async _maybeStart(){this._isRunning||(this._isRunning=!0,this._cancelBlockResetTimeout(),await this._start(),this.emit("_started"))}async _maybeEnd(){this._isRunning&&(this._isRunning=!1,this._setupBlockResetTimeout(),await this._end(),this.emit("_ended"))}_getBlockTrackerEventCount(){return uo.map(e=>this.listenerCount(e)).reduce(Qu)}_shouldUseNewBlock(e){const r=this._currentBlock;if(!r)return!0;const n=ho(e),i=ho(r);return this._usePastBlocks&&ni}_newPotentialLatest(e){this._shouldUseNewBlock(e)&&this._setCurrentBlock(e)}_setCurrentBlock(e){const r=this._currentBlock;this._currentBlock=e,this.emit("latest",e),this.emit("sync",{oldBlock:r,newBlock:e})}_setupBlockResetTimeout(){this._cancelBlockResetTimeout(),this._blockResetTimeout=setTimeout(this._resetCurrentBlock,this._blockResetDuration),this._blockResetTimeout.unref&&this._blockResetTimeout.unref()}_cancelBlockResetTimeout(){this._blockResetTimeout&&clearTimeout(this._blockResetTimeout)}_resetCurrentBlock(){this._currentBlock=null}}Tr.BaseBlockTracker=Ku;function ho(t){return Number.parseInt(t,16)}var Oa={},Ba={},Ve={};class Da extends TypeError{constructor(e,r){let n;const{message:i,explanation:s,...c}=e,{path:u}=e,d=u.length===0?i:`At path: ${u.join(".")} -- ${i}`;super(s??d),s!=null&&(this.cause=d),Object.assign(this,c),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...r()])}}function Xu(t){return at(t)&&typeof t[Symbol.iterator]=="function"}function at(t){return typeof t=="object"&&t!=null}function fo(t){if(Object.prototype.toString.call(t)!=="[object Object]")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function je(t){return typeof t=="symbol"?t.toString():typeof t=="string"?JSON.stringify(t):`${t}`}function Yu(t){const{done:e,value:r}=t.next();return e?void 0:r}function ed(t,e,r,n){if(t===!0)return;t===!1?t={}:typeof t=="string"&&(t={message:t});const{path:i,branch:s}=e,{type:c}=r,{refinement:u,message:d=`Expected a value of type \`${c}\`${u?` with refinement \`${u}\``:""}, but received: \`${je(n)}\``}=t;return{value:n,type:c,refinement:u,key:i[i.length-1],path:i,branch:s,...t,message:d}}function*Os(t,e,r,n){Xu(t)||(t=[t]);for(const i of t){const s=ed(i,e,r,n);s&&(yield s)}}function*ei(t,e,r={}){const{path:n=[],branch:i=[t],coerce:s=!1,mask:c=!1}=r,u={path:n,branch:i};if(s&&(t=e.coercer(t,u),c&&e.type!=="type"&&at(e.schema)&&at(t)&&!Array.isArray(t)))for(const h in t)e.schema[h]===void 0&&delete t[h];let d="valid";for(const h of e.validator(t,u))h.explanation=r.message,d="not_valid",yield[h,void 0];for(let[h,y,S]of e.entries(t,u)){const E=ei(y,S,{path:h===void 0?n:[...n,h],branch:h===void 0?i:[...i,y],coerce:s,mask:c,message:r.message});for(const M of E)M[0]?(d=M[0].refinement!=null?"not_refined":"not_valid",yield[M[0],void 0]):s&&(y=M[1],h===void 0?t=y:t instanceof Map?t.set(h,y):t instanceof Set?t.add(y):at(t)&&(y!==void 0||h in t)&&(t[h]=y))}if(d!=="not_valid")for(const h of e.refiner(t,u))h.explanation=r.message,d="not_refined",yield[h,void 0];d==="valid"&&(yield[void 0,t])}class ee{constructor(e){const{type:r,schema:n,validator:i,refiner:s,coercer:c=d=>d,entries:u=function*(){}}=e;this.type=r,this.schema=n,this.entries=u,this.coercer=c,i?this.validator=(d,h)=>{const y=i(d,h);return Os(y,h,this,d)}:this.validator=()=>[],s?this.refiner=(d,h)=>{const y=s(d,h);return Os(y,h,this,d)}:this.refiner=()=>[]}assert(e,r){return ja(e,this,r)}create(e,r){return Fa(e,this,r)}is(e){return ti(e,this)}mask(e,r){return Ha(e,this,r)}validate(e,r={}){return hr(e,this,r)}}function ja(t,e,r){const n=hr(t,e,{message:r});if(n[0])throw n[0]}function Fa(t,e,r){const n=hr(t,e,{coerce:!0,message:r});if(n[0])throw n[0];return n[1]}function Ha(t,e,r){const n=hr(t,e,{coerce:!0,mask:!0,message:r});if(n[0])throw n[0];return n[1]}function ti(t,e){return!hr(t,e)[0]}function hr(t,e,r={}){const n=ei(t,e,r),i=Yu(n);return i[0]?[new Da(i[0],function*(){for(const c of n)c[0]&&(yield c[0])}),void 0]:[void 0,i[1]]}function td(...t){const e=t[0].type==="type",r=t.map(i=>i.schema),n=Object.assign({},...r);return e?Or(n):$r(n)}function Xe(t,e){return new ee({type:t,schema:null,validator:e})}function rd(t,e){return new ee({...t,refiner:(r,n)=>r===void 0||t.refiner(r,n),validator(r,n){return r===void 0?!0:(e(r,n),t.validator(r,n))}})}function nd(t){return new ee({type:"dynamic",schema:null,*entries(e,r){yield*t(e,r).entries(e,r)},validator(e,r){return t(e,r).validator(e,r)},coercer(e,r){return t(e,r).coercer(e,r)},refiner(e,r){return t(e,r).refiner(e,r)}})}function sd(t){let e;return new ee({type:"lazy",schema:null,*entries(r,n){e??(e=t()),yield*e.entries(r,n)},validator(r,n){return e??(e=t()),e.validator(r,n)},coercer(r,n){return e??(e=t()),e.coercer(r,n)},refiner(r,n){return e??(e=t()),e.refiner(r,n)}})}function id(t,e){const{schema:r}=t,n={...r};for(const i of e)delete n[i];switch(t.type){case"type":return Or(n);default:return $r(n)}}function od(t){const e=t instanceof ee,r=e?{...t.schema}:{...t};for(const n in r)r[n]=Ua(r[n]);return e&&t.type==="type"?Or(r):$r(r)}function ad(t,e){const{schema:r}=t,n={};for(const i of e)n[i]=r[i];switch(t.type){case"type":return Or(n);default:return $r(n)}}function cd(t,e){return console.warn("superstruct@0.11 - The `struct` helper has been renamed to `define`."),Xe(t,e)}function ld(){return Xe("any",()=>!0)}function ud(t){return new ee({type:"array",schema:t,*entries(e){if(t&&Array.isArray(e))for(const[r,n]of e.entries())yield[r,n,t]},coercer(e){return Array.isArray(e)?e.slice():e},validator(e){return Array.isArray(e)||`Expected an array value, but received: ${je(e)}`}})}function dd(){return Xe("bigint",t=>typeof t=="bigint")}function hd(){return Xe("boolean",t=>typeof t=="boolean")}function fd(){return Xe("date",t=>t instanceof Date&&!isNaN(t.getTime())||`Expected a valid \`Date\` object, but received: ${je(t)}`)}function gd(t){const e={},r=t.map(n=>je(n)).join();for(const n of t)e[n]=n;return new ee({type:"enums",schema:e,validator(n){return t.includes(n)||`Expected one of \`${r}\`, but received: ${je(n)}`}})}function pd(){return Xe("func",t=>typeof t=="function"||`Expected a function, but received: ${je(t)}`)}function md(t){return Xe("instance",e=>e instanceof t||`Expected a \`${t.name}\` instance, but received: ${je(e)}`)}function vd(){return Xe("integer",t=>typeof t=="number"&&!isNaN(t)&&Number.isInteger(t)||`Expected an integer, but received: ${je(t)}`)}function wd(t){return new ee({type:"intersection",schema:null,*entries(e,r){for(const n of t)yield*n.entries(e,r)},*validator(e,r){for(const n of t)yield*n.validator(e,r)},*refiner(e,r){for(const n of t)yield*n.refiner(e,r)}})}function yd(t){const e=je(t),r=typeof t;return new ee({type:"literal",schema:r==="string"||r==="number"||r==="boolean"?t:null,validator(n){return n===t||`Expected the literal \`${e}\`, but received: ${je(n)}`}})}function bd(t,e){return new ee({type:"map",schema:null,*entries(r){if(t&&e&&r instanceof Map)for(const[n,i]of r.entries())yield[n,n,t],yield[n,i,e]},coercer(r){return r instanceof Map?new Map(r):r},validator(r){return r instanceof Map||`Expected a \`Map\` object, but received: ${je(r)}`}})}function ri(){return Xe("never",()=>!1)}function _d(t){return new ee({...t,validator:(e,r)=>e===null||t.validator(e,r),refiner:(e,r)=>e===null||t.refiner(e,r)})}function Ed(){return Xe("number",t=>typeof t=="number"&&!isNaN(t)||`Expected a number, but received: ${je(t)}`)}function $r(t){const e=t?Object.keys(t):[],r=ri();return new ee({type:"object",schema:t||null,*entries(n){if(t&&at(n)){const i=new Set(Object.keys(n));for(const s of e)i.delete(s),yield[s,n[s],t[s]];for(const s of i)yield[s,n[s],r]}},validator(n){return at(n)||`Expected an object, but received: ${je(n)}`},coercer(n){return at(n)?{...n}:n}})}function Ua(t){return new ee({...t,validator:(e,r)=>e===void 0||t.validator(e,r),refiner:(e,r)=>e===void 0||t.refiner(e,r)})}function Sd(t,e){return new ee({type:"record",schema:null,*entries(r){if(at(r))for(const n in r){const i=r[n];yield[n,n,t],yield[n,i,e]}},validator(r){return at(r)||`Expected an object, but received: ${je(r)}`}})}function Md(){return Xe("regexp",t=>t instanceof RegExp)}function kd(t){return new ee({type:"set",schema:null,*entries(e){if(t&&e instanceof Set)for(const r of e)yield[r,r,t]},coercer(e){return e instanceof Set?new Set(e):e},validator(e){return e instanceof Set||`Expected a \`Set\` object, but received: ${je(e)}`}})}function Va(){return Xe("string",t=>typeof t=="string"||`Expected a string, but received: ${je(t)}`)}function Rd(t){const e=ri();return new ee({type:"tuple",schema:null,*entries(r){if(Array.isArray(r)){const n=Math.max(t.length,r.length);for(let i=0;ir.type).join(" | ");return new ee({type:"union",schema:null,coercer(r){for(const n of t){const[i,s]=n.validate(r,{coerce:!0});if(!i)return s}return r},validator(r,n){const i=[];for(const s of t){const[...c]=ei(r,s,n),[u]=c;if(u[0])for(const[d]of c)d&&i.push(d);else return[]}return[`Expected the value to satisfy a union of \`${e}\`, but received: ${je(r)}`,...i]}})}function Wa(){return Xe("unknown",()=>!0)}function ni(t,e,r){return new ee({...t,coercer:(n,i)=>ti(n,e)?t.coercer(r(n,i),i):t.coercer(n,i)})}function Cd(t,e,r={}){return ni(t,Wa(),n=>{const i=typeof e=="function"?e():e;if(n===void 0)return i;if(!r.strict&&fo(n)&&fo(i)){const s={...n};let c=!1;for(const u in i)s[u]===void 0&&(s[u]=i[u],c=!0);if(c)return s}return n})}function Ad(t){return ni(t,Va(),e=>e.trim())}function Nd(t){return Ut(t,"empty",e=>{const r=za(e);return r===0||`Expected an empty ${t.type} but received one with a size of \`${r}\``})}function za(t){return t instanceof Map||t instanceof Set?t.size:t.length}function Ld(t,e,r={}){const{exclusive:n}=r;return Ut(t,"max",i=>n?in?i>e:i>=e||`Expected a ${t.type} greater than ${n?"":"or equal to "}${e} but received \`${i}\``)}function Td(t){return Ut(t,"nonempty",e=>za(e)>0||`Expected a nonempty ${t.type} but received an empty one`)}function Pd(t,e){return Ut(t,"pattern",r=>e.test(r)||`Expected a ${t.type} matching \`/${e.source}/\` but received "${r}"`)}function $d(t,e,r=e){const n=`Expected a ${t.type}`,i=e===r?`of \`${e}\``:`between \`${e}\` and \`${r}\``;return Ut(t,"size",s=>{if(typeof s=="number"||s instanceof Date)return e<=s&&s<=r||`${n} ${i} but received \`${s}\``;if(s instanceof Map||s instanceof Set){const{size:c}=s;return e<=c&&c<=r||`${n} with a size ${i} but received one with a size of \`${c}\``}else{const{length:c}=s;return e<=c&&c<=r||`${n} with a length ${i} but received one with a length of \`${c}\``}})}function Ut(t,e,r){return new ee({...t,*refiner(n,i){yield*t.refiner(n,i);const s=r(n,i),c=Os(s,i,t,n);for(const u of c)yield{...u,refinement:e}}})}const Od=Object.freeze(Object.defineProperty({__proto__:null,Struct:ee,StructError:Da,any:ld,array:ud,assert:ja,assign:td,bigint:dd,boolean:hd,coerce:ni,create:Fa,date:fd,defaulted:Cd,define:Xe,deprecated:rd,dynamic:nd,empty:Nd,enums:gd,func:pd,instance:md,integer:vd,intersection:wd,is:ti,lazy:sd,literal:yd,map:bd,mask:Ha,max:Ld,min:xd,never:ri,nonempty:Td,nullable:_d,number:Ed,object:$r,omit:id,optional:Ua,partial:od,pattern:Pd,pick:ad,record:Sd,refine:Ut,regexp:Md,set:kd,size:$d,string:Va,struct:cd,trimmed:Ad,tuple:Rd,type:Or,union:Id,unknown:Wa,validate:hr},Symbol.toStringTag,{value:"Module"})),Vt=Hs(Od);Object.defineProperty(Ve,"__esModule",{value:!0});Ve.assertExhaustive=Ve.assertStruct=Ve.assert=Ve.AssertionError=void 0;const Bd=Vt;function Dd(t){return typeof t=="object"&&t!==null&&"message"in t}function jd(t){var e,r;return typeof((r=(e=t==null?void 0:t.prototype)===null||e===void 0?void 0:e.constructor)===null||r===void 0?void 0:r.name)=="string"}function Fd(t){const e=Dd(t)?t.message:String(t);return e.endsWith(".")?e.slice(0,-1):e}function qa(t,e){return jd(t)?new t({message:e}):t({message:e})}class si extends Error{constructor(e){super(e.message),this.code="ERR_ASSERTION"}}Ve.AssertionError=si;function Hd(t,e="Assertion failed.",r=si){if(!t)throw e instanceof Error?e:qa(r,e)}Ve.assert=Hd;function Ud(t,e,r="Assertion failed",n=si){try{(0,Bd.assert)(t,e)}catch(i){throw qa(n,`${r}: ${Fd(i)}.`)}}Ve.assertStruct=Ud;function Vd(t){throw new Error("Invalid branch reached. Should be detected during compilation.")}Ve.assertExhaustive=Vd;var Br={};Object.defineProperty(Br,"__esModule",{value:!0});Br.base64=void 0;const Wd=Vt,zd=Ve,qd=(t,e={})=>{var r,n;const i=(r=e.paddingRequired)!==null&&r!==void 0?r:!1,s=(n=e.characterSet)!==null&&n!==void 0?n:"base64";let c;s==="base64"?c=String.raw`[A-Za-z0-9+\/]`:((0,zd.assert)(s==="base64url"),c=String.raw`[-_A-Za-z0-9]`);let u;return i?u=new RegExp(`^(?:${c}{4})*(?:${c}{3}=|${c}{2}==)?$`,"u"):u=new RegExp(`^(?:${c}{4})*(?:${c}{2,3}|${c}{3}=|${c}{2}==)?$`,"u"),(0,Wd.pattern)(t,u)};Br.base64=qd;var W={},Dr={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.remove0x=t.add0x=t.assertIsStrictHexString=t.assertIsHexString=t.isStrictHexString=t.isHexString=t.StrictHexStruct=t.HexStruct=void 0;const e=Vt,r=Ve;t.HexStruct=(0,e.pattern)((0,e.string)(),/^(?:0x)?[0-9a-f]+$/iu),t.StrictHexStruct=(0,e.pattern)((0,e.string)(),/^0x[0-9a-f]+$/iu);function n(h){return(0,e.is)(h,t.HexStruct)}t.isHexString=n;function i(h){return(0,e.is)(h,t.StrictHexStruct)}t.isStrictHexString=i;function s(h){(0,r.assert)(n(h),"Value must be a hexadecimal string.")}t.assertIsHexString=s;function c(h){(0,r.assert)(i(h),'Value must be a hexadecimal string, starting with "0x".')}t.assertIsStrictHexString=c;function u(h){return h.startsWith("0x")?h:h.startsWith("0X")?`0x${h.substring(2)}`:`0x${h}`}t.add0x=u;function d(h){return h.startsWith("0x")||h.startsWith("0X")?h.substring(2):h}t.remove0x=d})(Dr);Object.defineProperty(W,"__esModule",{value:!0});W.createDataView=W.concatBytes=W.valueToBytes=W.stringToBytes=W.numberToBytes=W.signedBigIntToBytes=W.bigIntToBytes=W.hexToBytes=W.bytesToString=W.bytesToNumber=W.bytesToSignedBigInt=W.bytesToBigInt=W.bytesToHex=W.assertIsBytes=W.isBytes=void 0;const tt=Ve,Bs=Dr,go=48,po=58,mo=87;function Jd(){const t=[];return()=>{if(t.length===0)for(let e=0;e<256;e++)t.push(e.toString(16).padStart(2,"0"));return t}}const Gd=Jd();function ii(t){return t instanceof Uint8Array}W.isBytes=ii;function fr(t){(0,tt.assert)(ii(t),"Value must be a Uint8Array.")}W.assertIsBytes=fr;function Ja(t){if(fr(t),t.length===0)return"0x";const e=Gd(),r=new Array(t.length);for(let n=0;n=BigInt(0),"Value must be a non-negative bigint.");const e=t.toString(16);return Pn(e)}W.bigIntToBytes=Za;function Xd(t,e){(0,tt.assert)(e>0);const r=t>>BigInt(31);return!((~t&r)+(t&~r)>>BigInt(e*8+-1))}function Yd(t,e){(0,tt.assert)(typeof t=="bigint","Value must be a bigint."),(0,tt.assert)(typeof e=="number","Byte length must be a number."),(0,tt.assert)(e>0,"Byte length must be greater than 0."),(0,tt.assert)(Xd(t,e),"Byte length is too small to represent the given value.");let r=t;const n=new Uint8Array(e);for(let i=0;i>=BigInt(8);return n.reverse()}W.signedBigIntToBytes=Yd;function Qa(t){(0,tt.assert)(typeof t=="number","Value must be a number."),(0,tt.assert)(t>=0,"Value must be a non-negative number."),(0,tt.assert)(Number.isSafeInteger(t),"Value is not a safe integer. Use `bigIntToBytes` instead.");const e=t.toString(16);return Pn(e)}W.numberToBytes=Qa;function Ka(t){return(0,tt.assert)(typeof t=="string","Value must be a string."),new TextEncoder().encode(t)}W.stringToBytes=Ka;function Xa(t){if(typeof t=="bigint")return Za(t);if(typeof t=="number")return Qa(t);if(typeof t=="string")return t.startsWith("0x")?Pn(t):Ka(t);if(ii(t))return t;throw new TypeError(`Unsupported value type: "${typeof t}".`)}W.valueToBytes=Xa;function eh(t){const e=new Array(t.length);let r=0;for(let i=0;ie.call(r,n,i,this))}get(e){return Ge(this,ct,"f").get(e)}has(e){return Ge(this,ct,"f").has(e)}keys(){return Ge(this,ct,"f").keys()}values(){return Ge(this,ct,"f").values()}toString(){return`FrozenMap(${this.size}) {${this.size>0?` ${[...this.entries()].map(([e,r])=>`${String(e)} => ${String(r)}`).join(", ")} `:""}}`}}or.FrozenMap=oi;class ai{constructor(e){ft.set(this,void 0),tc(this,ft,new Set(e),"f"),Object.freeze(this)}get size(){return Ge(this,ft,"f").size}[(ft=new WeakMap,Symbol.iterator)](){return Ge(this,ft,"f")[Symbol.iterator]()}entries(){return Ge(this,ft,"f").entries()}forEach(e,r){return Ge(this,ft,"f").forEach((n,i,s)=>e.call(r,n,i,this))}has(e){return Ge(this,ft,"f").has(e)}keys(){return Ge(this,ft,"f").keys()}values(){return Ge(this,ft,"f").values()}toString(){return`FrozenSet(${this.size}) {${this.size>0?` ${[...this.values()].map(e=>String(e)).join(", ")} `:""}}`}}or.FrozenSet=ai;Object.freeze(oi);Object.freeze(oi.prototype);Object.freeze(ai);Object.freeze(ai.prototype);var rc={};Object.defineProperty(rc,"__esModule",{value:!0});var nc={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.getJsonRpcIdValidator=t.assertIsJsonRpcError=t.isJsonRpcError=t.assertIsJsonRpcFailure=t.isJsonRpcFailure=t.assertIsJsonRpcSuccess=t.isJsonRpcSuccess=t.assertIsJsonRpcResponse=t.isJsonRpcResponse=t.assertIsPendingJsonRpcResponse=t.isPendingJsonRpcResponse=t.JsonRpcResponseStruct=t.JsonRpcFailureStruct=t.JsonRpcSuccessStruct=t.PendingJsonRpcResponseStruct=t.assertIsJsonRpcRequest=t.isJsonRpcRequest=t.assertIsJsonRpcNotification=t.isJsonRpcNotification=t.JsonRpcNotificationStruct=t.JsonRpcRequestStruct=t.JsonRpcParamsStruct=t.JsonRpcErrorStruct=t.JsonRpcIdStruct=t.JsonRpcVersionStruct=t.jsonrpc2=t.getJsonSize=t.isValidJson=t.JsonStruct=t.UnsafeJsonStruct=void 0;const e=Vt,r=Ve,n=()=>(0,e.define)("finite number",C=>(0,e.is)(C,(0,e.number)())&&Number.isFinite(C));t.UnsafeJsonStruct=(0,e.union)([(0,e.literal)(null),(0,e.boolean)(),n(),(0,e.string)(),(0,e.array)((0,e.lazy)(()=>t.UnsafeJsonStruct)),(0,e.record)((0,e.string)(),(0,e.lazy)(()=>t.UnsafeJsonStruct))]),t.JsonStruct=(0,e.define)("Json",(C,P)=>{function J(We,Qe){const H=[...Qe.validator(We,P)];return H.length>0?H:!0}try{const We=J(C,t.UnsafeJsonStruct);return We!==!0?We:J(JSON.parse(JSON.stringify(C)),t.UnsafeJsonStruct)}catch(We){return We instanceof RangeError?"Circular reference detected":!1}});function i(C){return(0,e.is)(C,t.JsonStruct)}t.isValidJson=i;function s(C){(0,r.assertStruct)(C,t.JsonStruct,"Invalid JSON value");const P=JSON.stringify(C);return new TextEncoder().encode(P).byteLength}t.getJsonSize=s,t.jsonrpc2="2.0",t.JsonRpcVersionStruct=(0,e.literal)(t.jsonrpc2),t.JsonRpcIdStruct=(0,e.nullable)((0,e.union)([(0,e.number)(),(0,e.string)()])),t.JsonRpcErrorStruct=(0,e.object)({code:(0,e.integer)(),message:(0,e.string)(),data:(0,e.optional)(t.JsonStruct),stack:(0,e.optional)((0,e.string)())}),t.JsonRpcParamsStruct=(0,e.optional)((0,e.union)([(0,e.record)((0,e.string)(),t.JsonStruct),(0,e.array)(t.JsonStruct)])),t.JsonRpcRequestStruct=(0,e.object)({id:t.JsonRpcIdStruct,jsonrpc:t.JsonRpcVersionStruct,method:(0,e.string)(),params:t.JsonRpcParamsStruct}),t.JsonRpcNotificationStruct=(0,e.omit)(t.JsonRpcRequestStruct,["id"]);function c(C){return(0,e.is)(C,t.JsonRpcNotificationStruct)}t.isJsonRpcNotification=c;function u(C,P){(0,r.assertStruct)(C,t.JsonRpcNotificationStruct,"Invalid JSON-RPC notification",P)}t.assertIsJsonRpcNotification=u;function d(C){return(0,e.is)(C,t.JsonRpcRequestStruct)}t.isJsonRpcRequest=d;function h(C,P){(0,r.assertStruct)(C,t.JsonRpcRequestStruct,"Invalid JSON-RPC request",P)}t.assertIsJsonRpcRequest=h,t.PendingJsonRpcResponseStruct=(0,e.object)({id:t.JsonRpcIdStruct,jsonrpc:t.JsonRpcVersionStruct,result:(0,e.optional)((0,e.unknown)()),error:(0,e.optional)(t.JsonRpcErrorStruct)}),t.JsonRpcSuccessStruct=(0,e.object)({id:t.JsonRpcIdStruct,jsonrpc:t.JsonRpcVersionStruct,result:t.JsonStruct}),t.JsonRpcFailureStruct=(0,e.object)({id:t.JsonRpcIdStruct,jsonrpc:t.JsonRpcVersionStruct,error:t.JsonRpcErrorStruct}),t.JsonRpcResponseStruct=(0,e.union)([t.JsonRpcSuccessStruct,t.JsonRpcFailureStruct]);function y(C){return(0,e.is)(C,t.PendingJsonRpcResponseStruct)}t.isPendingJsonRpcResponse=y;function S(C,P){(0,r.assertStruct)(C,t.PendingJsonRpcResponseStruct,"Invalid pending JSON-RPC response",P)}t.assertIsPendingJsonRpcResponse=S;function E(C){return(0,e.is)(C,t.JsonRpcResponseStruct)}t.isJsonRpcResponse=E;function M(C,P){(0,r.assertStruct)(C,t.JsonRpcResponseStruct,"Invalid JSON-RPC response",P)}t.assertIsJsonRpcResponse=M;function k(C){return(0,e.is)(C,t.JsonRpcSuccessStruct)}t.isJsonRpcSuccess=k;function T(C,P){(0,r.assertStruct)(C,t.JsonRpcSuccessStruct,"Invalid JSON-RPC success response",P)}t.assertIsJsonRpcSuccess=T;function O(C){return(0,e.is)(C,t.JsonRpcFailureStruct)}t.isJsonRpcFailure=O;function B(C,P){(0,r.assertStruct)(C,t.JsonRpcFailureStruct,"Invalid JSON-RPC failure response",P)}t.assertIsJsonRpcFailure=B;function L(C){return(0,e.is)(C,t.JsonRpcErrorStruct)}t.isJsonRpcError=L;function R(C,P){(0,r.assertStruct)(C,t.JsonRpcErrorStruct,"Invalid JSON-RPC error",P)}t.assertIsJsonRpcError=R;function z(C){const{permitEmptyString:P,permitFractions:J,permitNull:We}=Object.assign({permitEmptyString:!0,permitFractions:!1,permitNull:!0},C);return Y=>!!(typeof Y=="number"&&(J||Number.isInteger(Y))||typeof Y=="string"&&(P||Y.length>0)||We&&Y===null)}t.getJsonRpcIdValidator=z})(nc);var sc={};Object.defineProperty(sc,"__esModule",{value:!0});var ar={},hh=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ar,"__esModule",{value:!0});ar.createModuleLogger=ar.createProjectLogger=void 0;const fh=hh(xc),gh=(0,fh.default)("metamask");function ph(t){return gh.extend(t)}ar.createProjectLogger=ph;function mh(t,e){return t.extend(e)}ar.createModuleLogger=mh;var ic={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.calculateNumberSize=t.calculateStringSize=t.isASCII=t.isPlainObject=t.ESCAPE_CHARACTERS_REGEXP=t.JsonSize=t.hasProperty=t.isObject=t.isNullOrUndefined=t.isNonEmptyArray=void 0;function e(h){return Array.isArray(h)&&h.length>0}t.isNonEmptyArray=e;function r(h){return h==null}t.isNullOrUndefined=r;function n(h){return!!h&&typeof h=="object"&&!Array.isArray(h)}t.isObject=n;const i=(h,y)=>Object.hasOwnProperty.call(h,y);t.hasProperty=i,function(h){h[h.Null=4]="Null",h[h.Comma=1]="Comma",h[h.Wrapper=1]="Wrapper",h[h.True=4]="True",h[h.False=5]="False",h[h.Quote=1]="Quote",h[h.Colon=1]="Colon",h[h.Date=24]="Date"}(t.JsonSize||(t.JsonSize={})),t.ESCAPE_CHARACTERS_REGEXP=/"|\\|\n|\r|\t/gu;function s(h){if(typeof h!="object"||h===null)return!1;try{let y=h;for(;Object.getPrototypeOf(y)!==null;)y=Object.getPrototypeOf(y);return Object.getPrototypeOf(h)===y}catch{return!1}}t.isPlainObject=s;function c(h){return h.charCodeAt(0)<=127}t.isASCII=c;function u(h){var y;return h.split("").reduce((E,M)=>c(M)?E+1:E+2,0)+((y=h.match(t.ESCAPE_CHARACTERS_REGEXP))!==null&&y!==void 0?y:[]).length}t.calculateStringSize=u;function d(h){return h.toString().length}t.calculateNumberSize=d})(ic);var bt={};Object.defineProperty(bt,"__esModule",{value:!0});bt.hexToBigInt=bt.hexToNumber=bt.bigIntToHex=bt.numberToHex=void 0;const er=Ve,_r=Dr,vh=t=>((0,er.assert)(typeof t=="number","Value must be a number."),(0,er.assert)(t>=0,"Value must be a non-negative number."),(0,er.assert)(Number.isSafeInteger(t),"Value is not a safe integer. Use `bigIntToHex` instead."),(0,_r.add0x)(t.toString(16)));bt.numberToHex=vh;const wh=t=>((0,er.assert)(typeof t=="bigint","Value must be a bigint."),(0,er.assert)(t>=0,"Value must be a non-negative bigint."),(0,_r.add0x)(t.toString(16)));bt.bigIntToHex=wh;const yh=t=>{(0,_r.assertIsHexString)(t);const e=parseInt(t,16);return(0,er.assert)(Number.isSafeInteger(e),"Value is not a safe integer. Use `hexToBigInt` instead."),e};bt.hexToNumber=yh;const bh=t=>((0,_r.assertIsHexString)(t),BigInt((0,_r.add0x)(t)));bt.hexToBigInt=bh;var oc={};Object.defineProperty(oc,"__esModule",{value:!0});var ac={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.timeSince=t.inMilliseconds=t.Duration=void 0,function(s){s[s.Millisecond=1]="Millisecond",s[s.Second=1e3]="Second",s[s.Minute=6e4]="Minute",s[s.Hour=36e5]="Hour",s[s.Day=864e5]="Day",s[s.Week=6048e5]="Week",s[s.Year=31536e6]="Year"}(t.Duration||(t.Duration={}));const e=s=>Number.isInteger(s)&&s>=0,r=(s,c)=>{if(!e(s))throw new Error(`"${c}" must be a non-negative integer. Received: "${s}".`)};function n(s,c){return r(s,"count"),s*c}t.inMilliseconds=n;function i(s){return r(s,"timestamp"),Date.now()-s}t.timeSince=i})(ac);var cc={};Object.defineProperty(cc,"__esModule",{value:!0});var lc={},Ds={exports:{}};const _h="2.0.0",uc=256,Eh=Number.MAX_SAFE_INTEGER||9007199254740991,Sh=16,Mh=uc-6,kh=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var Bn={MAX_LENGTH:uc,MAX_SAFE_COMPONENT_LENGTH:Sh,MAX_SAFE_BUILD_LENGTH:Mh,MAX_SAFE_INTEGER:Eh,RELEASE_TYPES:kh,SEMVER_SPEC_VERSION:_h,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},ks={};const Rh=typeof process=="object"&&ks&&ks.NODE_DEBUG&&/\bsemver\b/i.test(ks.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};var Dn=Rh;(function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:i}=Bn,s=Dn;e=t.exports={};const c=e.re=[],u=e.safeRe=[],d=e.src=[],h=e.t={};let y=0;const S="[a-zA-Z0-9-]",E=[["\\s",1],["\\d",i],[S,n]],M=T=>{for(const[O,B]of E)T=T.split(`${O}*`).join(`${O}{0,${B}}`).split(`${O}+`).join(`${O}{1,${B}}`);return T},k=(T,O,B)=>{const L=M(O),R=y++;s(T,R,O),h[T]=R,d[R]=O,c[R]=new RegExp(O,B?"g":void 0),u[R]=new RegExp(L,B?"g":void 0)};k("NUMERICIDENTIFIER","0|[1-9]\\d*"),k("NUMERICIDENTIFIERLOOSE","\\d+"),k("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${S}*`),k("MAINVERSION",`(${d[h.NUMERICIDENTIFIER]})\\.(${d[h.NUMERICIDENTIFIER]})\\.(${d[h.NUMERICIDENTIFIER]})`),k("MAINVERSIONLOOSE",`(${d[h.NUMERICIDENTIFIERLOOSE]})\\.(${d[h.NUMERICIDENTIFIERLOOSE]})\\.(${d[h.NUMERICIDENTIFIERLOOSE]})`),k("PRERELEASEIDENTIFIER",`(?:${d[h.NUMERICIDENTIFIER]}|${d[h.NONNUMERICIDENTIFIER]})`),k("PRERELEASEIDENTIFIERLOOSE",`(?:${d[h.NUMERICIDENTIFIERLOOSE]}|${d[h.NONNUMERICIDENTIFIER]})`),k("PRERELEASE",`(?:-(${d[h.PRERELEASEIDENTIFIER]}(?:\\.${d[h.PRERELEASEIDENTIFIER]})*))`),k("PRERELEASELOOSE",`(?:-?(${d[h.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${d[h.PRERELEASEIDENTIFIERLOOSE]})*))`),k("BUILDIDENTIFIER",`${S}+`),k("BUILD",`(?:\\+(${d[h.BUILDIDENTIFIER]}(?:\\.${d[h.BUILDIDENTIFIER]})*))`),k("FULLPLAIN",`v?${d[h.MAINVERSION]}${d[h.PRERELEASE]}?${d[h.BUILD]}?`),k("FULL",`^${d[h.FULLPLAIN]}$`),k("LOOSEPLAIN",`[v=\\s]*${d[h.MAINVERSIONLOOSE]}${d[h.PRERELEASELOOSE]}?${d[h.BUILD]}?`),k("LOOSE",`^${d[h.LOOSEPLAIN]}$`),k("GTLT","((?:<|>)?=?)"),k("XRANGEIDENTIFIERLOOSE",`${d[h.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),k("XRANGEIDENTIFIER",`${d[h.NUMERICIDENTIFIER]}|x|X|\\*`),k("XRANGEPLAIN",`[v=\\s]*(${d[h.XRANGEIDENTIFIER]})(?:\\.(${d[h.XRANGEIDENTIFIER]})(?:\\.(${d[h.XRANGEIDENTIFIER]})(?:${d[h.PRERELEASE]})?${d[h.BUILD]}?)?)?`),k("XRANGEPLAINLOOSE",`[v=\\s]*(${d[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[h.XRANGEIDENTIFIERLOOSE]})(?:${d[h.PRERELEASELOOSE]})?${d[h.BUILD]}?)?)?`),k("XRANGE",`^${d[h.GTLT]}\\s*${d[h.XRANGEPLAIN]}$`),k("XRANGELOOSE",`^${d[h.GTLT]}\\s*${d[h.XRANGEPLAINLOOSE]}$`),k("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),k("COERCE",`${d[h.COERCEPLAIN]}(?:$|[^\\d])`),k("COERCEFULL",d[h.COERCEPLAIN]+`(?:${d[h.PRERELEASE]})?(?:${d[h.BUILD]})?(?:$|[^\\d])`),k("COERCERTL",d[h.COERCE],!0),k("COERCERTLFULL",d[h.COERCEFULL],!0),k("LONETILDE","(?:~>?)"),k("TILDETRIM",`(\\s*)${d[h.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",k("TILDE",`^${d[h.LONETILDE]}${d[h.XRANGEPLAIN]}$`),k("TILDELOOSE",`^${d[h.LONETILDE]}${d[h.XRANGEPLAINLOOSE]}$`),k("LONECARET","(?:\\^)"),k("CARETTRIM",`(\\s*)${d[h.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",k("CARET",`^${d[h.LONECARET]}${d[h.XRANGEPLAIN]}$`),k("CARETLOOSE",`^${d[h.LONECARET]}${d[h.XRANGEPLAINLOOSE]}$`),k("COMPARATORLOOSE",`^${d[h.GTLT]}\\s*(${d[h.LOOSEPLAIN]})$|^$`),k("COMPARATOR",`^${d[h.GTLT]}\\s*(${d[h.FULLPLAIN]})$|^$`),k("COMPARATORTRIM",`(\\s*)${d[h.GTLT]}\\s*(${d[h.LOOSEPLAIN]}|${d[h.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",k("HYPHENRANGE",`^\\s*(${d[h.XRANGEPLAIN]})\\s+-\\s+(${d[h.XRANGEPLAIN]})\\s*$`),k("HYPHENRANGELOOSE",`^\\s*(${d[h.XRANGEPLAINLOOSE]})\\s+-\\s+(${d[h.XRANGEPLAINLOOSE]})\\s*$`),k("STAR","(<|>)?=?\\s*\\*"),k("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),k("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Ds,Ds.exports);var jr=Ds.exports;const Ih=Object.freeze({loose:!0}),Ch=Object.freeze({}),Ah=t=>t?typeof t!="object"?Ih:t:Ch;var ci=Ah;const wo=/^[0-9]+$/,dc=(t,e)=>{const r=wo.test(t),n=wo.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tdc(e,t);var hc={compareIdentifiers:dc,rcompareIdentifiers:Nh};const Qr=Dn,{MAX_LENGTH:yo,MAX_SAFE_INTEGER:Kr}=Bn,{safeRe:bo,t:_o}=jr,Lh=ci,{compareIdentifiers:Gt}=hc;let xh=class gt{constructor(e,r){if(r=Lh(r),e instanceof gt){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>yo)throw new TypeError(`version is longer than ${yo} characters`);Qr("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;const n=e.trim().match(r.loose?bo[_o.LOOSE]:bo[_o.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Kr||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Kr||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Kr||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){const s=+i;if(s>=0&&s=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(r){let s=[r,i];n===!1&&(s=[r]),Gt(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var Ze=xh;const Eo=Ze,Th=(t,e,r=!1)=>{if(t instanceof Eo)return t;try{return new Eo(t,e)}catch(n){if(!r)return null;throw n}};var gr=Th;const Ph=gr,$h=(t,e)=>{const r=Ph(t,e);return r?r.version:null};var Oh=$h;const Bh=gr,Dh=(t,e)=>{const r=Bh(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};var jh=Dh;const So=Ze,Fh=(t,e,r,n,i)=>{typeof r=="string"&&(i=n,n=r,r=void 0);try{return new So(t instanceof So?t.version:t,r).inc(e,n,i).version}catch{return null}};var Hh=Fh;const Mo=gr,Uh=(t,e)=>{const r=Mo(t,null,!0),n=Mo(e,null,!0),i=r.compare(n);if(i===0)return null;const s=i>0,c=s?r:n,u=s?n:r,d=!!c.prerelease.length;if(!!u.prerelease.length&&!d)return!u.patch&&!u.minor?"major":c.patch?"patch":c.minor?"minor":"major";const y=d?"pre":"";return r.major!==n.major?y+"major":r.minor!==n.minor?y+"minor":r.patch!==n.patch?y+"patch":"prerelease"};var Vh=Uh;const Wh=Ze,zh=(t,e)=>new Wh(t,e).major;var qh=zh;const Jh=Ze,Gh=(t,e)=>new Jh(t,e).minor;var Zh=Gh;const Qh=Ze,Kh=(t,e)=>new Qh(t,e).patch;var Xh=Kh;const Yh=gr,ef=(t,e)=>{const r=Yh(t,e);return r&&r.prerelease.length?r.prerelease:null};var tf=ef;const ko=Ze,rf=(t,e,r)=>new ko(t,r).compare(new ko(e,r));var ut=rf;const nf=ut,sf=(t,e,r)=>nf(e,t,r);var of=sf;const af=ut,cf=(t,e)=>af(t,e,!0);var lf=cf;const Ro=Ze,uf=(t,e,r)=>{const n=new Ro(t,r),i=new Ro(e,r);return n.compare(i)||n.compareBuild(i)};var li=uf;const df=li,hf=(t,e)=>t.sort((r,n)=>df(r,n,e));var ff=hf;const gf=li,pf=(t,e)=>t.sort((r,n)=>gf(n,r,e));var mf=pf;const vf=ut,wf=(t,e,r)=>vf(t,e,r)>0;var jn=wf;const yf=ut,bf=(t,e,r)=>yf(t,e,r)<0;var ui=bf;const _f=ut,Ef=(t,e,r)=>_f(t,e,r)===0;var fc=Ef;const Sf=ut,Mf=(t,e,r)=>Sf(t,e,r)!==0;var gc=Mf;const kf=ut,Rf=(t,e,r)=>kf(t,e,r)>=0;var di=Rf;const If=ut,Cf=(t,e,r)=>If(t,e,r)<=0;var hi=Cf;const Af=fc,Nf=gc,Lf=jn,xf=di,Tf=ui,Pf=hi,$f=(t,e,r,n)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t===r;case"!==":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t!==r;case"":case"=":case"==":return Af(t,r,n);case"!=":return Nf(t,r,n);case">":return Lf(t,r,n);case">=":return xf(t,r,n);case"<":return Tf(t,r,n);case"<=":return Pf(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};var pc=$f;const Of=Ze,Bf=gr,{safeRe:Xr,t:Yr}=jr,Df=(t,e)=>{if(t instanceof Of)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?Xr[Yr.COERCEFULL]:Xr[Yr.COERCE]);else{const d=e.includePrerelease?Xr[Yr.COERCERTLFULL]:Xr[Yr.COERCERTL];let h;for(;(h=d.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||h.index+h[0].length!==r.index+r[0].length)&&(r=h),d.lastIndex=h.index+h[1].length+h[2].length;d.lastIndex=-1}if(r===null)return null;const n=r[2],i=r[3]||"0",s=r[4]||"0",c=e.includePrerelease&&r[5]?`-${r[5]}`:"",u=e.includePrerelease&&r[6]?`+${r[6]}`:"";return Bf(`${n}.${i}.${s}${c}${u}`,e)};var jf=Df;class Ff{constructor(){this.max=1e3,this.map=new Map}get(e){const r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}delete(e){return this.map.delete(e)}set(e,r){if(!this.delete(e)&&r!==void 0){if(this.map.size>=this.max){const i=this.map.keys().next().value;this.delete(i)}this.map.set(e,r)}return this}}var Hf=Ff,Rs,Io;function dt(){if(Io)return Rs;Io=1;const t=/\s+/g;class e{constructor(l,f){if(f=i(f),l instanceof e)return l.loose===!!f.loose&&l.includePrerelease===!!f.includePrerelease?l:new e(l.raw,f);if(l instanceof s)return this.raw=l.value,this.set=[[l]],this.formatted=void 0,this;if(this.options=f,this.loose=!!f.loose,this.includePrerelease=!!f.includePrerelease,this.raw=l.trim().replace(t," "),this.set=this.raw.split("||").map(g=>this.parseRange(g.trim())).filter(g=>g.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const g=this.set[0];if(this.set=this.set.filter(m=>!T(m[0])),this.set.length===0)this.set=[g];else if(this.set.length>1){for(const m of this.set)if(m.length===1&&O(m[0])){this.set=[m];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let l=0;l0&&(this.formatted+="||");const f=this.set[l];for(let g=0;g0&&(this.formatted+=" "),this.formatted+=f[g].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(l){const g=((this.options.includePrerelease&&M)|(this.options.loose&&k))+":"+l,m=n.get(g);if(m)return m;const w=this.options.loose,_=w?d[h.HYPHENRANGELOOSE]:d[h.HYPHENRANGE];l=l.replace(_,q(this.options.includePrerelease)),c("hyphen replace",l),l=l.replace(d[h.COMPARATORTRIM],y),c("comparator trim",l),l=l.replace(d[h.TILDETRIM],S),c("tilde trim",l),l=l.replace(d[h.CARETTRIM],E),c("caret trim",l);let p=l.split(" ").map(I=>L(I,this.options)).join(" ").split(/\s+/).map(I=>H(I,this.options));w&&(p=p.filter(I=>(c("loose invalid filter",I,this.options),!!I.match(d[h.COMPARATORLOOSE])))),c("range list",p);const a=new Map,v=p.map(I=>new s(I,this.options));for(const I of v){if(T(I))return[I];a.set(I.value,I)}a.size>1&&a.has("")&&a.delete("");const N=[...a.values()];return n.set(g,N),N}intersects(l,f){if(!(l instanceof e))throw new TypeError("a Range is required");return this.set.some(g=>B(g,f)&&l.set.some(m=>B(m,f)&&g.every(w=>m.every(_=>w.intersects(_,f)))))}test(l){if(!l)return!1;if(typeof l=="string")try{l=new u(l,this.options)}catch{return!1}for(let f=0;fo.value==="<0.0.0-0",O=o=>o.value==="",B=(o,l)=>{let f=!0;const g=o.slice();let m=g.pop();for(;f&&g.length;)f=g.every(w=>m.intersects(w,l)),m=g.pop();return f},L=(o,l)=>(c("comp",o,l),o=P(o,l),c("caret",o),o=z(o,l),c("tildes",o),o=We(o,l),c("xrange",o),o=Y(o,l),c("stars",o),o),R=o=>!o||o.toLowerCase()==="x"||o==="*",z=(o,l)=>o.trim().split(/\s+/).map(f=>C(f,l)).join(" "),C=(o,l)=>{const f=l.loose?d[h.TILDELOOSE]:d[h.TILDE];return o.replace(f,(g,m,w,_,p)=>{c("tilde",o,g,m,w,_,p);let a;return R(m)?a="":R(w)?a=`>=${m}.0.0 <${+m+1}.0.0-0`:R(_)?a=`>=${m}.${w}.0 <${m}.${+w+1}.0-0`:p?(c("replaceTilde pr",p),a=`>=${m}.${w}.${_}-${p} <${m}.${+w+1}.0-0`):a=`>=${m}.${w}.${_} <${m}.${+w+1}.0-0`,c("tilde return",a),a})},P=(o,l)=>o.trim().split(/\s+/).map(f=>J(f,l)).join(" "),J=(o,l)=>{c("caret",o,l);const f=l.loose?d[h.CARETLOOSE]:d[h.CARET],g=l.includePrerelease?"-0":"";return o.replace(f,(m,w,_,p,a)=>{c("caret",o,m,w,_,p,a);let v;return R(w)?v="":R(_)?v=`>=${w}.0.0${g} <${+w+1}.0.0-0`:R(p)?w==="0"?v=`>=${w}.${_}.0${g} <${w}.${+_+1}.0-0`:v=`>=${w}.${_}.0${g} <${+w+1}.0.0-0`:a?(c("replaceCaret pr",a),w==="0"?_==="0"?v=`>=${w}.${_}.${p}-${a} <${w}.${_}.${+p+1}-0`:v=`>=${w}.${_}.${p}-${a} <${w}.${+_+1}.0-0`:v=`>=${w}.${_}.${p}-${a} <${+w+1}.0.0-0`):(c("no pr"),w==="0"?_==="0"?v=`>=${w}.${_}.${p}${g} <${w}.${_}.${+p+1}-0`:v=`>=${w}.${_}.${p}${g} <${w}.${+_+1}.0-0`:v=`>=${w}.${_}.${p} <${+w+1}.0.0-0`),c("caret return",v),v})},We=(o,l)=>(c("replaceXRanges",o,l),o.split(/\s+/).map(f=>Qe(f,l)).join(" ")),Qe=(o,l)=>{o=o.trim();const f=l.loose?d[h.XRANGELOOSE]:d[h.XRANGE];return o.replace(f,(g,m,w,_,p,a)=>{c("xRange",o,g,m,w,_,p,a);const v=R(w),N=v||R(_),I=N||R(p),$=I;return m==="="&&$&&(m=""),a=l.includePrerelease?"-0":"",v?m===">"||m==="<"?g="<0.0.0-0":g="*":m&&$?(N&&(_=0),p=0,m===">"?(m=">=",N?(w=+w+1,_=0,p=0):(_=+_+1,p=0)):m==="<="&&(m="<",N?w=+w+1:_=+_+1),m==="<"&&(a="-0"),g=`${m+w}.${_}.${p}${a}`):N?g=`>=${w}.0.0${a} <${+w+1}.0.0-0`:I&&(g=`>=${w}.${_}.0${a} <${w}.${+_+1}.0-0`),c("xRange return",g),g})},Y=(o,l)=>(c("replaceStars",o,l),o.trim().replace(d[h.STAR],"")),H=(o,l)=>(c("replaceGTE0",o,l),o.trim().replace(d[l.includePrerelease?h.GTE0PRE:h.GTE0],"")),q=o=>(l,f,g,m,w,_,p,a,v,N,I,$)=>(R(g)?f="":R(m)?f=`>=${g}.0.0${o?"-0":""}`:R(w)?f=`>=${g}.${m}.0${o?"-0":""}`:_?f=`>=${f}`:f=`>=${f}${o?"-0":""}`,R(v)?a="":R(N)?a=`<${+v+1}.0.0-0`:R(I)?a=`<${v}.${+N+1}.0-0`:$?a=`<=${v}.${N}.${I}-${$}`:o?a=`<${v}.${N}.${+I+1}-0`:a=`<=${a}`,`${f} ${a}`.trim()),b=(o,l,f)=>{for(let g=0;g0){const m=o[g].semver;if(m.major===l.major&&m.minor===l.minor&&m.patch===l.patch)return!0}return!1}return!0};return Rs}var Is,Co;function Fn(){if(Co)return Is;Co=1;const t=Symbol("SemVer ANY");class e{static get ANY(){return t}constructor(y,S){if(S=r(S),y instanceof e){if(y.loose===!!S.loose)return y;y=y.value}y=y.trim().split(/\s+/).join(" "),c("comparator",y,S),this.options=S,this.loose=!!S.loose,this.parse(y),this.semver===t?this.value="":this.value=this.operator+this.semver.version,c("comp",this)}parse(y){const S=this.options.loose?n[i.COMPARATORLOOSE]:n[i.COMPARATOR],E=y.match(S);if(!E)throw new TypeError(`Invalid comparator: ${y}`);this.operator=E[1]!==void 0?E[1]:"",this.operator==="="&&(this.operator=""),E[2]?this.semver=new u(E[2],this.options.loose):this.semver=t}toString(){return this.value}test(y){if(c("Comparator.test",y,this.options.loose),this.semver===t||y===t)return!0;if(typeof y=="string")try{y=new u(y,this.options)}catch{return!1}return s(y,this.operator,this.semver,this.options)}intersects(y,S){if(!(y instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new d(y.value,S).test(this.value):y.operator===""?y.value===""?!0:new d(this.value,S).test(y.semver):(S=r(S),S.includePrerelease&&(this.value==="<0.0.0-0"||y.value==="<0.0.0-0")||!S.includePrerelease&&(this.value.startsWith("<0.0.0")||y.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&y.operator.startsWith(">")||this.operator.startsWith("<")&&y.operator.startsWith("<")||this.semver.version===y.semver.version&&this.operator.includes("=")&&y.operator.includes("=")||s(this.semver,"<",y.semver,S)&&this.operator.startsWith(">")&&y.operator.startsWith("<")||s(this.semver,">",y.semver,S)&&this.operator.startsWith("<")&&y.operator.startsWith(">")))}}Is=e;const r=ci,{safeRe:n,t:i}=jr,s=pc,c=Dn,u=Ze,d=dt();return Is}const Uf=dt(),Vf=(t,e,r)=>{try{e=new Uf(e,r)}catch{return!1}return e.test(t)};var Hn=Vf;const Wf=dt(),zf=(t,e)=>new Wf(t,e).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));var qf=zf;const Jf=Ze,Gf=dt(),Zf=(t,e,r)=>{let n=null,i=null,s=null;try{s=new Gf(e,r)}catch{return null}return t.forEach(c=>{s.test(c)&&(!n||i.compare(c)===-1)&&(n=c,i=new Jf(n,r))}),n};var Qf=Zf;const Kf=Ze,Xf=dt(),Yf=(t,e,r)=>{let n=null,i=null,s=null;try{s=new Xf(e,r)}catch{return null}return t.forEach(c=>{s.test(c)&&(!n||i.compare(c)===1)&&(n=c,i=new Kf(n,r))}),n};var e0=Yf;const Cs=Ze,t0=dt(),Ao=jn,r0=(t,e)=>{t=new t0(t,e);let r=new Cs("0.0.0");if(t.test(r)||(r=new Cs("0.0.0-0"),t.test(r)))return r;r=null;for(let n=0;n{const u=new Cs(c.semver.version);switch(c.operator){case">":u.prerelease.length===0?u.patch++:u.prerelease.push(0),u.raw=u.format();case"":case">=":(!s||Ao(u,s))&&(s=u);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${c.operator}`)}}),s&&(!r||Ao(r,s))&&(r=s)}return r&&t.test(r)?r:null};var n0=r0;const s0=dt(),i0=(t,e)=>{try{return new s0(t,e).range||"*"}catch{return null}};var o0=i0;const a0=Ze,mc=Fn(),{ANY:c0}=mc,l0=dt(),u0=Hn,No=jn,Lo=ui,d0=hi,h0=di,f0=(t,e,r,n)=>{t=new a0(t,n),e=new l0(e,n);let i,s,c,u,d;switch(r){case">":i=No,s=d0,c=Lo,u=">",d=">=";break;case"<":i=Lo,s=h0,c=No,u="<",d="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(u0(t,e,n))return!1;for(let h=0;h{M.semver===c0&&(M=new mc(">=0.0.0")),S=S||M,E=E||M,i(M.semver,S.semver,n)?S=M:c(M.semver,E.semver,n)&&(E=M)}),S.operator===u||S.operator===d||(!E.operator||E.operator===u)&&s(t,E.semver))return!1;if(E.operator===d&&c(t,E.semver))return!1}return!0};var fi=f0;const g0=fi,p0=(t,e,r)=>g0(t,e,">",r);var m0=p0;const v0=fi,w0=(t,e,r)=>v0(t,e,"<",r);var y0=w0;const xo=dt(),b0=(t,e,r)=>(t=new xo(t,r),e=new xo(e,r),t.intersects(e,r));var _0=b0;const E0=Hn,S0=ut;var M0=(t,e,r)=>{const n=[];let i=null,s=null;const c=t.sort((y,S)=>S0(y,S,r));for(const y of c)E0(y,e,r)?(s=y,i||(i=y)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);const u=[];for(const[y,S]of n)y===S?u.push(y):!S&&y===c[0]?u.push("*"):S?y===c[0]?u.push(`<=${S}`):u.push(`${y} - ${S}`):u.push(`>=${y}`);const d=u.join(" || "),h=typeof e.raw=="string"?e.raw:String(e);return d.length{if(t===e)return!0;t=new To(t,r),e=new To(e,r);let n=!1;e:for(const i of t.set){for(const s of e.set){const c=I0(i,s,r);if(n=n||c!==null,c)continue e}if(n)return!1}return!0},R0=[new gi(">=0.0.0-0")],Po=[new gi(">=0.0.0")],I0=(t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===As){if(e.length===1&&e[0].semver===As)return!0;r.includePrerelease?t=R0:t=Po}if(e.length===1&&e[0].semver===As){if(r.includePrerelease)return!0;e=Po}const n=new Set;let i,s;for(const M of t)M.operator===">"||M.operator===">="?i=$o(i,M,r):M.operator==="<"||M.operator==="<="?s=Oo(s,M,r):n.add(M.semver);if(n.size>1)return null;let c;if(i&&s){if(c=pi(i.semver,s.semver,r),c>0)return null;if(c===0&&(i.operator!==">="||s.operator!=="<="))return null}for(const M of n){if(i&&!mr(M,String(i),r)||s&&!mr(M,String(s),r))return null;for(const k of e)if(!mr(M,String(k),r))return!1;return!0}let u,d,h,y,S=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,E=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1;S&&S.prerelease.length===1&&s.operator==="<"&&S.prerelease[0]===0&&(S=!1);for(const M of e){if(y=y||M.operator===">"||M.operator===">=",h=h||M.operator==="<"||M.operator==="<=",i){if(E&&M.semver.prerelease&&M.semver.prerelease.length&&M.semver.major===E.major&&M.semver.minor===E.minor&&M.semver.patch===E.patch&&(E=!1),M.operator===">"||M.operator===">="){if(u=$o(i,M,r),u===M&&u!==i)return!1}else if(i.operator===">="&&!mr(i.semver,String(M),r))return!1}if(s){if(S&&M.semver.prerelease&&M.semver.prerelease.length&&M.semver.major===S.major&&M.semver.minor===S.minor&&M.semver.patch===S.patch&&(S=!1),M.operator==="<"||M.operator==="<="){if(d=Oo(s,M,r),d===M&&d!==s)return!1}else if(s.operator==="<="&&!mr(s.semver,String(M),r))return!1}if(!M.operator&&(s||i)&&c!==0)return!1}return!(i&&h&&!s&&c!==0||s&&y&&!i&&c!==0||E||S)},$o=(t,e,r)=>{if(!t)return e;const n=pi(t.semver,e.semver,r);return n>0?t:n<0||e.operator===">"&&t.operator===">="?e:t},Oo=(t,e,r)=>{if(!t)return e;const n=pi(t.semver,e.semver,r);return n<0?t:n>0||e.operator==="<"&&t.operator==="<="?e:t};var C0=k0;const Ns=jr,Bo=Bn,A0=Ze,Do=hc,N0=gr,L0=Oh,x0=jh,T0=Hh,P0=Vh,$0=qh,O0=Zh,B0=Xh,D0=tf,j0=ut,F0=of,H0=lf,U0=li,V0=ff,W0=mf,z0=jn,q0=ui,J0=fc,G0=gc,Z0=di,Q0=hi,K0=pc,X0=jf,Y0=Fn(),e1=dt(),t1=Hn,r1=qf,n1=Qf,s1=e0,i1=n0,o1=o0,a1=fi,c1=m0,l1=y0,u1=_0,d1=M0,h1=C0;var f1={parse:N0,valid:L0,clean:x0,inc:T0,diff:P0,major:$0,minor:O0,patch:B0,prerelease:D0,compare:j0,rcompare:F0,compareLoose:H0,compareBuild:U0,sort:V0,rsort:W0,gt:z0,lt:q0,eq:J0,neq:G0,gte:Z0,lte:Q0,cmp:K0,coerce:X0,Comparator:Y0,Range:e1,satisfies:t1,toComparators:r1,maxSatisfying:n1,minSatisfying:s1,minVersion:i1,validRange:o1,outside:a1,gtr:c1,ltr:l1,intersects:u1,simplifyRange:d1,subset:h1,SemVer:A0,re:Ns.re,src:Ns.src,tokens:Ns.t,SEMVER_SPEC_VERSION:Bo.SEMVER_SPEC_VERSION,RELEASE_TYPES:Bo.RELEASE_TYPES,compareIdentifiers:Do.compareIdentifiers,rcompareIdentifiers:Do.rcompareIdentifiers};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.satisfiesVersionRange=t.gtRange=t.gtVersion=t.assertIsSemVerRange=t.assertIsSemVerVersion=t.isValidSemVerRange=t.isValidSemVerVersion=t.VersionRangeStruct=t.VersionStruct=void 0;const e=f1,r=Vt,n=Ve;t.VersionStruct=(0,r.refine)((0,r.string)(),"Version",S=>(0,e.valid)(S)===null?`Expected SemVer version, got "${S}"`:!0),t.VersionRangeStruct=(0,r.refine)((0,r.string)(),"Version range",S=>(0,e.validRange)(S)===null?`Expected SemVer range, got "${S}"`:!0);function i(S){return(0,r.is)(S,t.VersionStruct)}t.isValidSemVerVersion=i;function s(S){return(0,r.is)(S,t.VersionRangeStruct)}t.isValidSemVerRange=s;function c(S){(0,n.assertStruct)(S,t.VersionStruct)}t.assertIsSemVerVersion=c;function u(S){(0,n.assertStruct)(S,t.VersionRangeStruct)}t.assertIsSemVerRange=u;function d(S,E){return(0,e.gt)(S,E)}t.gtVersion=d;function h(S,E){return(0,e.gtr)(S,E)}t.gtRange=h;function y(S,E){return(0,e.satisfies)(S,E,{includePrerelease:!0})}t.satisfiesVersionRange=y})(lc);(function(t){var e=x&&x.__createBinding||(Object.create?function(n,i,s,c){c===void 0&&(c=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,c,u)}:function(n,i,s,c){c===void 0&&(c=s),n[c]=i[s]}),r=x&&x.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(t,"__esModule",{value:!0}),r(Ve,t),r(Br,t),r(W,t),r($n,t),r(yt,t),r(or,t),r(rc,t),r(Dr,t),r(nc,t),r(sc,t),r(ar,t),r(ic,t),r(bt,t),r(oc,t),r(ac,t),r(cc,t),r(lc,t)})(Ba);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.createModuleLogger=t.projectLogger=void 0;const e=Ba;Object.defineProperty(t,"createModuleLogger",{enumerable:!0,get:function(){return e.createModuleLogger}}),t.projectLogger=(0,e.createProjectLogger)("eth-block-tracker")})(Oa);var vc=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Tn,"__esModule",{value:!0});Tn.PollingBlockTracker=void 0;const g1=vc(Ys),p1=vc(Vu),m1=Tr,jo=Oa,Fo=(0,jo.createModuleLogger)(jo.projectLogger,"polling-block-tracker"),v1=(0,g1.default)(),w1=1e3;class y1 extends m1.BaseBlockTracker{constructor(e={}){var r;if(!e.provider)throw new Error("PollingBlockTracker - no provider specified.");super(Object.assign(Object.assign({},e),{blockResetDuration:(r=e.blockResetDuration)!==null&&r!==void 0?r:e.pollingInterval})),this._provider=e.provider,this._pollingInterval=e.pollingInterval||20*w1,this._retryTimeout=e.retryTimeout||this._pollingInterval/10,this._keepEventLoopActive=e.keepEventLoopActive===void 0?!0:e.keepEventLoopActive,this._setSkipCacheFlag=e.setSkipCacheFlag||!1}async checkForLatestBlock(){return await this._updateLatestBlock(),await this.getLatestBlock()}async _start(){this._synchronize()}async _end(){}async _synchronize(){for(var e;this._isRunning;)try{await this._updateLatestBlock();const r=Ho(this._pollingInterval,!this._keepEventLoopActive);this.emit("_waitingForNextIteration"),await r}catch(r){const n=new Error(`PollingBlockTracker - encountered an error while attempting to update latest block: +${(e=r.stack)!==null&&e!==void 0?e:r}`);try{this.emit("error",n)}catch{console.error(n)}const i=Ho(this._retryTimeout,!this._keepEventLoopActive);this.emit("_waitingForNextIteration"),await i}}async _updateLatestBlock(){const e=await this._fetchLatestBlock();this._newPotentialLatest(e)}async _fetchLatestBlock(){const e={jsonrpc:"2.0",id:v1(),method:"eth_blockNumber",params:[]};this._setSkipCacheFlag&&(e.skipCache=!0),Fo("Making request",e);const r=await(0,p1.default)(n=>this._provider.sendAsync(e,n))();if(Fo("Got response",r),r.error)throw new Error(`PollingBlockTracker - encountered error fetching block: +${r.error.message}`);return r.result}}Tn.PollingBlockTracker=y1;function Ho(t,e){return new Promise(r=>{const n=setTimeout(r,t);n.unref&&e&&n.unref()})}var Un={},b1=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Un,"__esModule",{value:!0});Un.SubscribeBlockTracker=void 0;const _1=b1(Ys),E1=Tr,S1=(0,_1.default)();class M1 extends E1.BaseBlockTracker{constructor(e={}){if(!e.provider)throw new Error("SubscribeBlockTracker - no provider specified.");super(e),this._provider=e.provider,this._subscriptionId=null}async checkForLatestBlock(){return await this.getLatestBlock()}async _start(){if(this._subscriptionId===void 0||this._subscriptionId===null)try{const e=await this._call("eth_blockNumber");this._subscriptionId=await this._call("eth_subscribe","newHeads"),this._provider.on("data",this._handleSubData.bind(this)),this._newPotentialLatest(e)}catch(e){this.emit("error",e)}}async _end(){if(this._subscriptionId!==null&&this._subscriptionId!==void 0)try{await this._call("eth_unsubscribe",this._subscriptionId),this._subscriptionId=null}catch(e){this.emit("error",e)}}_call(e,...r){return new Promise((n,i)=>{this._provider.sendAsync({id:S1(),method:e,params:r,jsonrpc:"2.0"},(s,c)=>{s?i(s):n(c.result)})})}_handleSubData(e,r){var n;r.method==="eth_subscription"&&((n=r.params)===null||n===void 0?void 0:n.subscription)===this._subscriptionId&&this._newPotentialLatest(r.params.result.number)}}Un.SubscribeBlockTracker=M1;(function(t){var e=x&&x.__createBinding||(Object.create?function(n,i,s,c){c===void 0&&(c=s),Object.defineProperty(n,c,{enumerable:!0,get:function(){return i[s]}})}:function(n,i,s,c){c===void 0&&(c=s),n[c]=i[s]}),r=x&&x.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(t,"__esModule",{value:!0}),r(Tn,t),r(Un,t)})($a);var mi={},Vn={},Fr={};Object.defineProperty(Fr,"__esModule",{value:!0});Fr.getUniqueId=void 0;const wc=4294967295;let Ls=Math.floor(Math.random()*wc);function k1(){return Ls=(Ls+1)%wc,Ls}Fr.getUniqueId=k1;Object.defineProperty(Vn,"__esModule",{value:!0});Vn.createIdRemapMiddleware=void 0;const R1=Fr;function I1(){return(t,e,r,n)=>{const i=t.id,s=R1.getUniqueId();t.id=s,e.id=s,r(c=>{t.id=i,e.id=i,c()})}}Vn.createIdRemapMiddleware=I1;var Wn={};Object.defineProperty(Wn,"__esModule",{value:!0});Wn.createAsyncMiddleware=void 0;function C1(t){return async(e,r,n,i)=>{let s;const c=new Promise(y=>{s=y});let u=null,d=!1;const h=async()=>{d=!0,n(y=>{u=y,s()}),await c};try{await t(e,r,h),d?(await c,u(null)):i(null)}catch(y){u?u(y):i(y)}}}Wn.createAsyncMiddleware=C1;var zn={};Object.defineProperty(zn,"__esModule",{value:!0});zn.createScaffoldMiddleware=void 0;function A1(t){return(e,r,n,i)=>{const s=t[e.method];return s===void 0?n():typeof s=="function"?s(e,r,n,i):(r.result=s,i())}}zn.createScaffoldMiddleware=A1;var Hr={},vi={};Object.defineProperty(vi,"__esModule",{value:!0});const N1=ta;function Uo(t,e,r){try{Reflect.apply(t,e,r)}catch(n){setTimeout(()=>{throw n})}}function L1(t){const e=t.length,r=new Array(e);for(let n=0;n0&&([c]=r),c instanceof Error)throw c;const u=new Error(`Unhandled error.${c?` (${c.message})`:""}`);throw u.context=c,u}const s=i[e];if(s===void 0)return!1;if(typeof s=="function")Uo(s,this,r);else{const c=s.length,u=L1(s);for(let d=0;d"u"&&(n=_c()),js(t,"",0,[],void 0,0,n);var i;try{Bt.length===0?i=JSON.stringify(t,e,r):i=JSON.stringify(t,Sc(e),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Ft.length!==0;){var s=Ft.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return i}function tr(t,e,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:t}),Ft.push([n,r,e,i])):Bt.push([e,r,t]):(n[r]=t,Ft.push([n,r,e]))}function js(t,e,r,n,i,s,c){s+=1;var u;if(typeof t=="object"&&t!==null){for(u=0;uc.depthLimit){tr(sn,t,e,i);return}if(typeof c.edgesLimit<"u"&&r+1>c.edgesLimit){tr(sn,t,e,i);return}if(n.push(t),Array.isArray(t))for(u=0;ue?1:0}function Ec(t,e,r,n){typeof n>"u"&&(n=_c());var i=Fs(t,"",0,[],void 0,0,n)||t,s;try{Bt.length===0?s=JSON.stringify(i,e,r):s=JSON.stringify(i,Sc(e),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Ft.length!==0;){var c=Ft.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return s}function Fs(t,e,r,n,i,s,c){s+=1;var u;if(typeof t=="object"&&t!==null){for(u=0;uc.depthLimit){tr(sn,t,e,i);return}if(typeof c.edgesLimit<"u"&&r+1>c.edgesLimit){tr(sn,t,e,i);return}if(n.push(t),Array.isArray(t))for(u=0;u0)for(var n=0;n=1e3&&t<=4999}function D1(t,e){if(e!=="[Circular]")return e}var wi={},At={};Object.defineProperty(At,"__esModule",{value:!0});At.errorValues=At.errorCodes=void 0;At.errorCodes={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901}};At.errorValues={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."}};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.serializeError=t.isValidCode=t.getMessageFromCode=t.JSON_RPC_SERVER_ERROR_MESSAGE=void 0;const e=At,r=Ct,n=e.errorCodes.rpc.internal,i="Unspecified error message. This is a bug, please report it.",s={code:n,message:c(n)};t.JSON_RPC_SERVER_ERROR_MESSAGE="Unspecified server error.";function c(E,M=i){if(Number.isInteger(E)){const k=E.toString();if(S(e.errorValues,k))return e.errorValues[k].message;if(h(E))return t.JSON_RPC_SERVER_ERROR_MESSAGE}return M}t.getMessageFromCode=c;function u(E){if(!Number.isInteger(E))return!1;const M=E.toString();return!!(e.errorValues[M]||h(E))}t.isValidCode=u;function d(E,{fallbackError:M=s,shouldIncludeStack:k=!1}={}){var T,O;if(!M||!Number.isInteger(M.code)||typeof M.message!="string")throw new Error("Must provide fallback error with integer number code and string message.");if(E instanceof r.EthereumRpcError)return E.serialize();const B={};if(E&&typeof E=="object"&&!Array.isArray(E)&&S(E,"code")&&u(E.code)){const R=E;B.code=R.code,R.message&&typeof R.message=="string"?(B.message=R.message,S(R,"data")&&(B.data=R.data)):(B.message=c(B.code),B.data={originalError:y(E)})}else{B.code=M.code;const R=(T=E)===null||T===void 0?void 0:T.message;B.message=R&&typeof R=="string"?R:M.message,B.data={originalError:y(E)}}const L=(O=E)===null||O===void 0?void 0:O.stack;return k&&E&&L&&typeof L=="string"&&(B.stack=L),B}t.serializeError=d;function h(E){return E>=-32099&&E<=-32e3}function y(E){return E&&typeof E=="object"&&!Array.isArray(E)?Object.assign({},E):E}function S(E,M){return Object.prototype.hasOwnProperty.call(E,M)}})(wi);var qn={};Object.defineProperty(qn,"__esModule",{value:!0});qn.ethErrors=void 0;const yi=Ct,kc=wi,qe=At;qn.ethErrors={rpc:{parse:t=>nt(qe.errorCodes.rpc.parse,t),invalidRequest:t=>nt(qe.errorCodes.rpc.invalidRequest,t),invalidParams:t=>nt(qe.errorCodes.rpc.invalidParams,t),methodNotFound:t=>nt(qe.errorCodes.rpc.methodNotFound,t),internal:t=>nt(qe.errorCodes.rpc.internal,t),server:t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:e}=t;if(!Number.isInteger(e)||e>-32005||e<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return nt(e,t)},invalidInput:t=>nt(qe.errorCodes.rpc.invalidInput,t),resourceNotFound:t=>nt(qe.errorCodes.rpc.resourceNotFound,t),resourceUnavailable:t=>nt(qe.errorCodes.rpc.resourceUnavailable,t),transactionRejected:t=>nt(qe.errorCodes.rpc.transactionRejected,t),methodNotSupported:t=>nt(qe.errorCodes.rpc.methodNotSupported,t),limitExceeded:t=>nt(qe.errorCodes.rpc.limitExceeded,t)},provider:{userRejectedRequest:t=>vr(qe.errorCodes.provider.userRejectedRequest,t),unauthorized:t=>vr(qe.errorCodes.provider.unauthorized,t),unsupportedMethod:t=>vr(qe.errorCodes.provider.unsupportedMethod,t),disconnected:t=>vr(qe.errorCodes.provider.disconnected,t),chainDisconnected:t=>vr(qe.errorCodes.provider.chainDisconnected,t),custom:t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:e,message:r,data:n}=t;if(!r||typeof r!="string")throw new Error('"message" must be a nonempty string');return new yi.EthereumProviderError(e,r,n)}}};function nt(t,e){const[r,n]=Rc(e);return new yi.EthereumRpcError(t,r||kc.getMessageFromCode(t),n)}function vr(t,e){const[r,n]=Rc(e);return new yi.EthereumProviderError(t,r||kc.getMessageFromCode(t),n)}function Rc(t){if(t){if(typeof t=="string")return[t];if(typeof t=="object"&&!Array.isArray(t)){const{message:e,data:r}=t;if(e&&typeof e!="string")throw new Error("Must specify string message.");return[e||void 0,r]}}return[]}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.getMessageFromCode=t.serializeError=t.EthereumProviderError=t.EthereumRpcError=t.ethErrors=t.errorCodes=void 0;const e=Ct;Object.defineProperty(t,"EthereumRpcError",{enumerable:!0,get:function(){return e.EthereumRpcError}}),Object.defineProperty(t,"EthereumProviderError",{enumerable:!0,get:function(){return e.EthereumProviderError}});const r=wi;Object.defineProperty(t,"serializeError",{enumerable:!0,get:function(){return r.serializeError}}),Object.defineProperty(t,"getMessageFromCode",{enumerable:!0,get:function(){return r.getMessageFromCode}});const n=qn;Object.defineProperty(t,"ethErrors",{enumerable:!0,get:function(){return n.ethErrors}});const i=At;Object.defineProperty(t,"errorCodes",{enumerable:!0,get:function(){return i.errorCodes}})})(yc);var j1=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Hr,"__esModule",{value:!0});Hr.JsonRpcEngine=void 0;const F1=j1(vi),st=yc;class _t extends F1.default{constructor(){super(),this._middleware=[]}push(e){this._middleware.push(e)}handle(e,r){if(r&&typeof r!="function")throw new Error('"callback" must be a function if provided.');return Array.isArray(e)?r?this._handleBatch(e,r):this._handleBatch(e):r?this._handle(e,r):this._promiseHandle(e)}asMiddleware(){return async(e,r,n,i)=>{try{const[s,c,u]=await _t._runAllMiddleware(e,r,this._middleware);return c?(await _t._runReturnHandlers(u),i(s)):n(async d=>{try{await _t._runReturnHandlers(u)}catch(h){return d(h)}return d()})}catch(s){return i(s)}}}async _handleBatch(e,r){try{const n=await Promise.all(e.map(this._promiseHandle.bind(this)));return r?r(null,n):n}catch(n){if(r)return r(n);throw n}}_promiseHandle(e){return new Promise(r=>{this._handle(e,(n,i)=>{r(i)})})}async _handle(e,r){if(!e||Array.isArray(e)||typeof e!="object"){const c=new st.EthereumRpcError(st.errorCodes.rpc.invalidRequest,`Requests must be plain objects. Received: ${typeof e}`,{request:e});return r(c,{id:void 0,jsonrpc:"2.0",error:c})}if(typeof e.method!="string"){const c=new st.EthereumRpcError(st.errorCodes.rpc.invalidRequest,`Must specify a string method. Received: ${typeof e.method}`,{request:e});return r(c,{id:e.id,jsonrpc:"2.0",error:c})}const n=Object.assign({},e),i={id:n.id,jsonrpc:n.jsonrpc};let s=null;try{await this._processRequest(n,i)}catch(c){s=c}return s&&(delete i.result,i.error||(i.error=st.serializeError(s))),r(s,i)}async _processRequest(e,r){const[n,i,s]=await _t._runAllMiddleware(e,r,this._middleware);if(_t._checkForCompletion(e,r,i),await _t._runReturnHandlers(s),n)throw n}static async _runAllMiddleware(e,r,n){const i=[];let s=null,c=!1;for(const u of n)if([s,c]=await _t._runMiddleware(e,r,u,i),c)break;return[s,c,i.reverse()]}static _runMiddleware(e,r,n,i){return new Promise(s=>{const c=d=>{const h=d||r.error;h&&(r.error=st.serializeError(h)),s([h,!0])},u=d=>{r.error?c(r.error):(d&&(typeof d!="function"&&c(new st.EthereumRpcError(st.errorCodes.rpc.internal,`JsonRpcEngine: "next" return handlers must be functions. Received "${typeof d}" for request: +${xs(e)}`,{request:e})),i.push(d)),s([null,!1]))};try{n(e,r,u,c)}catch(d){c(d)}})}static async _runReturnHandlers(e){for(const r of e)await new Promise((n,i)=>{r(s=>s?i(s):n())})}static _checkForCompletion(e,r,n){if(!("result"in r)&&!("error"in r))throw new st.EthereumRpcError(st.errorCodes.rpc.internal,`JsonRpcEngine: Response has no error or result for request: +${xs(e)}`,{request:e});if(!n)throw new st.EthereumRpcError(st.errorCodes.rpc.internal,`JsonRpcEngine: Nothing ended request: +${xs(e)}`,{request:e})}}Hr.JsonRpcEngine=_t;function xs(t){return JSON.stringify(t,null,2)}var Jn={};Object.defineProperty(Jn,"__esModule",{value:!0});Jn.mergeMiddleware=void 0;const H1=Hr;function U1(t){const e=new H1.JsonRpcEngine;return t.forEach(r=>e.push(r)),e.asMiddleware()}Jn.mergeMiddleware=U1;(function(t){var e=x&&x.__createBinding||(Object.create?function(n,i,s,c){c===void 0&&(c=s),Object.defineProperty(n,c,{enumerable:!0,get:function(){return i[s]}})}:function(n,i,s,c){c===void 0&&(c=s),n[c]=i[s]}),r=x&&x.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(t,"__esModule",{value:!0}),r(Vn,t),r(Wn,t),r(zn,t),r(Fr,t),r(Hr,t),r(Jn,t)})(mi);var Ic={},bi={};const _i=Hs(Tc);var Gn={};Object.defineProperty(Gn,"__esModule",{value:!0});var Vo=_i,V1=function(){function t(e){if(this._maxConcurrency=e,this._queue=[],e<=0)throw new Error("semaphore must be initialized to a positive value");this._value=e}return t.prototype.acquire=function(){var e=this,r=this.isLocked(),n=new Promise(function(i){return e._queue.push(i)});return r||this._dispatch(),n},t.prototype.runExclusive=function(e){return Vo.__awaiter(this,void 0,void 0,function(){var r,n,i;return Vo.__generator(this,function(s){switch(s.label){case 0:return[4,this.acquire()];case 1:r=s.sent(),n=r[0],i=r[1],s.label=2;case 2:return s.trys.push([2,,4,5]),[4,e(n)];case 3:return[2,s.sent()];case 4:return i(),[7];case 5:return[2]}})})},t.prototype.isLocked=function(){return this._value<=0},t.prototype.release=function(){if(this._maxConcurrency>1)throw new Error("this method is unavailabel on semaphores with concurrency > 1; use the scoped release returned by acquire instead");if(this._currentReleaser){var e=this._currentReleaser;this._currentReleaser=void 0,e()}},t.prototype._dispatch=function(){var e=this,r=this._queue.shift();if(r){var n=!1;this._currentReleaser=function(){n||(n=!0,e._value++,e._dispatch())},r([this._value--,this._currentReleaser])}},t}();Gn.default=V1;Object.defineProperty(bi,"__esModule",{value:!0});var Wo=_i,W1=Gn,z1=function(){function t(){this._semaphore=new W1.default(1)}return t.prototype.acquire=function(){return Wo.__awaiter(this,void 0,void 0,function(){var e,r;return Wo.__generator(this,function(n){switch(n.label){case 0:return[4,this._semaphore.acquire()];case 1:return e=n.sent(),r=e[1],[2,r]}})})},t.prototype.runExclusive=function(e){return this._semaphore.runExclusive(function(){return e()})},t.prototype.isLocked=function(){return this._semaphore.isLocked()},t.prototype.release=function(){this._semaphore.release()},t}();bi.default=z1;var Zn={};Object.defineProperty(Zn,"__esModule",{value:!0});Zn.withTimeout=void 0;var en=_i;function q1(t,e,r){var n=this;return r===void 0&&(r=new Error("timeout")),{acquire:function(){return new Promise(function(i,s){return en.__awaiter(n,void 0,void 0,function(){var c,u,d;return en.__generator(this,function(h){switch(h.label){case 0:return c=!1,setTimeout(function(){c=!0,s(r)},e),[4,t.acquire()];case 1:return u=h.sent(),c?(d=Array.isArray(u)?u[1]:u,d()):i(u),[2]}})})})},runExclusive:function(i){return en.__awaiter(this,void 0,void 0,function(){var s,c;return en.__generator(this,function(u){switch(u.label){case 0:s=function(){},u.label=1;case 1:return u.trys.push([1,,7,8]),[4,this.acquire()];case 2:return c=u.sent(),Array.isArray(c)?(s=c[1],[4,i(c[0])]):[3,4];case 3:return[2,u.sent()];case 4:return s=c,[4,i()];case 5:return[2,u.sent()];case 6:return[3,8];case 7:return s(),[7];case 8:return[2]}})})},release:function(){t.release()},isLocked:function(){return t.isLocked()}}}Zn.withTimeout=q1;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.withTimeout=t.Semaphore=t.Mutex=void 0;var e=bi;Object.defineProperty(t,"Mutex",{enumerable:!0,get:function(){return e.default}});var r=Gn;Object.defineProperty(t,"Semaphore",{enumerable:!0,get:function(){return r.default}});var n=Zn;Object.defineProperty(t,"withTimeout",{enumerable:!0,get:function(){return n.withTimeout}})})(Ic);var J1=Z1,G1=Object.prototype.hasOwnProperty;function Z1(){for(var t={},e=0;efunction(...i){const s=e.promiseModule;return new s((c,u)=>{e.multiArgs?i.push((...h)=>{e.errorFirst?h[0]?u(h):(h.shift(),c(h)):c(h)}):e.errorFirst?i.push((h,y)=>{h?u(h):c(y)}):i.push(c),Reflect.apply(t,this===r?n:this,i)})},qo=new WeakMap;var eg=(t,e)=>{e={exclude:[/.+(?:Sync|Stream)$/],errorFirst:!0,promiseModule:Promise,...e};const r=typeof t;if(!(t!==null&&(r==="object"||r==="function")))throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${t===null?"null":r}\``);const n=(c,u)=>{let d=qo.get(c);if(d||(d={},qo.set(c,d)),u in d)return d[u];const h=k=>typeof k=="string"||typeof u=="symbol"?u===k:k.test(u),y=Reflect.getOwnPropertyDescriptor(c,u),S=y===void 0||y.writable||y.configurable,M=(e.include?e.include.some(h):!e.exclude.some(h))&&S;return d[u]=M,M},i=new WeakMap,s=new Proxy(t,{apply(c,u,d){const h=i.get(c);if(h)return Reflect.apply(h,u,d);const y=e.excludeMain?c:zo(c,e,s,c);return i.set(c,y),Reflect.apply(y,u,d)},get(c,u){const d=c[u];if(!n(c,u)||d===Function.prototype[u])return d;const h=i.get(d);if(h)return h;if(typeof d=="function"){const y=zo(d,e,s,c);return i.set(d,y),y}return d}});return s};const tg=Pr.default;let rg=class extends tg{constructor(){super(),this.updates=[]}async initialize(){}async update(){throw new Error("BaseFilter - no update method specified")}addResults(e){this.updates=this.updates.concat(e),e.forEach(r=>this.emit("update",r))}addInitialResults(e){}getChangesAndClear(){const e=this.updates;return this.updates=[],e}};var Ei=rg;const ng=Ei;let sg=class extends ng{constructor(){super(),this.allResults=[]}async update(){throw new Error("BaseFilterWithHistory - no update method specified")}addResults(e){this.allResults=this.allResults.concat(e),super.addResults(e)}addInitialResults(e){this.allResults=this.allResults.concat(e),super.addInitialResults(e)}getAllResults(){return this.allResults}};var ig=sg,Vr={minBlockRef:og,maxBlockRef:ag,sortBlockRefs:Si,bnToHex:cg,blockRefIsNumber:lg,hexToInt:on,incrementHexInt:ug,intToHex:Cc,unsafeRandomBytes:dg};function og(...t){return Si(t)[0]}function ag(...t){const e=Si(t);return e[e.length-1]}function Si(t){return t.sort((e,r)=>e==="latest"||r==="earliest"?1:r==="latest"||e==="earliest"?-1:on(e)-on(r))}function cg(t){return"0x"+t.toString(16)}function lg(t){return t&&!["earliest","latest","pending"].includes(t)}function on(t){return t==null?t:Number.parseInt(t,16)}function ug(t){if(t==null)return t;const e=on(t);return Cc(e+1)}function Cc(t){if(t==null)return t;let e=t.toString(16);return e.length%2&&(e="0"+e),"0x"+e}function dg(t){let e="0x";for(let r=0;rn.toLowerCase()))}async initialize({currentBlock:e}){let r=this.params.fromBlock;["latest","pending"].includes(r)&&(r=e),r==="earliest"&&(r="0x0"),this.params.fromBlock=r;const n=mg(this.params.toBlock,e),i=Object.assign({},this.params,{toBlock:n}),s=await this._fetchLogs(i);this.addInitialResults(s)}async update({oldBlock:e,newBlock:r}){const n=r;let i;e?i=pg(e):i=r;const s=Object.assign({},this.params,{fromBlock:i,toBlock:n}),u=(await this._fetchLogs(s)).filter(d=>this.matchLog(d));this.addResults(u)}async _fetchLogs(e){return await fg(n=>this.ethQuery.getLogs(e,n))()}matchLog(e){if(tn(this.params.fromBlock)>=tn(e.blockNumber)||vg(this.params.toBlock)&&tn(this.params.toBlock)<=tn(e.blockNumber))return!1;const r=e.address&&e.address.toLowerCase();return this.params.address&&r&&!this.params.address.includes(r)?!1:this.params.topics.every((i,s)=>{let c=e.topics[s];if(!c)return!1;c=c.toLowerCase();let u=Array.isArray(i)?i:[i];return u.includes(null)?!0:(u=u.map(y=>y.toLowerCase()),u.includes(c))})}};var yg=wg,Mi=bg;async function bg({provider:t,fromBlock:e,toBlock:r}){e||(e=r);const n=Go(e),s=Go(r)-n+1,c=Array(s).fill().map((d,h)=>n+h).map(_g);let u=await Promise.all(c.map(d=>Sg(t,"eth_getBlockByNumber",[d,!1])));return u=u.filter(d=>d!==null),u}function Go(t){return t==null?t:Number.parseInt(t,16)}function _g(t){return t==null?t:"0x"+t.toString(16)}function Eg(t,e){return new Promise((r,n)=>{t.sendAsync(e,(i,s)=>{i?n(i):s.error?n(s.error):s.result?r(s.result):n(new Error("Result was empty"))})})}async function Sg(t,e,r){for(let n=0;n<3;n++)try{return await Eg(t,{id:1,jsonrpc:"2.0",method:e,params:r})}catch(i){console.error(`provider.sendAsync failed: ${i.stack||i.message||i}`)}return null}const Mg=Ei,kg=Mi,{incrementHexInt:Rg}=Vr;let Ig=class extends Mg{constructor({provider:e,params:r}){super(),this.type="block",this.provider=e}async update({oldBlock:e,newBlock:r}){const n=r,i=Rg(e),c=(await kg({provider:this.provider,fromBlock:i,toBlock:n})).map(u=>u.hash);this.addResults(c)}};var Cg=Ig;const Ag=Ei,Ng=Mi,{incrementHexInt:Lg}=Vr;let xg=class extends Ag{constructor({provider:e}){super(),this.type="tx",this.provider=e}async update({oldBlock:e}){const r=e,n=Lg(e),i=await Ng({provider:this.provider,fromBlock:n,toBlock:r}),s=[];for(const c of i)s.push(...c.transactions);this.addResults(s)}};var Tg=xg;const Pg=Ic.Mutex,{createAsyncMiddleware:$g,createScaffoldMiddleware:Og}=mi,Bg=yg,Dg=Cg,jg=Tg,{intToHex:Ac,hexToInt:Ts}=Vr;var Fg=Hg;function Hg({blockTracker:t,provider:e}){let r=0,n={};const i=new Pg,s=Ug({mutex:i}),c=Og({eth_newFilter:s(Ps(d)),eth_newBlockFilter:s(Ps(h)),eth_newPendingTransactionFilter:s(Ps(y)),eth_uninstallFilter:s(nn(M)),eth_getFilterChanges:s(nn(S)),eth_getFilterLogs:s(nn(E))}),u=async({oldBlock:L,newBlock:R})=>{if(n.length===0)return;const z=await i.acquire();try{await Promise.all(Zt(n).map(async C=>{try{await C.update({oldBlock:L,newBlock:R})}catch(P){console.error(P)}}))}catch(C){console.error(C)}z()};return c.newLogFilter=d,c.newBlockFilter=h,c.newPendingTransactionFilter=y,c.uninstallFilter=M,c.getFilterChanges=S,c.getFilterLogs=E,c.destroy=()=>{O()},c;async function d(L){const R=new Bg({provider:e,params:L});return await k(R),R}async function h(){const L=new Dg({provider:e});return await k(L),L}async function y(){const L=new jg({provider:e});return await k(L),L}async function S(L){const R=Ts(L),z=n[R];if(!z)throw new Error(`No filter for index "${R}"`);return z.getChangesAndClear()}async function E(L){const R=Ts(L),z=n[R];if(!z)throw new Error(`No filter for index "${R}"`);let C=[];return z.type==="log"&&(C=z.getAllResults()),C}async function M(L){const R=Ts(L),C=!!n[R];return C&&await T(R),C}async function k(L){const R=Zt(n).length,z=await t.getLatestBlock();await L.initialize({currentBlock:z}),r++,n[r]=L,L.id=r,L.idHex=Ac(r);const C=Zt(n).length;return B({prevFilterCount:R,newFilterCount:C}),r}async function T(L){const R=Zt(n).length;delete n[L];const z=Zt(n).length;B({prevFilterCount:R,newFilterCount:z})}async function O(){const L=Zt(n).length;n={},B({prevFilterCount:L,newFilterCount:0})}function B({prevFilterCount:L,newFilterCount:R}){if(L===0&&R>0){t.on("sync",u);return}if(L>0&&R===0){t.removeListener("sync",u);return}}}function Ps(t){return nn(async(...e)=>{const r=await t(...e);return Ac(r.id)})}function nn(t){return $g(async(e,r)=>{const n=await t.apply(null,e.params);r.result=n})}function Ug({mutex:t}){return e=>async(r,n,i,s)=>{(await t.acquire())(),e(r,n,i,s)}}function Zt(t,e){const r=[];for(let n in t)r.push(t[n]);return r}const Vg=Pr.default,{createAsyncMiddleware:Zo,createScaffoldMiddleware:Wg}=mi,zg=Fg,{unsafeRandomBytes:qg,incrementHexInt:Jg}=Vr,Gg=Mi;var Zg=Qg;function Qg({blockTracker:t,provider:e}){const r={},n=zg({blockTracker:t,provider:e});let i=!1;const s=new Vg,c=Wg({eth_subscribe:Zo(u),eth_unsubscribe:Zo(d)});return c.destroy=y,{events:s,middleware:c};async function u(S,E){if(i)throw new Error("SubscriptionManager - attempting to use after destroying");const M=S.params[0],k=qg(16);let T;switch(M){case"newHeads":T=O({subId:k});break;case"logs":const L=S.params[1],R=await n.newLogFilter(L);T=B({subId:k,filter:R});break;default:throw new Error(`SubscriptionManager - unsupported subscription type "${M}"`)}r[k]=T,E.result=k;return;function O({subId:L}){const R={type:M,destroy:async()=>{t.removeListener("sync",R.update)},update:async({oldBlock:z,newBlock:C})=>{const P=C,J=Jg(z);(await Gg({provider:e,fromBlock:J,toBlock:P})).map(Kg).filter(Y=>Y!==null).forEach(Y=>{h(L,Y)})}};return t.on("sync",R.update),R}function B({subId:L,filter:R}){return R.on("update",C=>h(L,C)),{type:M,destroy:async()=>await n.uninstallFilter(R.idHex)}}}async function d(S,E){if(i)throw new Error("SubscriptionManager - attempting to use after destroying");const M=S.params[0],k=r[M];if(!k){E.result=!1;return}delete r[M],await k.destroy(),E.result=!0}function h(S,E){s.emit("notification",{jsonrpc:"2.0",method:"eth_subscription",params:{subscription:S,result:E}})}function y(){s.removeAllListeners();for(const S in r)r[S].destroy(),delete r[S];i=!0}}function Kg(t){return t==null?null:{hash:t.hash,parentHash:t.parentHash,sha3Uncles:t.sha3Uncles,miner:t.miner,stateRoot:t.stateRoot,transactionsRoot:t.transactionsRoot,receiptsRoot:t.receiptsRoot,logsBloom:t.logsBloom,difficulty:t.difficulty,number:t.number,gasLimit:t.gasLimit,gasUsed:t.gasUsed,nonce:t.nonce,mixHash:t.mixHash,timestamp:t.timestamp,extraData:t.extraData}}Object.defineProperty(xn,"__esModule",{value:!0});xn.SubscriptionManager=void 0;const Xg=$a,Yg=Zg,Qo=()=>{};class ep{constructor(e){const r=new Xg.PollingBlockTracker({provider:e,pollingInterval:15e3,setSkipCacheFlag:!0}),{events:n,middleware:i}=Yg({blockTracker:r,provider:e});this.events=n,this.subscriptionMiddleware=i}async handleRequest(e){const r={};return await this.subscriptionMiddleware(e,r,Qo,Qo),r}destroy(){this.subscriptionMiddleware.destroy()}}xn.SubscriptionManager=ep;var Nc=x&&x.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(rr,"__esModule",{value:!0});rr.CoinbaseWalletProvider=void 0;const tp=Nc(un),rp=Dc,U=Sr,j=A,np=Ir,Ko=it,rn=dr,Ye=cr,$s=Nc(Du),wr=ur,sp=ir,ip=xn,Xo="DefaultChainId",Yo="DefaultJsonRpcUrl";class op extends rp.EventEmitter{constructor(e){var r,n;super(),this._filterPolyfill=new sp.FilterPolyfill(this),this._subscriptionManager=new ip.SubscriptionManager(this),this._relay=null,this._addresses=[],this.hasMadeFirstChainChangedEmission=!1,this.setProviderInfo=this.setProviderInfo.bind(this),this.updateProviderInfo=this.updateProviderInfo.bind(this),this.getChainId=this.getChainId.bind(this),this.setAppInfo=this.setAppInfo.bind(this),this.enable=this.enable.bind(this),this.close=this.close.bind(this),this.send=this.send.bind(this),this.sendAsync=this.sendAsync.bind(this),this.request=this.request.bind(this),this._setAddresses=this._setAddresses.bind(this),this.scanQRCode=this.scanQRCode.bind(this),this.genericRequest=this.genericRequest.bind(this),this._chainIdFromOpts=e.chainId,this._jsonRpcUrlFromOpts=e.jsonRpcUrl,this._overrideIsMetaMask=e.overrideIsMetaMask,this._relayProvider=e.relayProvider,this._storage=e.storage,this._relayEventManager=e.relayEventManager,this.diagnostic=e.diagnosticLogger,this.reloadOnDisconnect=!0,this.isCoinbaseWallet=(r=e.overrideIsCoinbaseWallet)!==null&&r!==void 0?r:!0,this.isCoinbaseBrowser=(n=e.overrideIsCoinbaseBrowser)!==null&&n!==void 0?n:!1,this.qrUrl=e.qrUrl;const i=this.getChainId(),s=(0,j.prepend0x)(i.toString(16));this.emit("connect",{chainIdStr:s});const c=this._storage.getItem(Ko.LOCAL_STORAGE_ADDRESSES_KEY);if(c){const u=c.split(" ");u[0]!==""&&(this._addresses=u.map(d=>(0,j.ensureAddressString)(d)),this.emit("accountsChanged",u))}this._subscriptionManager.events.on("notification",u=>{this.emit("message",{type:u.method,data:u.params})}),this._isAuthorized()&&this.initializeRelay(),window.addEventListener("message",u=>{var d;if(!(u.origin!==location.origin||u.source!==window)&&u.data.type==="walletLinkMessage"&&u.data.data.action==="dappChainSwitched"){const h=u.data.data.chainId,y=(d=u.data.data.jsonRpcUrl)!==null&&d!==void 0?d:this.jsonRpcUrl;this.updateProviderInfo(y,Number(h))}})}get selectedAddress(){return this._addresses[0]||void 0}get networkVersion(){return this.getChainId().toString(10)}get chainId(){return(0,j.prepend0x)(this.getChainId().toString(16))}get isWalletLink(){return!0}get isMetaMask(){return this._overrideIsMetaMask}get host(){return this.jsonRpcUrl}get connected(){return!0}isConnected(){return!0}get jsonRpcUrl(){var e;return(e=this._storage.getItem(Yo))!==null&&e!==void 0?e:this._jsonRpcUrlFromOpts}set jsonRpcUrl(e){this._storage.setItem(Yo,e)}disableReloadOnDisconnect(){this.reloadOnDisconnect=!1}setProviderInfo(e,r){this.isCoinbaseBrowser||(this._chainIdFromOpts=r,this._jsonRpcUrlFromOpts=e),this.updateProviderInfo(this.jsonRpcUrl,this.getChainId())}updateProviderInfo(e,r){this.jsonRpcUrl=e;const n=this.getChainId();this._storage.setItem(Xo,r.toString(10)),((0,j.ensureIntNumber)(r)!==n||!this.hasMadeFirstChainChangedEmission)&&(this.emit("chainChanged",this.getChainId()),this.hasMadeFirstChainChangedEmission=!0)}async watchAsset(e,r,n,i,s,c){const d=await(await this.initializeRelay()).watchAsset(e,r,n,i,s,c==null?void 0:c.toString()).promise;return(0,Ye.isErrorResponse)(d)?!1:!!d.result}async addEthereumChain(e,r,n,i,s,c){var u,d;if((0,j.ensureIntNumber)(e)===this.getChainId())return!1;const h=await this.initializeRelay(),y=h.inlineAddEthereumChain(e.toString());!this._isAuthorized()&&!y&&await h.requestEthereumAccounts().promise;const S=await h.addEthereumChain(e.toString(),r,s,n,i,c).promise;return(0,Ye.isErrorResponse)(S)?!1:(((u=S.result)===null||u===void 0?void 0:u.isApproved)===!0&&this.updateProviderInfo(r[0],e),((d=S.result)===null||d===void 0?void 0:d.isApproved)===!0)}async switchEthereumChain(e){const n=await(await this.initializeRelay()).switchEthereumChain(e.toString(10),this.selectedAddress||void 0).promise;if((0,Ye.isErrorResponse)(n)){if(!n.errorCode)return;throw n.errorCode===U.standardErrorCodes.provider.unsupportedChain?U.standardErrors.provider.unsupportedChain():U.standardErrors.provider.custom({message:n.errorMessage,code:n.errorCode})}const i=n.result;i.isApproved&&i.rpcUrl.length>0&&this.updateProviderInfo(i.rpcUrl,e)}setAppInfo(e,r){this.initializeRelay().then(n=>n.setAppInfo(e,r))}async enable(){var e;return(e=this.diagnostic)===null||e===void 0||e.log(wr.EVENTS.ETH_ACCOUNTS_STATE,{method:"provider::enable",addresses_length:this._addresses.length,sessionIdHash:this._relay?rn.Session.hash(this._relay.session.id):void 0}),this._isAuthorized()?[...this._addresses]:await this.send("eth_requestAccounts")}async close(){(await this.initializeRelay()).resetAndReload()}send(e,r){try{const n=this._send(e,r);if(n instanceof Promise)return n.catch(i=>{throw(0,U.serializeError)(i,e)})}catch(n){throw(0,U.serializeError)(n,e)}}_send(e,r){if(typeof e=="string"){const i=e,s=Array.isArray(r)?r:r!==void 0?[r]:[],c={jsonrpc:"2.0",id:0,method:i,params:s};return this._sendRequestAsync(c).then(u=>u.result)}if(typeof r=="function"){const i=e,s=r;return this._sendAsync(i,s)}if(Array.isArray(e))return e.map(s=>this._sendRequest(s));const n=e;return this._sendRequest(n)}async sendAsync(e,r){try{return this._sendAsync(e,r).catch(n=>{throw(0,U.serializeError)(n,e)})}catch(n){return Promise.reject((0,U.serializeError)(n,e))}}async _sendAsync(e,r){if(typeof r!="function")throw new Error("callback is required");if(Array.isArray(e)){const i=r;this._sendMultipleRequestsAsync(e).then(s=>i(null,s)).catch(s=>i(s,null));return}const n=r;return this._sendRequestAsync(e).then(i=>n(null,i)).catch(i=>n(i,null))}async request(e){try{return this._request(e).catch(r=>{throw(0,U.serializeError)(r,e.method)})}catch(r){return Promise.reject((0,U.serializeError)(r,e.method))}}async _request(e){if(!e||typeof e!="object"||Array.isArray(e))throw U.standardErrors.rpc.invalidRequest({message:"Expected a single, non-array, object argument.",data:e});const{method:r,params:n}=e;if(typeof r!="string"||r.length===0)throw U.standardErrors.rpc.invalidRequest({message:"'args.method' must be a non-empty string.",data:e});if(n!==void 0&&!Array.isArray(n)&&(typeof n!="object"||n===null))throw U.standardErrors.rpc.invalidRequest({message:"'args.params' must be an object or array if provided.",data:e});const i=n===void 0?[]:n,s=this._relayEventManager.makeRequestId();return(await this._sendRequestAsync({method:r,params:i,jsonrpc:"2.0",id:s})).result}async scanQRCode(e){const n=await(await this.initializeRelay()).scanQRCode((0,j.ensureRegExpString)(e)).promise;if((0,Ye.isErrorResponse)(n))throw(0,U.serializeError)(n.errorMessage,"scanQRCode");if(typeof n.result!="string")throw(0,U.serializeError)("result was not a string","scanQRCode");return n.result}async genericRequest(e,r){const i=await(await this.initializeRelay()).genericRequest(e,r).promise;if((0,Ye.isErrorResponse)(i))throw(0,U.serializeError)(i.errorMessage,"generic");if(typeof i.result!="string")throw(0,U.serializeError)("result was not a string","generic");return i.result}async connectAndSignIn(e){var r;(r=this.diagnostic)===null||r===void 0||r.log(wr.EVENTS.ETH_ACCOUNTS_STATE,{method:"provider::connectAndSignIn",sessionIdHash:this._relay?rn.Session.hash(this._relay.session.id):void 0});let n;try{const s=await this.initializeRelay();if(!(s instanceof np.MobileRelay))throw new Error("connectAndSignIn is only supported on mobile");if(n=await s.connectAndSignIn(e).promise,(0,Ye.isErrorResponse)(n))throw new Error(n.errorMessage)}catch(s){throw typeof s.message=="string"&&s.message.match(/(denied|rejected)/i)?U.standardErrors.provider.userRejectedRequest("User denied account authorization"):s}if(!n.result)throw new Error("accounts received is empty");const{accounts:i}=n.result;return this._setAddresses(i),this.isCoinbaseBrowser||await this.switchEthereumChain(this.getChainId()),n.result}async selectProvider(e){const n=await(await this.initializeRelay()).selectProvider(e).promise;if((0,Ye.isErrorResponse)(n))throw(0,U.serializeError)(n.errorMessage,"selectProvider");if(typeof n.result!="string")throw(0,U.serializeError)("result was not a string","selectProvider");return n.result}supportsSubscriptions(){return!1}subscribe(){throw new Error("Subscriptions are not supported")}unsubscribe(){throw new Error("Subscriptions are not supported")}disconnect(){return!0}_sendRequest(e){const r={jsonrpc:"2.0",id:e.id},{method:n}=e;if(r.result=this._handleSynchronousMethods(e),r.result===void 0)throw new Error(`Coinbase Wallet does not support calling ${n} synchronously without a callback. Please provide a callback parameter to call ${n} asynchronously.`);return r}_setAddresses(e,r){if(!Array.isArray(e))throw new Error("addresses is not an array");const n=e.map(i=>(0,j.ensureAddressString)(i));JSON.stringify(n)!==JSON.stringify(this._addresses)&&(this._addresses=n,this.emit("accountsChanged",this._addresses),this._storage.setItem(Ko.LOCAL_STORAGE_ADDRESSES_KEY,n.join(" ")))}_sendRequestAsync(e){return new Promise((r,n)=>{try{const i=this._handleSynchronousMethods(e);if(i!==void 0)return r({jsonrpc:"2.0",id:e.id,result:i});const s=this._handleAsynchronousFilterMethods(e);if(s!==void 0){s.then(u=>r(Object.assign(Object.assign({},u),{id:e.id}))).catch(u=>n(u));return}const c=this._handleSubscriptionMethods(e);if(c!==void 0){c.then(u=>r({jsonrpc:"2.0",id:e.id,result:u.result})).catch(u=>n(u));return}}catch(i){return n(i)}this._handleAsynchronousMethods(e).then(i=>i&&r(Object.assign(Object.assign({},i),{id:e.id}))).catch(i=>n(i))})}_sendMultipleRequestsAsync(e){return Promise.all(e.map(r=>this._sendRequestAsync(r)))}_handleSynchronousMethods(e){const{method:r}=e,n=e.params||[];switch(r){case"eth_accounts":return this._eth_accounts();case"eth_coinbase":return this._eth_coinbase();case"eth_uninstallFilter":return this._eth_uninstallFilter(n);case"net_version":return this._net_version();case"eth_chainId":return this._eth_chainId();default:return}}async _handleAsynchronousMethods(e){const{method:r}=e,n=e.params||[];switch(r){case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_sign":return this._eth_sign(n);case"eth_ecRecover":return this._eth_ecRecover(n);case"personal_sign":return this._personal_sign(n);case"personal_ecRecover":return this._personal_ecRecover(n);case"eth_signTransaction":return this._eth_signTransaction(n);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(n);case"eth_sendTransaction":return this._eth_sendTransaction(n);case"eth_signTypedData_v1":return this._eth_signTypedData_v1(n);case"eth_signTypedData_v2":return this._throwUnsupportedMethodError();case"eth_signTypedData_v3":return this._eth_signTypedData_v3(n);case"eth_signTypedData_v4":case"eth_signTypedData":return this._eth_signTypedData_v4(n);case"cbWallet_arbitrary":return this._cbwallet_arbitrary(n);case"wallet_addEthereumChain":return this._wallet_addEthereumChain(n);case"wallet_switchEthereumChain":return this._wallet_switchEthereumChain(n);case"wallet_watchAsset":return this._wallet_watchAsset(n)}return(await this.initializeRelay()).makeEthereumJSONRPCRequest(e,this.jsonRpcUrl).catch(s=>{var c;throw(s.code===U.standardErrorCodes.rpc.methodNotFound||s.code===U.standardErrorCodes.rpc.methodNotSupported)&&((c=this.diagnostic)===null||c===void 0||c.log(wr.EVENTS.METHOD_NOT_IMPLEMENTED,{method:e.method,sessionIdHash:this._relay?rn.Session.hash(this._relay.session.id):void 0})),s})}_handleAsynchronousFilterMethods(e){const{method:r}=e,n=e.params||[];switch(r){case"eth_newFilter":return this._eth_newFilter(n);case"eth_newBlockFilter":return this._eth_newBlockFilter();case"eth_newPendingTransactionFilter":return this._eth_newPendingTransactionFilter();case"eth_getFilterChanges":return this._eth_getFilterChanges(n);case"eth_getFilterLogs":return this._eth_getFilterLogs(n)}}_handleSubscriptionMethods(e){switch(e.method){case"eth_subscribe":case"eth_unsubscribe":return this._subscriptionManager.handleRequest(e)}}_isKnownAddress(e){try{const r=(0,j.ensureAddressString)(e);return this._addresses.map(i=>(0,j.ensureAddressString)(i)).includes(r)}catch{}return!1}_ensureKnownAddress(e){var r;if(!this._isKnownAddress(e))throw(r=this.diagnostic)===null||r===void 0||r.log(wr.EVENTS.UNKNOWN_ADDRESS_ENCOUNTERED),new Error("Unknown Ethereum address")}_prepareTransactionParams(e){const r=e.from?(0,j.ensureAddressString)(e.from):this.selectedAddress;if(!r)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(r);const n=e.to?(0,j.ensureAddressString)(e.to):null,i=e.value!=null?(0,j.ensureBN)(e.value):new tp.default(0),s=e.data?(0,j.ensureBuffer)(e.data):Buffer.alloc(0),c=e.nonce!=null?(0,j.ensureIntNumber)(e.nonce):null,u=e.gasPrice!=null?(0,j.ensureBN)(e.gasPrice):null,d=e.maxFeePerGas!=null?(0,j.ensureBN)(e.maxFeePerGas):null,h=e.maxPriorityFeePerGas!=null?(0,j.ensureBN)(e.maxPriorityFeePerGas):null,y=e.gas!=null?(0,j.ensureBN)(e.gas):null,S=e.chainId?(0,j.ensureIntNumber)(e.chainId):this.getChainId();return{fromAddress:r,toAddress:n,weiValue:i,data:s,nonce:c,gasPriceInWei:u,maxFeePerGas:d,maxPriorityFeePerGas:h,gasLimit:y,chainId:S}}_isAuthorized(){return this._addresses.length>0}_requireAuthorization(){if(!this._isAuthorized())throw U.standardErrors.provider.unauthorized({})}_throwUnsupportedMethodError(){throw U.standardErrors.provider.unsupportedMethod({})}async _signEthereumMessage(e,r,n,i){this._ensureKnownAddress(r);try{const c=await(await this.initializeRelay()).signEthereumMessage(e,r,n,i).promise;if((0,Ye.isErrorResponse)(c))throw new Error(c.errorMessage);return{jsonrpc:"2.0",id:0,result:c.result}}catch(s){throw typeof s.message=="string"&&s.message.match(/(denied|rejected)/i)?U.standardErrors.provider.userRejectedRequest("User denied message signature"):s}}async _ethereumAddressFromSignedMessage(e,r,n){const s=await(await this.initializeRelay()).ethereumAddressFromSignedMessage(e,r,n).promise;if((0,Ye.isErrorResponse)(s))throw new Error(s.errorMessage);return{jsonrpc:"2.0",id:0,result:s.result}}_eth_accounts(){return[...this._addresses]}_eth_coinbase(){return this.selectedAddress||null}_net_version(){return this.getChainId().toString(10)}_eth_chainId(){return(0,j.hexStringFromIntNumber)(this.getChainId())}getChainId(){const e=this._storage.getItem(Xo);if(!e)return(0,j.ensureIntNumber)(this._chainIdFromOpts);const r=parseInt(e,10);return(0,j.ensureIntNumber)(r)}async _eth_requestAccounts(){var e;if((e=this.diagnostic)===null||e===void 0||e.log(wr.EVENTS.ETH_ACCOUNTS_STATE,{method:"provider::_eth_requestAccounts",addresses_length:this._addresses.length,sessionIdHash:this._relay?rn.Session.hash(this._relay.session.id):void 0}),this._isAuthorized())return Promise.resolve({jsonrpc:"2.0",id:0,result:this._addresses});let r;try{if(r=await(await this.initializeRelay()).requestEthereumAccounts().promise,(0,Ye.isErrorResponse)(r))throw new Error(r.errorMessage)}catch(n){throw typeof n.message=="string"&&n.message.match(/(denied|rejected)/i)?U.standardErrors.provider.userRejectedRequest("User denied account authorization"):n}if(!r.result)throw new Error("accounts received is empty");return this._setAddresses(r.result),this.isCoinbaseBrowser||await this.switchEthereumChain(this.getChainId()),{jsonrpc:"2.0",id:0,result:this._addresses}}_eth_sign(e){this._requireAuthorization();const r=(0,j.ensureAddressString)(e[0]),n=(0,j.ensureBuffer)(e[1]);return this._signEthereumMessage(n,r,!1)}_eth_ecRecover(e){const r=(0,j.ensureBuffer)(e[0]),n=(0,j.ensureBuffer)(e[1]);return this._ethereumAddressFromSignedMessage(r,n,!1)}_personal_sign(e){this._requireAuthorization();const r=(0,j.ensureBuffer)(e[0]),n=(0,j.ensureAddressString)(e[1]);return this._signEthereumMessage(r,n,!0)}_personal_ecRecover(e){const r=(0,j.ensureBuffer)(e[0]),n=(0,j.ensureBuffer)(e[1]);return this._ethereumAddressFromSignedMessage(r,n,!0)}async _eth_signTransaction(e){this._requireAuthorization();const r=this._prepareTransactionParams(e[0]||{});try{const i=await(await this.initializeRelay()).signEthereumTransaction(r).promise;if((0,Ye.isErrorResponse)(i))throw new Error(i.errorMessage);return{jsonrpc:"2.0",id:0,result:i.result}}catch(n){throw typeof n.message=="string"&&n.message.match(/(denied|rejected)/i)?U.standardErrors.provider.userRejectedRequest("User denied transaction signature"):n}}async _eth_sendRawTransaction(e){const r=(0,j.ensureBuffer)(e[0]),i=await(await this.initializeRelay()).submitEthereumTransaction(r,this.getChainId()).promise;if((0,Ye.isErrorResponse)(i))throw new Error(i.errorMessage);return{jsonrpc:"2.0",id:0,result:i.result}}async _eth_sendTransaction(e){this._requireAuthorization();const r=this._prepareTransactionParams(e[0]||{});try{const i=await(await this.initializeRelay()).signAndSubmitEthereumTransaction(r).promise;if((0,Ye.isErrorResponse)(i))throw new Error(i.errorMessage);return{jsonrpc:"2.0",id:0,result:i.result}}catch(n){throw typeof n.message=="string"&&n.message.match(/(denied|rejected)/i)?U.standardErrors.provider.userRejectedRequest("User denied transaction signature"):n}}async _eth_signTypedData_v1(e){this._requireAuthorization();const r=(0,j.ensureParsedJSONObject)(e[0]),n=(0,j.ensureAddressString)(e[1]);this._ensureKnownAddress(n);const i=$s.default.hashForSignTypedDataLegacy({data:r}),s=JSON.stringify(r,null,2);return this._signEthereumMessage(i,n,!1,s)}async _eth_signTypedData_v3(e){this._requireAuthorization();const r=(0,j.ensureAddressString)(e[0]),n=(0,j.ensureParsedJSONObject)(e[1]);this._ensureKnownAddress(r);const i=$s.default.hashForSignTypedData_v3({data:n}),s=JSON.stringify(n,null,2);return this._signEthereumMessage(i,r,!1,s)}async _eth_signTypedData_v4(e){this._requireAuthorization();const r=(0,j.ensureAddressString)(e[0]),n=(0,j.ensureParsedJSONObject)(e[1]);this._ensureKnownAddress(r);const i=$s.default.hashForSignTypedData_v4({data:n}),s=JSON.stringify(n,null,2);return this._signEthereumMessage(i,r,!1,s)}async _cbwallet_arbitrary(e){const r=e[0],n=e[1];if(typeof n!="string")throw new Error("parameter must be a string");if(typeof r!="object"||r===null)throw new Error("parameter must be an object");return{jsonrpc:"2.0",id:0,result:await this.genericRequest(r,n)}}async _wallet_addEthereumChain(e){var r,n,i,s;const c=e[0];if(((r=c.rpcUrls)===null||r===void 0?void 0:r.length)===0)return{jsonrpc:"2.0",id:0,error:{code:2,message:"please pass in at least 1 rpcUrl"}};if(!c.chainName||c.chainName.trim()==="")throw U.standardErrors.rpc.invalidParams("chainName is a required field");if(!c.nativeCurrency)throw U.standardErrors.rpc.invalidParams("nativeCurrency is a required field");const u=parseInt(c.chainId,16);return await this.addEthereumChain(u,(n=c.rpcUrls)!==null&&n!==void 0?n:[],(i=c.blockExplorerUrls)!==null&&i!==void 0?i:[],c.chainName,(s=c.iconUrls)!==null&&s!==void 0?s:[],c.nativeCurrency)?{jsonrpc:"2.0",id:0,result:null}:{jsonrpc:"2.0",id:0,error:{code:2,message:"unable to add ethereum chain"}}}async _wallet_switchEthereumChain(e){const r=e[0];return await this.switchEthereumChain(parseInt(r.chainId,16)),{jsonrpc:"2.0",id:0,result:null}}async _wallet_watchAsset(e){const r=Array.isArray(e)?e[0]:e;if(!r.type)throw U.standardErrors.rpc.invalidParams("Type is required");if((r==null?void 0:r.type)!=="ERC20")throw U.standardErrors.rpc.invalidParams(`Asset of type '${r.type}' is not supported`);if(!(r!=null&&r.options))throw U.standardErrors.rpc.invalidParams("Options are required");if(!(r!=null&&r.options.address))throw U.standardErrors.rpc.invalidParams("Address is required");const n=this.getChainId(),{address:i,symbol:s,image:c,decimals:u}=r.options;return{jsonrpc:"2.0",id:0,result:await this.watchAsset(r.type,i,s,u,c,n)}}_eth_uninstallFilter(e){const r=(0,j.ensureHexString)(e[0]);return this._filterPolyfill.uninstallFilter(r)}async _eth_newFilter(e){const r=e[0];return{jsonrpc:"2.0",id:0,result:await this._filterPolyfill.newFilter(r)}}async _eth_newBlockFilter(){return{jsonrpc:"2.0",id:0,result:await this._filterPolyfill.newBlockFilter()}}async _eth_newPendingTransactionFilter(){return{jsonrpc:"2.0",id:0,result:await this._filterPolyfill.newPendingTransactionFilter()}}_eth_getFilterChanges(e){const r=(0,j.ensureHexString)(e[0]);return this._filterPolyfill.getFilterChanges(r)}_eth_getFilterLogs(e){const r=(0,j.ensureHexString)(e[0]);return this._filterPolyfill.getFilterLogs(r)}initializeRelay(){return this._relay?Promise.resolve(this._relay):this._relayProvider().then(e=>(e.setAccountsCallback((r,n)=>this._setAddresses(r,n)),e.setChainCallback((r,n)=>{this.updateProviderInfo(n,parseInt(r,10))}),e.setDappDefaultChainCallback(this._chainIdFromOpts),this._relay=e,e))}}rr.CoinbaseWalletProvider=op;var Qn={};Object.defineProperty(Qn,"__esModule",{value:!0});Qn.RelayEventManager=void 0;const ap=A;class cp{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const e=this._nextRequestId,r=(0,ap.prepend0x)(e.toString(16));return this.callbacks.get(r)&&this.callbacks.delete(r),e}}Qn.RelayEventManager=cp;Object.defineProperty(br,"__esModule",{value:!0});br.CoinbaseWalletSDK=void 0;const lp=cn,up=ln,ea=A,dp=pn,hp=rr,fp=Ir,gp=xr,pp=Qn,mp=Ar,vp=Cr,Lc=lr;class Kn{constructor(e){var r,n,i;this._appName="",this._appLogoUrl=null,this._relay=null,this._relayEventManager=null;const s=e.linkAPIUrl||up.LINK_API_URL;typeof e.overrideIsMetaMask>"u"?this._overrideIsMetaMask=!1:this._overrideIsMetaMask=e.overrideIsMetaMask,this._overrideIsCoinbaseWallet=(r=e.overrideIsCoinbaseWallet)!==null&&r!==void 0?r:!0,this._overrideIsCoinbaseBrowser=(n=e.overrideIsCoinbaseBrowser)!==null&&n!==void 0?n:!1,this._diagnosticLogger=e.diagnosticLogger,this._reloadOnDisconnect=(i=e.reloadOnDisconnect)!==null&&i!==void 0?i:!0;const c=new URL(s),u=`${c.protocol}//${c.host}`;if(this._storage=new dp.ScopedLocalStorage(`-walletlink:${u}`),this._storage.setItem("version",Kn.VERSION),this.walletExtension||this.coinbaseBrowser)return;this._relayEventManager=new pp.RelayEventManager;const d=(0,ea.isMobileWeb)(),h=e.uiConstructor||(S=>d?new gp.MobileRelayUI(S):new mp.WalletLinkRelayUI(S)),y={linkAPIUrl:s,version:Lc.LIB_VERSION,darkMode:!!e.darkMode,headlessMode:!!e.headlessMode,uiConstructor:h,storage:this._storage,relayEventManager:this._relayEventManager,diagnosticLogger:this._diagnosticLogger,reloadOnDisconnect:this._reloadOnDisconnect,enableMobileWalletLink:e.enableMobileWalletLink};this._relay=d?new fp.MobileRelay(y):new vp.WalletLinkRelay(y),this.setAppInfo(e.appName,e.appLogoUrl),!e.headlessMode&&this._relay.attachUI()}makeWeb3Provider(e="",r=1){const n=this.walletExtension;if(n)return this.isCipherProvider(n)||n.setProviderInfo(e,r),this._reloadOnDisconnect===!1&&typeof n.disableReloadOnDisconnect=="function"&&n.disableReloadOnDisconnect(),n;const i=this.coinbaseBrowser;if(i)return i;const s=this._relay;if(!s||!this._relayEventManager||!this._storage)throw new Error("Relay not initialized, should never happen");return e||s.setConnectDisabled(!0),new hp.CoinbaseWalletProvider({relayProvider:()=>Promise.resolve(s),relayEventManager:this._relayEventManager,storage:this._storage,jsonRpcUrl:e,chainId:r,qrUrl:this.getQrUrl(),diagnosticLogger:this._diagnosticLogger,overrideIsMetaMask:this._overrideIsMetaMask,overrideIsCoinbaseWallet:this._overrideIsCoinbaseWallet,overrideIsCoinbaseBrowser:this._overrideIsCoinbaseBrowser})}setAppInfo(e,r){var n;this._appName=e||"DApp",this._appLogoUrl=r||(0,ea.getFavicon)();const i=this.walletExtension;i?this.isCipherProvider(i)||i.setAppInfo(this._appName,this._appLogoUrl):(n=this._relay)===null||n===void 0||n.setAppInfo(this._appName,this._appLogoUrl)}disconnect(){var e;const r=this===null||this===void 0?void 0:this.walletExtension;r?r.close():(e=this._relay)===null||e===void 0||e.resetAndReload()}getQrUrl(){var e,r;return(r=(e=this._relay)===null||e===void 0?void 0:e.getQRCodeUrl())!==null&&r!==void 0?r:null}getCoinbaseWalletLogo(e,r=240){return(0,lp.walletLogo)(e,r)}get walletExtension(){var e;return(e=window.coinbaseWalletExtension)!==null&&e!==void 0?e:window.walletLinkExtension}get coinbaseBrowser(){var e,r;try{const n=(e=window.ethereum)!==null&&e!==void 0?e:(r=window.top)===null||r===void 0?void 0:r.ethereum;return n&&"isCoinbaseBrowser"in n&&n.isCoinbaseBrowser?n:void 0}catch{return}}isCipherProvider(e){return typeof e.isCipher=="boolean"&&e.isCipher}}br.CoinbaseWalletSDK=Kn;Kn.VERSION=Lc.LIB_VERSION;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CoinbaseWalletProvider=t.CoinbaseWalletSDK=void 0;const e=br,r=rr;var n=br;Object.defineProperty(t,"CoinbaseWalletSDK",{enumerable:!0,get:function(){return n.CoinbaseWalletSDK}});var i=rr;Object.defineProperty(t,"CoinbaseWalletProvider",{enumerable:!0,get:function(){return i.CoinbaseWalletProvider}}),t.default=e.CoinbaseWalletSDK,typeof window<"u"&&(window.CoinbaseWalletSDK=e.CoinbaseWalletSDK,window.CoinbaseWalletProvider=r.CoinbaseWalletProvider,window.WalletLink=e.CoinbaseWalletSDK,window.WalletLinkProvider=r.CoinbaseWalletProvider)})(ra);const wp=Pc(ra),Tp=Object.freeze(Object.defineProperty({__proto__:null,default:wp},Symbol.toStringTag,{value:"Module"}));export{Tp as i}; diff --git a/buddybook/assets/index-Rg7xls9w.js b/buddybook/assets/index-Rg7xls9w.js new file mode 100644 index 0000000..706fd32 --- /dev/null +++ b/buddybook/assets/index-Rg7xls9w.js @@ -0,0 +1,2 @@ +import{k as m,c as q,e as k,t as F,n as Ye,i as Je,I as Ze,s as B,B as xe,a as G,b as en,d as N,f as V}from"./index-B-6Lwopd.js";const nn=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,tn=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function an(e){const{domain:n={},message:t,primaryType:i}=e,r={EIP712Domain:un({domain:n}),...e.types};on({domain:n,message:t,primaryType:i,types:r});const a=["0x1901"];return n&&a.push(sn({domain:n,types:r})),i!=="EIP712Domain"&&a.push($({data:t,primaryType:i,types:r})),m(q(a))}function sn({domain:e,types:n}){return $({data:e,primaryType:"EIP712Domain",types:n})}function $({data:e,primaryType:n,types:t}){const i=K({data:e,primaryType:n,types:t});return m(i)}function K({data:e,primaryType:n,types:t}){const i=[{type:"bytes32"}],r=[cn({primaryType:n,types:t})];for(const a of t[n]){const[u,l]=Q({types:t,name:a.name,type:a.type,value:e[a.name]});i.push(u),r.push(l)}return k(i,r)}function cn({primaryType:e,types:n}){const t=F(rn({primaryType:e,types:n}));return m(t)}function rn({primaryType:e,types:n}){let t="";const i=X({primaryType:e,types:n});i.delete(e);const r=[e,...Array.from(i).sort()];for(const a of r)t+=`${a}(${n[a].map(({name:u,type:l})=>`${l} ${u}`).join(",")})`;return t}function X({primaryType:e,types:n},t=new Set){const i=e.match(/^\w*/u),r=i==null?void 0:i[0];if(t.has(r)||n[r]===void 0)return t;t.add(r);for(const a of n[r])X({primaryType:a.type,types:n},t);return t}function Q({types:e,name:n,type:t,value:i}){if(e[t]!==void 0)return[{type:"bytes32"},m(K({data:i,primaryType:t,types:e}))];if(t==="bytes")return i=`0x${(i.length%2?"0":"")+i.slice(2)}`,[{type:"bytes32"},m(i)];if(t==="string")return[{type:"bytes32"},m(F(i))];if(t.lastIndexOf("]")===t.length-1){const r=t.slice(0,t.lastIndexOf("[")),a=i.map(u=>Q({name:n,type:r,types:e,value:u}));return[{type:"bytes32"},m(k(a.map(([u])=>u),a.map(([,u])=>u)))]}return[{type:t},i]}function on(e){const{domain:n,message:t,primaryType:i,types:r}=e,a=(u,l)=>{for(const f of u){const{name:v,type:g}=f,h=l[v],p=g.match(tn);if(p&&(typeof h=="number"||typeof h=="bigint")){const[M,S,L]=p;Ye(h,{signed:S==="int",size:Number.parseInt(L)/8})}if(g==="address"&&typeof h=="string"&&!Je(h))throw new Ze({address:h});const C=g.match(nn);if(C){const[M,S]=C;if(S&&B(h)!==Number.parseInt(S))throw new xe({expectedSize:Number.parseInt(S),givenSize:B(h)})}const D=r[g];D&&a(D,h)}};r.EIP712Domain&&n&&a(r.EIP712Domain,n),i!=="EIP712Domain"&&a(r[i],t)}function un({domain:e}){return[typeof(e==null?void 0:e.name)=="string"&&{name:"name",type:"string"},(e==null?void 0:e.version)&&{name:"version",type:"string"},typeof(e==null?void 0:e.chainId)=="number"&&{name:"chainId",type:"uint256"},(e==null?void 0:e.verifyingContract)&&{name:"verifyingContract",type:"address"},(e==null?void 0:e.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}const dn=`Ethereum Signed Message: +`;function ln(e){const n=typeof e=="string"?G(e):typeof e.raw=="string"?e.raw:en(e.raw),t=G(`${dn}${B(n)}`);return q([t,n])}function fn(e,n){return m(ln(e),n)}const gn=()=>"9.1.0",hn=e=>e.toString(16).padStart(2,"0"),En=e=>{const n=new Uint8Array(e/2);return window.crypto.getRandomValues(n),Array.from(n,hn).join("")},_n=()=>typeof window<"u"?En(10):new Date().getTime().toString(36);class w{}w.makeRequest=(e,n)=>({id:_n(),method:e,params:n,env:{sdkVersion:gn()}});w.makeResponse=(e,n,t)=>({id:e,success:!0,version:t,data:n});w.makeErrorResponse=(e,n,t)=>({id:e,success:!1,error:n,version:t});var E;(function(e){e.sendTransactions="sendTransactions",e.rpcCall="rpcCall",e.getChainInfo="getChainInfo",e.getSafeInfo="getSafeInfo",e.getTxBySafeTxHash="getTxBySafeTxHash",e.getSafeBalances="getSafeBalances",e.signMessage="signMessage",e.signTypedMessage="signTypedMessage",e.getEnvironmentInfo="getEnvironmentInfo",e.getOffChainSignature="getOffChainSignature",e.requestAddressBook="requestAddressBook",e.wallet_getPermissions="wallet_getPermissions",e.wallet_requestPermissions="wallet_requestPermissions"})(E||(E={}));var H;(function(e){e.requestAddressBook="requestAddressBook"})(H||(H={}));class yn{constructor(n=null,t=!1){this.allowedOrigins=null,this.callbacks=new Map,this.debugMode=!1,this.isServer=typeof window>"u",this.isValidMessage=({origin:i,data:r,source:a})=>{const u=!r,l=!this.isServer&&a===window.parent,f=typeof r.version<"u"&&parseInt(r.version.split(".")[0]),v=typeof f=="number"&&f>=1;let g=!0;return Array.isArray(this.allowedOrigins)&&(g=this.allowedOrigins.find(h=>h.test(i))!==void 0),!u&&l&&v&&g},this.logIncomingMessage=i=>{console.info(`Safe Apps SDK v1: A message was received from origin ${i.origin}. `,i.data)},this.onParentMessage=i=>{this.isValidMessage(i)&&(this.debugMode&&this.logIncomingMessage(i),this.handleIncomingMessage(i.data))},this.handleIncomingMessage=i=>{const{id:r}=i,a=this.callbacks.get(r);a&&(a(i),this.callbacks.delete(r))},this.send=(i,r)=>{const a=w.makeRequest(i,r);if(this.isServer)throw new Error("Window doesn't exist");return window.parent.postMessage(a,"*"),new Promise((u,l)=>{this.callbacks.set(a.id,f=>{if(!f.success){l(new Error(f.error));return}u(f)})})},this.allowedOrigins=n,this.debugMode=t,this.isServer||window.addEventListener("message",this.onParentMessage)}}const z=e=>typeof e=="object"&&e!=null&&"domain"in e&&"types"in e&&"message"in e;var Tn={},y={},T={},j=N&&N.__awaiter||function(e,n,t,i){function r(a){return a instanceof t?a:new t(function(u){u(a)})}return new(t||(t=Promise))(function(a,u){function l(g){try{v(i.next(g))}catch(h){u(h)}}function f(g){try{v(i.throw(g))}catch(h){u(h)}}function v(g){g.done?a(g.value):r(g.value).then(l,f)}v((i=i.apply(e,n||[])).next())})};Object.defineProperty(T,"__esModule",{value:!0});T.getData=T.fetchData=T.stringifyQuery=T.insertParams=void 0;const vn=e=>typeof e=="object"&&e!==null&&"code"in e&&"message"in e;function In(e,n,t){return e.replace(new RegExp(`\\{${n}\\}`,"g"),t)}function An(e,n){return n?Object.keys(n).reduce((t,i)=>In(t,i,String(n[i])),e):e}T.insertParams=An;function mn(e){if(!e)return"";const n=new URLSearchParams;Object.keys(e).forEach(i=>{e[i]!=null&&n.append(i,String(e[i]))});const t=n.toString();return t?`?${t}`:""}T.stringifyQuery=mn;function Y(e){return j(this,void 0,void 0,function*(){let n;try{n=yield e.json()}catch{n={}}if(!e.ok){const t=vn(n)?`CGW error - ${n.code}: ${n.message}`:`CGW error - status ${e.statusText}`;throw new Error(t)}return n})}function Sn(e,n,t,i,r){return j(this,void 0,void 0,function*(){const a=Object.assign({"Content-Type":"application/json"},i),u={method:n??"POST",headers:a};r&&(u.credentials=r),t!=null&&(u.body=typeof t=="string"?t:JSON.stringify(t));const l=yield fetch(e,u);return Y(l)})}T.fetchData=Sn;function On(e,n,t){return j(this,void 0,void 0,function*(){const i={method:"GET"};n&&(i.headers=Object.assign(Object.assign({},n),{"Content-Type":"application/json"})),t&&(i.credentials=t);const r=yield fetch(e,i);return Y(r)})}T.getData=On;Object.defineProperty(y,"__esModule",{value:!0});y.getEndpoint=y.deleteEndpoint=y.putEndpoint=y.postEndpoint=void 0;const O=T;function P(e,n,t,i){const r=(0,O.insertParams)(n,t),a=(0,O.stringifyQuery)(i);return`${e}${r}${a}`}function Nn(e,n,t){const i=P(e,n,t==null?void 0:t.path,t==null?void 0:t.query);return(0,O.fetchData)(i,"POST",t==null?void 0:t.body,t==null?void 0:t.headers,t==null?void 0:t.credentials)}y.postEndpoint=Nn;function bn(e,n,t){const i=P(e,n,t==null?void 0:t.path,t==null?void 0:t.query);return(0,O.fetchData)(i,"PUT",t==null?void 0:t.body,t==null?void 0:t.headers,t==null?void 0:t.credentials)}y.putEndpoint=bn;function pn(e,n,t){const i=P(e,n,t==null?void 0:t.path,t==null?void 0:t.query);return(0,O.fetchData)(i,"DELETE",t==null?void 0:t.body,t==null?void 0:t.headers,t==null?void 0:t.credentials)}y.deleteEndpoint=pn;function Cn(e,n,t,i){if(i)return(0,O.getData)(i,void 0,t==null?void 0:t.credentials);const r=P(e,n,t==null?void 0:t.path,t==null?void 0:t.query);return(0,O.getData)(r,t==null?void 0:t.headers,t==null?void 0:t.credentials)}y.getEndpoint=Cn;var R={};Object.defineProperty(R,"__esModule",{value:!0});R.DEFAULT_BASE_URL=void 0;R.DEFAULT_BASE_URL="https://safe-client.safe.global";var J={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ImplementationVersionState=void 0,function(n){n.UP_TO_DATE="UP_TO_DATE",n.OUTDATED="OUTDATED",n.UNKNOWN="UNKNOWN"}(e.ImplementationVersionState||(e.ImplementationVersionState={}))})(J);var Z={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.SafeAppSocialPlatforms=e.SafeAppFeatures=e.SafeAppAccessPolicyTypes=void 0,function(n){n.NoRestrictions="NO_RESTRICTIONS",n.DomainAllowlist="DOMAIN_ALLOWLIST"}(e.SafeAppAccessPolicyTypes||(e.SafeAppAccessPolicyTypes={})),function(n){n.BATCHED_TRANSACTIONS="BATCHED_TRANSACTIONS"}(e.SafeAppFeatures||(e.SafeAppFeatures={})),function(n){n.TWITTER="TWITTER",n.GITHUB="GITHUB",n.DISCORD="DISCORD"}(e.SafeAppSocialPlatforms||(e.SafeAppSocialPlatforms={}))})(Z);var x={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.LabelValue=e.StartTimeValue=e.DurationType=e.DetailedExecutionInfoType=e.TransactionListItemType=e.ConflictType=e.TransactionInfoType=e.SettingsInfoType=e.TransactionTokenType=e.TransferDirection=e.TransactionStatus=e.Operation=void 0,function(n){n[n.CALL=0]="CALL",n[n.DELEGATE=1]="DELEGATE"}(e.Operation||(e.Operation={})),function(n){n.AWAITING_CONFIRMATIONS="AWAITING_CONFIRMATIONS",n.AWAITING_EXECUTION="AWAITING_EXECUTION",n.CANCELLED="CANCELLED",n.FAILED="FAILED",n.SUCCESS="SUCCESS"}(e.TransactionStatus||(e.TransactionStatus={})),function(n){n.INCOMING="INCOMING",n.OUTGOING="OUTGOING",n.UNKNOWN="UNKNOWN"}(e.TransferDirection||(e.TransferDirection={})),function(n){n.ERC20="ERC20",n.ERC721="ERC721",n.NATIVE_COIN="NATIVE_COIN"}(e.TransactionTokenType||(e.TransactionTokenType={})),function(n){n.SET_FALLBACK_HANDLER="SET_FALLBACK_HANDLER",n.ADD_OWNER="ADD_OWNER",n.REMOVE_OWNER="REMOVE_OWNER",n.SWAP_OWNER="SWAP_OWNER",n.CHANGE_THRESHOLD="CHANGE_THRESHOLD",n.CHANGE_IMPLEMENTATION="CHANGE_IMPLEMENTATION",n.ENABLE_MODULE="ENABLE_MODULE",n.DISABLE_MODULE="DISABLE_MODULE",n.SET_GUARD="SET_GUARD",n.DELETE_GUARD="DELETE_GUARD"}(e.SettingsInfoType||(e.SettingsInfoType={})),function(n){n.TRANSFER="Transfer",n.SETTINGS_CHANGE="SettingsChange",n.CUSTOM="Custom",n.CREATION="Creation",n.SWAP_ORDER="SwapOrder",n.TWAP_ORDER="TwapOrder",n.SWAP_TRANSFER="SwapTransfer"}(e.TransactionInfoType||(e.TransactionInfoType={})),function(n){n.NONE="None",n.HAS_NEXT="HasNext",n.END="End"}(e.ConflictType||(e.ConflictType={})),function(n){n.TRANSACTION="TRANSACTION",n.LABEL="LABEL",n.CONFLICT_HEADER="CONFLICT_HEADER",n.DATE_LABEL="DATE_LABEL"}(e.TransactionListItemType||(e.TransactionListItemType={})),function(n){n.MULTISIG="MULTISIG",n.MODULE="MODULE"}(e.DetailedExecutionInfoType||(e.DetailedExecutionInfoType={})),function(n){n.AUTO="AUTO",n.LIMIT_DURATION="LIMIT_DURATION"}(e.DurationType||(e.DurationType={})),function(n){n.AT_MINING_TIME="AT_MINING_TIME",n.AT_EPOCH="AT_EPOCH"}(e.StartTimeValue||(e.StartTimeValue={})),function(n){n.Queued="Queued",n.Next="Next"}(e.LabelValue||(e.LabelValue={}))})(x);var ee={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.FEATURES=e.GAS_PRICE_TYPE=e.RPC_AUTHENTICATION=void 0,function(n){n.API_KEY_PATH="API_KEY_PATH",n.NO_AUTHENTICATION="NO_AUTHENTICATION",n.UNKNOWN="UNKNOWN"}(e.RPC_AUTHENTICATION||(e.RPC_AUTHENTICATION={})),function(n){n.ORACLE="ORACLE",n.FIXED="FIXED",n.FIXED_1559="FIXED1559",n.UNKNOWN="UNKNOWN"}(e.GAS_PRICE_TYPE||(e.GAS_PRICE_TYPE={})),function(n){n.ERC721="ERC721",n.SAFE_APPS="SAFE_APPS",n.CONTRACT_INTERACTION="CONTRACT_INTERACTION",n.DOMAIN_LOOKUP="DOMAIN_LOOKUP",n.SPENDING_LIMIT="SPENDING_LIMIT",n.EIP1559="EIP1559",n.SAFE_TX_GAS_OPTIONAL="SAFE_TX_GAS_OPTIONAL",n.TX_SIMULATION="TX_SIMULATION",n.EIP1271="EIP1271"}(e.FEATURES||(e.FEATURES={}))})(ee);var ne={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.TokenType=void 0,function(n){n.ERC20="ERC20",n.ERC721="ERC721",n.NATIVE_TOKEN="NATIVE_TOKEN"}(e.TokenType||(e.TokenType={}))})(ne);var te={};Object.defineProperty(te,"__esModule",{value:!0});var ie={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConfirmationViewTypes=void 0,function(n){n.COW_SWAP_ORDER="COW_SWAP_ORDER",n.COW_SWAP_TWAP_ORDER="COW_SWAP_TWAP_ORDER"}(e.ConfirmationViewTypes||(e.ConfirmationViewTypes={}))})(ie);var ae={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.SafeMessageStatus=e.SafeMessageListItemType=void 0,function(n){n.DATE_LABEL="DATE_LABEL",n.MESSAGE="MESSAGE"}(e.SafeMessageListItemType||(e.SafeMessageListItemType={})),function(n){n.NEEDS_CONFIRMATION="NEEDS_CONFIRMATION",n.CONFIRMED="CONFIRMED"}(e.SafeMessageStatus||(e.SafeMessageStatus={}))})(ae);var se={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DeviceType=void 0,function(n){n.ANDROID="ANDROID",n.IOS="IOS",n.WEB="WEB"}(e.DeviceType||(e.DeviceType={}))})(se);var ce={};Object.defineProperty(ce,"__esModule",{value:!0});(function(e){var n=N&&N.__createBinding||(Object.create?function(s,c,o,d){d===void 0&&(d=o);var A=Object.getOwnPropertyDescriptor(c,o);(!A||("get"in A?!c.__esModule:A.writable||A.configurable))&&(A={enumerable:!0,get:function(){return c[o]}}),Object.defineProperty(s,d,A)}:function(s,c,o,d){d===void 0&&(d=o),s[d]=c[o]}),t=N&&N.__exportStar||function(s,c){for(var o in s)o!=="default"&&!Object.prototype.hasOwnProperty.call(c,o)&&n(c,s,o)};Object.defineProperty(e,"__esModule",{value:!0}),e.deleteAccount=e.getAccount=e.createAccount=e.verifyAuth=e.getAuthNonce=e.getContract=e.getSafeOverviews=e.unsubscribeAll=e.unsubscribeSingle=e.registerRecoveryModule=e.deleteRegisteredEmail=e.getRegisteredEmail=e.verifyEmail=e.resendEmailVerificationCode=e.changeEmail=e.registerEmail=e.unregisterDevice=e.unregisterSafe=e.registerDevice=e.getDelegates=e.confirmSafeMessage=e.proposeSafeMessage=e.getSafeMessage=e.getSafeMessages=e.getDecodedData=e.getMasterCopies=e.getSafeApps=e.getChainConfig=e.getChainsConfig=e.getConfirmationView=e.proposeTransaction=e.getNonces=e.postSafeGasEstimation=e.deleteTransaction=e.getTransactionDetails=e.getTransactionQueue=e.getTransactionHistory=e.getCollectiblesPage=e.getCollectibles=e.getAllOwnedSafes=e.getOwnedSafes=e.getFiatCurrencies=e.getBalances=e.getMultisigTransactions=e.getModuleTransactions=e.getIncomingTransfers=e.getSafeInfo=e.getRelayCount=e.relayTransaction=e.setBaseUrl=void 0,e.putAccountDataSettings=e.getAccountDataSettings=e.getAccountDataTypes=void 0;const i=y,r=R;t(J,e),t(Z,e),t(x,e),t(ee,e),t(ne,e),t(te,e),t(ie,e),t(ae,e),t(se,e),t(ce,e);let a=r.DEFAULT_BASE_URL;const u=s=>{a=s};e.setBaseUrl=u;function l(s,c){return(0,i.postEndpoint)(a,"/v1/chains/{chainId}/relay",{path:{chainId:s},body:c})}e.relayTransaction=l;function f(s,c){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/relay/{address}",{path:{chainId:s,address:c}})}e.getRelayCount=f;function v(s,c){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{address}",{path:{chainId:s,address:c}})}e.getSafeInfo=v;function g(s,c,o,d){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{address}/incoming-transfers/",{path:{chainId:s,address:c},query:o},d)}e.getIncomingTransfers=g;function h(s,c,o,d){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{address}/module-transactions/",{path:{chainId:s,address:c},query:o},d)}e.getModuleTransactions=h;function p(s,c,o,d){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{address}/multisig-transactions/",{path:{chainId:s,address:c},query:o},d)}e.getMultisigTransactions=p;function C(s,c,o="usd",d={}){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{address}/balances/{currency}",{path:{chainId:s,address:c,currency:o},query:d})}e.getBalances=C;function D(){return(0,i.getEndpoint)(a,"/v1/balances/supported-fiat-codes")}e.getFiatCurrencies=D;function M(s,c){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/owners/{address}/safes",{path:{chainId:s,address:c}})}e.getOwnedSafes=M;function S(s){return(0,i.getEndpoint)(a,"/v1/owners/{address}/safes",{path:{address:s}})}e.getAllOwnedSafes=S;function L(s,c,o={}){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{address}/collectibles",{path:{chainId:s,address:c},query:o})}e.getCollectibles=L;function ue(s,c,o={},d){return(0,i.getEndpoint)(a,"/v2/chains/{chainId}/safes/{address}/collectibles",{path:{chainId:s,address:c},query:o},d)}e.getCollectiblesPage=ue;function de(s,c,o={},d){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/transactions/history",{path:{chainId:s,safe_address:c},query:o},d)}e.getTransactionHistory=de;function le(s,c,o={},d){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/transactions/queued",{path:{chainId:s,safe_address:c},query:o},d)}e.getTransactionQueue=le;function fe(s,c){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/transactions/{transactionId}",{path:{chainId:s,transactionId:c}})}e.getTransactionDetails=fe;function ge(s,c,o){return(0,i.deleteEndpoint)(a,"/v1/chains/{chainId}/transactions/{safeTxHash}",{path:{chainId:s,safeTxHash:c},body:{signature:o}})}e.deleteTransaction=ge;function he(s,c,o){return(0,i.postEndpoint)(a,"/v2/chains/{chainId}/safes/{safe_address}/multisig-transactions/estimations",{path:{chainId:s,safe_address:c},body:o})}e.postSafeGasEstimation=he;function Ee(s,c){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/nonces",{path:{chainId:s,safe_address:c}})}e.getNonces=Ee;function _e(s,c,o){return(0,i.postEndpoint)(a,"/v1/chains/{chainId}/transactions/{safe_address}/propose",{path:{chainId:s,safe_address:c},body:o})}e.proposeTransaction=_e;function ye(s,c,o,d){return(0,i.postEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/views/transaction-confirmation",{path:{chainId:s,safe_address:c},body:{data:o,to:d}})}e.getConfirmationView=ye;function Te(s){return(0,i.getEndpoint)(a,"/v1/chains",{query:s})}e.getChainsConfig=Te;function ve(s){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}",{path:{chainId:s}})}e.getChainConfig=ve;function Ie(s,c={}){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safe-apps",{path:{chainId:s},query:c})}e.getSafeApps=Ie;function Ae(s){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/about/master-copies",{path:{chainId:s}})}e.getMasterCopies=Ae;function me(s,c,o){return(0,i.postEndpoint)(a,"/v1/chains/{chainId}/data-decoder",{path:{chainId:s},body:{data:c,to:o}})}e.getDecodedData=me;function Se(s,c,o){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/messages",{path:{chainId:s,safe_address:c},query:{}},o)}e.getSafeMessages=Se;function Oe(s,c){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/messages/{message_hash}",{path:{chainId:s,message_hash:c}})}e.getSafeMessage=Oe;function Ne(s,c,o){return(0,i.postEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/messages",{path:{chainId:s,safe_address:c},body:o})}e.proposeSafeMessage=Ne;function be(s,c,o){return(0,i.postEndpoint)(a,"/v1/chains/{chainId}/messages/{message_hash}/signatures",{path:{chainId:s,message_hash:c},body:o})}e.confirmSafeMessage=be;function pe(s,c={}){return(0,i.getEndpoint)(a,"/v2/chains/{chainId}/delegates",{path:{chainId:s},query:c})}e.getDelegates=pe;function Ce(s){return(0,i.postEndpoint)(a,"/v1/register/notifications",{body:s})}e.registerDevice=Ce;function De(s,c,o){return(0,i.deleteEndpoint)(a,"/v1/chains/{chainId}/notifications/devices/{uuid}/safes/{safe_address}",{path:{chainId:s,safe_address:c,uuid:o}})}e.unregisterSafe=De;function we(s,c){return(0,i.deleteEndpoint)(a,"/v1/chains/{chainId}/notifications/devices/{uuid}",{path:{chainId:s,uuid:c}})}e.unregisterDevice=we;function Pe(s,c,o,d){return(0,i.postEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/emails",{path:{chainId:s,safe_address:c},body:o,headers:d})}e.registerEmail=Pe;function Re(s,c,o,d,A){return(0,i.putEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}",{path:{chainId:s,safe_address:c,signer:o},body:d,headers:A})}e.changeEmail=Re;function Me(s,c,o){return(0,i.postEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}/verify-resend",{path:{chainId:s,safe_address:c,signer:o},body:""})}e.resendEmailVerificationCode=Me;function Le(s,c,o,d){return(0,i.putEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}/verify",{path:{chainId:s,safe_address:c,signer:o},body:d})}e.verifyEmail=Le;function Be(s,c,o,d){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}",{path:{chainId:s,safe_address:c,signer:o},headers:d})}e.getRegisteredEmail=Be;function He(s,c,o,d){return(0,i.deleteEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}",{path:{chainId:s,safe_address:c,signer:o},headers:d})}e.deleteRegisteredEmail=He;function Ue(s,c,o){return(0,i.postEndpoint)(a,"/v1/chains/{chainId}/safes/{safe_address}/recovery",{path:{chainId:s,safe_address:c},body:o})}e.registerRecoveryModule=Ue;function je(s){return(0,i.deleteEndpoint)(a,"/v1/subscriptions",{query:s})}e.unsubscribeSingle=je;function Ge(s){return(0,i.deleteEndpoint)(a,"/v1/subscriptions/all",{query:s})}e.unsubscribeAll=Ge;function Ve(s,c){return(0,i.getEndpoint)(a,"/v1/safes",{query:Object.assign(Object.assign({},c),{safes:s.join(",")})})}e.getSafeOverviews=Ve;function We(s,c){return(0,i.getEndpoint)(a,"/v1/chains/{chainId}/contracts/{contractAddress}",{path:{chainId:s,contractAddress:c}})}e.getContract=We;function qe(){return(0,i.getEndpoint)(a,"/v1/auth/nonce",{credentials:"include"})}e.getAuthNonce=qe;function ke(s){return(0,i.postEndpoint)(a,"/v1/auth/verify",{body:s,credentials:"include"})}e.verifyAuth=ke;function Fe(s){return(0,i.postEndpoint)(a,"/v1/accounts",{body:s,credentials:"include"})}e.createAccount=Fe;function $e(s){return(0,i.getEndpoint)(a,"/v1/accounts/{address}",{path:{address:s},credentials:"include"})}e.getAccount=$e;function Ke(s){return(0,i.deleteEndpoint)(a,"/v1/accounts/{address}",{path:{address:s},credentials:"include"})}e.deleteAccount=Ke;function Xe(){return(0,i.getEndpoint)(a,"/v1/accounts/data-types")}e.getAccountDataTypes=Xe;function Qe(s){return(0,i.getEndpoint)(a,"/v1/accounts/{address}/data-settings",{path:{address:s},credentials:"include"})}e.getAccountDataSettings=Qe;function ze(s,c){return(0,i.putEndpoint)(a,"/v1/accounts/{address}/data-settings",{path:{address:s},body:c,credentials:"include"})}e.putAccountDataSettings=ze})(Tn);class Dn{constructor(n){this.communicator=n}async getBySafeTxHash(n){if(!n)throw new Error("Invalid safeTxHash");return(await this.communicator.send(E.getTxBySafeTxHash,{safeTxHash:n})).data}async signMessage(n){const t={message:n};return(await this.communicator.send(E.signMessage,t)).data}async signTypedMessage(n){if(!z(n))throw new Error("Invalid typed data");return(await this.communicator.send(E.signTypedMessage,{typedData:n})).data}async send({txs:n,params:t}){if(!n||!n.length)throw new Error("No transactions were passed");const i={txs:n,params:t};return(await this.communicator.send(E.sendTransactions,i)).data}}const _={eth_call:"eth_call",eth_gasPrice:"eth_gasPrice",eth_getLogs:"eth_getLogs",eth_getBalance:"eth_getBalance",eth_getCode:"eth_getCode",eth_getBlockByHash:"eth_getBlockByHash",eth_getBlockByNumber:"eth_getBlockByNumber",eth_getStorageAt:"eth_getStorageAt",eth_getTransactionByHash:"eth_getTransactionByHash",eth_getTransactionReceipt:"eth_getTransactionReceipt",eth_getTransactionCount:"eth_getTransactionCount",eth_estimateGas:"eth_estimateGas",safe_setSettings:"safe_setSettings"},I={defaultBlockParam:(e="latest")=>e,returnFullTxObjectParam:(e=!1)=>e,blockNumberToHex:e=>Number.isInteger(e)?`0x${e.toString(16)}`:e};class wn{constructor(n){this.communicator=n,this.call=this.buildRequest({call:_.eth_call,formatters:[null,I.defaultBlockParam]}),this.getBalance=this.buildRequest({call:_.eth_getBalance,formatters:[null,I.defaultBlockParam]}),this.getCode=this.buildRequest({call:_.eth_getCode,formatters:[null,I.defaultBlockParam]}),this.getStorageAt=this.buildRequest({call:_.eth_getStorageAt,formatters:[null,I.blockNumberToHex,I.defaultBlockParam]}),this.getPastLogs=this.buildRequest({call:_.eth_getLogs}),this.getBlockByHash=this.buildRequest({call:_.eth_getBlockByHash,formatters:[null,I.returnFullTxObjectParam]}),this.getBlockByNumber=this.buildRequest({call:_.eth_getBlockByNumber,formatters:[I.blockNumberToHex,I.returnFullTxObjectParam]}),this.getTransactionByHash=this.buildRequest({call:_.eth_getTransactionByHash}),this.getTransactionReceipt=this.buildRequest({call:_.eth_getTransactionReceipt}),this.getTransactionCount=this.buildRequest({call:_.eth_getTransactionCount,formatters:[null,I.defaultBlockParam]}),this.getGasPrice=this.buildRequest({call:_.eth_gasPrice}),this.getEstimateGas=t=>this.buildRequest({call:_.eth_estimateGas})([t]),this.setSafeSettings=this.buildRequest({call:_.safe_setSettings})}buildRequest(n){const{call:t,formatters:i}=n;return async r=>{i&&Array.isArray(r)&&i.forEach((l,f)=>{l&&(r[f]=l(r[f]))});const a={call:t,params:r||[]};return(await this.communicator.send(E.rpcCall,a)).data}}}const Pn="0x1626ba7e",Rn="0x20c13b0b",U=4001;class b extends Error{constructor(n,t,i){super(n),this.code=t,this.data=i,Object.setPrototypeOf(this,b.prototype)}}class re{constructor(n){this.communicator=n}async getPermissions(){return(await this.communicator.send(E.wallet_getPermissions,void 0)).data}async requestPermissions(n){if(!this.isPermissionRequestValid(n))throw new b("Permissions request is invalid",U);try{return(await this.communicator.send(E.wallet_requestPermissions,n)).data}catch{throw new b("Permissions rejected",U)}}isPermissionRequestValid(n){return n.every(t=>typeof t=="object"?Object.keys(t).every(i=>!!Object.values(H).includes(i)):!1)}}const W=(e,n)=>n.some(t=>t.parentCapability===e),Mn=()=>(e,n,t)=>{const i=t.value;return t.value=async function(){const r=new re(this.communicator);let a=await r.getPermissions();if(W(n,a)||(a=await r.requestPermissions([{[n]:{}}])),!W(n,a))throw new b("Permissions rejected",U);return i.apply(this)},t};var Ln=function(e,n,t,i){var r=arguments.length,a=r<3?n:i===null?i=Object.getOwnPropertyDescriptor(n,t):i,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(e,n,t,i);else for(var l=e.length-1;l>=0;l--)(u=e[l])&&(a=(r<3?u(a):r>3?u(n,t,a):u(n,t))||a);return r>3&&a&&Object.defineProperty(n,t,a),a};class oe{constructor(n){this.communicator=n}async getChainInfo(){return(await this.communicator.send(E.getChainInfo,void 0)).data}async getInfo(){return(await this.communicator.send(E.getSafeInfo,void 0)).data}async experimental_getBalances({currency:n="usd"}={}){return(await this.communicator.send(E.getSafeBalances,{currency:n})).data}async check1271Signature(n,t="0x"){const i=await this.getInfo(),r=V({abi:[{constant:!1,inputs:[{name:"_dataHash",type:"bytes32"},{name:"_signature",type:"bytes"}],name:"isValidSignature",outputs:[{name:"",type:"bytes4"}],payable:!1,stateMutability:"nonpayable",type:"function"}],functionName:"isValidSignature",args:[n,t]}),a={call:_.eth_call,params:[{to:i.safeAddress,data:r},"latest"]};try{return(await this.communicator.send(E.rpcCall,a)).data.slice(0,10).toLowerCase()===Pn}catch{return!1}}async check1271SignatureBytes(n,t="0x"){const i=await this.getInfo(),r=V({abi:[{constant:!1,inputs:[{name:"_data",type:"bytes"},{name:"_signature",type:"bytes"}],name:"isValidSignature",outputs:[{name:"",type:"bytes4"}],payable:!1,stateMutability:"nonpayable",type:"function"}],functionName:"isValidSignature",args:[n,t]}),a={call:_.eth_call,params:[{to:i.safeAddress,data:r},"latest"]};try{return(await this.communicator.send(E.rpcCall,a)).data.slice(0,10).toLowerCase()===Rn}catch{return!1}}calculateMessageHash(n){return fn(n)}calculateTypedMessageHash(n){const t=typeof n.domain.chainId=="object"?n.domain.chainId.toNumber():Number(n.domain.chainId);let i=n.primaryType;if(!i){const r=Object.values(n.types),a=Object.keys(n.types).filter(u=>r.every(l=>l.every(({type:f})=>f.replace("[","").replace("]","")!==u)));if(a.length===0||a.length>1)throw new Error("Please specify primaryType");i=a[0]}return an({message:n.message,domain:{...n.domain,chainId:t,verifyingContract:n.domain.verifyingContract,salt:n.domain.salt},types:n.types,primaryType:i})}async getOffChainSignature(n){return(await this.communicator.send(E.getOffChainSignature,n)).data}async isMessageSigned(n,t="0x"){let i;if(typeof n=="string"&&(i=async()=>{const r=this.calculateMessageHash(n);return await this.isMessageHashSigned(r,t)}),z(n)&&(i=async()=>{const r=this.calculateTypedMessageHash(n);return await this.isMessageHashSigned(r,t)}),i)return await i();throw new Error("Invalid message type")}async isMessageHashSigned(n,t="0x"){const i=[this.check1271Signature.bind(this),this.check1271SignatureBytes.bind(this)];for(const r of i)if(await r(n,t))return!0;return!1}async getEnvironmentInfo(){return(await this.communicator.send(E.getEnvironmentInfo,void 0)).data}async requestAddressBook(){return(await this.communicator.send(E.requestAddressBook,void 0)).data}}Ln([Mn()],oe.prototype,"requestAddressBook",null);class Hn{constructor(n={}){const{allowedDomains:t=null,debug:i=!1}=n;this.communicator=new yn(t,i),this.eth=new wn(this.communicator),this.txs=new Dn(this.communicator),this.safe=new oe(this.communicator),this.wallet=new re(this.communicator)}}export{w as MessageFormatter,E as Methods,_ as RPC_CALLS,H as RestrictedMethods,Hn as default,gn as getSDKVersion,z as isObjectEIP712TypedData}; diff --git a/buddybook/assets/index-wat9_83N.js b/buddybook/assets/index-wat9_83N.js new file mode 100644 index 0000000..32aa5dd --- /dev/null +++ b/buddybook/assets/index-wat9_83N.js @@ -0,0 +1,54 @@ +import{T as $t,M as oe,R as N,E as k,C as $,a as X,b as Br,O as Z,c as ht}from"./index-DY1ObU95.js";import{C as Wr}from"./index-B-6Lwopd.js";class Ur{setAnimation(t){this.animation=t,t==null||t.finished.then(()=>this.clearAnimation()).catch(()=>{})}clearAnimation(){this.animation=this.generator=void 0}}function jr(e,t){e.indexOf(t)===-1&&e.push(t)}const Jo=(e,t,o)=>Math.min(Math.max(o,e),t),V={duration:.3,delay:0,endDelay:0,repeat:0,easing:"ease"},ne=e=>typeof e=="number",bt=e=>Array.isArray(e)&&!ne(e[0]),kr=(e,t,o)=>{const n=t-e;return((o-e)%n+n)%n+e};function Hr(e,t){return bt(e)?e[kr(0,e.length,t)]:e}const Qo=(e,t,o)=>-o*e+o*t+e,Xo=()=>{},et=e=>e,mo=(e,t,o)=>t-e===0?1:(o-e)/(t-e);function tr(e,t){const o=e[e.length-1];for(let n=1;n<=t;n++){const r=mo(0,t,n);e.push(Qo(o,1,r))}}function zr(e){const t=[0];return tr(t,e-1),t}function Fr(e,t=zr(e.length),o=et){const n=e.length,r=n-t.length;return r>0&&tr(t,r),i=>{let s=0;for(;sArray.isArray(e)&&ne(e[0]),ke=e=>typeof e=="object"&&!!e.createAnimation,xt=e=>typeof e=="function",Vr=e=>typeof e=="string",Nt={ms:e=>e*1e3,s:e=>e/1e3},or=(e,t,o)=>(((1-3*o+3*t)*e+(3*o-6*t))*e+3*t)*e,Zr=1e-7,Kr=12;function qr(e,t,o,n,r){let i,s,l=0;do s=t+(o-t)/2,i=or(s,n,r)-e,i>0?o=s:t=s;while(Math.abs(i)>Zr&&++lqr(i,0,1,e,o);return i=>i===0||i===1?i:or(r(i),t,n)}const Yr=(e,t="end")=>o=>{o=t==="end"?Math.min(o,.999):Math.max(o,.001);const n=o*e,r=t==="end"?Math.floor(n):Math.ceil(n);return Jo(0,1,r/e)},Gr={ease:Lt(.25,.1,.25,1),"ease-in":Lt(.42,0,1,1),"ease-in-out":Lt(.42,0,.58,1),"ease-out":Lt(0,0,.58,1)},Jr=/\((.*?)\)/;function Ao(e){if(xt(e))return e;if(er(e))return Lt(...e);const t=Gr[e];if(t)return t;if(e.startsWith("steps")){const o=Jr.exec(e);if(o){const n=o[1].split(",");return Yr(parseFloat(n[0]),n[1].trim())}}return et}class rr{constructor(t,o=[0,1],{easing:n,duration:r=V.duration,delay:i=V.delay,endDelay:s=V.endDelay,repeat:l=V.repeat,offset:a,direction:c="normal",autoplay:d=!0}={}){if(this.startTime=null,this.rate=1,this.t=0,this.cancelTimestamp=null,this.easing=et,this.duration=0,this.totalDuration=0,this.repeat=0,this.playState="idle",this.finished=new Promise((h,p)=>{this.resolve=h,this.reject=p}),n=n||V.easing,ke(n)){const h=n.createAnimation(o);n=h.easing,o=h.keyframes||o,r=h.duration||r}this.repeat=l,this.easing=bt(n)?et:Ao(n),this.updateDuration(r);const y=Fr(o,a,bt(n)?n.map(Ao):et);this.tick=h=>{var p;i=i;let g=0;this.pauseTime!==void 0?g=this.pauseTime:g=(h-this.startTime)*this.rate,this.t=g,g/=1e3,g=Math.max(g-i,0),this.playState==="finished"&&this.pauseTime===void 0&&(g=this.totalDuration);const f=g/this.duration;let O=Math.floor(f),m=f%1;!m&&f>=1&&(m=1),m===1&&O--;const b=O%2;(c==="reverse"||c==="alternate"&&b||c==="alternate-reverse"&&!b)&&(m=1-m);const w=g>=this.totalDuration?1:Math.min(m,1),v=y(this.easing(w));t(v),this.pauseTime===void 0&&(this.playState==="finished"||g>=this.totalDuration+s)?(this.playState="finished",(p=this.resolve)===null||p===void 0||p.call(this,v)):this.playState!=="idle"&&(this.frameRequestId=requestAnimationFrame(this.tick))},d&&this.play()}play(){const t=performance.now();this.playState="running",this.pauseTime!==void 0?this.startTime=t-this.pauseTime:this.startTime||(this.startTime=t),this.cancelTimestamp=this.startTime,this.pauseTime=void 0,this.frameRequestId=requestAnimationFrame(this.tick)}pause(){this.playState="paused",this.pauseTime=this.t}finish(){this.playState="finished",this.tick(0)}stop(){var t;this.playState="idle",this.frameRequestId!==void 0&&cancelAnimationFrame(this.frameRequestId),(t=this.reject)===null||t===void 0||t.call(this,!1)}cancel(){this.stop(),this.tick(this.cancelTimestamp)}reverse(){this.rate*=-1}commitStyles(){}updateDuration(t){this.duration=t,this.totalDuration=t*(this.repeat+1)}get currentTime(){return this.t}set currentTime(t){this.pauseTime!==void 0||this.rate===0?this.pauseTime=t:this.startTime=performance.now()-t/this.rate}get playbackRate(){return this.rate}set playbackRate(t){this.rate=t}}/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const re=window,fo=re.ShadowRoot&&(re.ShadyCSS===void 0||re.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,po=Symbol(),Oo=new WeakMap;let nr=class{constructor(t,o,n){if(this._$cssResult$=!0,n!==po)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=o}get styleSheet(){let t=this.o;const o=this.t;if(fo&&t===void 0){const n=o!==void 0&&o.length===1;n&&(t=Oo.get(o)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&Oo.set(o,t))}return t}toString(){return this.cssText}};const Qr=e=>new nr(typeof e=="string"?e:e+"",void 0,po),I=(e,...t)=>{const o=e.length===1?e[0]:t.reduce((n,r,i)=>n+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+e[i+1],e[0]);return new nr(o,e,po)},Xr=(e,t)=>{fo?e.adoptedStyleSheets=t.map(o=>o instanceof CSSStyleSheet?o:o.styleSheet):t.forEach(o=>{const n=document.createElement("style"),r=re.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=o.cssText,e.appendChild(n)})},Po=fo?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let o="";for(const n of t.cssRules)o+=n.cssText;return Qr(o)})(e):e;/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */var _e;const ie=window,Io=ie.trustedTypes,tn=Io?Io.emptyScript:"",To=ie.reactiveElementPolyfillSupport,He={toAttribute(e,t){switch(t){case Boolean:e=e?tn:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let o=e;switch(t){case Boolean:o=e!==null;break;case Number:o=e===null?null:Number(e);break;case Object:case Array:try{o=JSON.parse(e)}catch{o=null}}return o}},ir=(e,t)=>t!==e&&(t==t||e==e),Ce={attribute:!0,type:String,converter:He,reflect:!1,hasChanged:ir},ze="finalized";let wt=class extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this._$Eu()}static addInitializer(t){var o;this.finalize(),((o=this.h)!==null&&o!==void 0?o:this.h=[]).push(t)}static get observedAttributes(){this.finalize();const t=[];return this.elementProperties.forEach((o,n)=>{const r=this._$Ep(n,o);r!==void 0&&(this._$Ev.set(r,n),t.push(r))}),t}static createProperty(t,o=Ce){if(o.state&&(o.attribute=!1),this.finalize(),this.elementProperties.set(t,o),!o.noAccessor&&!this.prototype.hasOwnProperty(t)){const n=typeof t=="symbol"?Symbol():"__"+t,r=this.getPropertyDescriptor(t,n,o);r!==void 0&&Object.defineProperty(this.prototype,t,r)}}static getPropertyDescriptor(t,o,n){return{get(){return this[o]},set(r){const i=this[t];this[o]=r,this.requestUpdate(t,i,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)||Ce}static finalize(){if(this.hasOwnProperty(ze))return!1;this[ze]=!0;const t=Object.getPrototypeOf(this);if(t.finalize(),t.h!==void 0&&(this.h=[...t.h]),this.elementProperties=new Map(t.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){const o=this.properties,n=[...Object.getOwnPropertyNames(o),...Object.getOwnPropertySymbols(o)];for(const r of n)this.createProperty(r,o[r])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(t){const o=[];if(Array.isArray(t)){const n=new Set(t.flat(1/0).reverse());for(const r of n)o.unshift(Po(r))}else t!==void 0&&o.push(Po(t));return o}static _$Ep(t,o){const n=o.attribute;return n===!1?void 0:typeof n=="string"?n:typeof t=="string"?t.toLowerCase():void 0}_$Eu(){var t;this._$E_=new Promise(o=>this.enableUpdating=o),this._$AL=new Map,this._$Eg(),this.requestUpdate(),(t=this.constructor.h)===null||t===void 0||t.forEach(o=>o(this))}addController(t){var o,n;((o=this._$ES)!==null&&o!==void 0?o:this._$ES=[]).push(t),this.renderRoot!==void 0&&this.isConnected&&((n=t.hostConnected)===null||n===void 0||n.call(t))}removeController(t){var o;(o=this._$ES)===null||o===void 0||o.splice(this._$ES.indexOf(t)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach((t,o)=>{this.hasOwnProperty(o)&&(this._$Ei.set(o,this[o]),delete this[o])})}createRenderRoot(){var t;const o=(t=this.shadowRoot)!==null&&t!==void 0?t:this.attachShadow(this.constructor.shadowRootOptions);return Xr(o,this.constructor.elementStyles),o}connectedCallback(){var t;this.renderRoot===void 0&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$ES)===null||t===void 0||t.forEach(o=>{var n;return(n=o.hostConnected)===null||n===void 0?void 0:n.call(o)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$ES)===null||t===void 0||t.forEach(o=>{var n;return(n=o.hostDisconnected)===null||n===void 0?void 0:n.call(o)})}attributeChangedCallback(t,o,n){this._$AK(t,n)}_$EO(t,o,n=Ce){var r;const i=this.constructor._$Ep(t,n);if(i!==void 0&&n.reflect===!0){const s=(((r=n.converter)===null||r===void 0?void 0:r.toAttribute)!==void 0?n.converter:He).toAttribute(o,n.type);this._$El=t,s==null?this.removeAttribute(i):this.setAttribute(i,s),this._$El=null}}_$AK(t,o){var n;const r=this.constructor,i=r._$Ev.get(t);if(i!==void 0&&this._$El!==i){const s=r.getPropertyOptions(i),l=typeof s.converter=="function"?{fromAttribute:s.converter}:((n=s.converter)===null||n===void 0?void 0:n.fromAttribute)!==void 0?s.converter:He;this._$El=i,this[i]=l.fromAttribute(o,s.type),this._$El=null}}requestUpdate(t,o,n){let r=!0;t!==void 0&&(((n=n||this.constructor.getPropertyOptions(t)).hasChanged||ir)(this[t],o)?(this._$AL.has(t)||this._$AL.set(t,o),n.reflect===!0&&this._$El!==t&&(this._$EC===void 0&&(this._$EC=new Map),this._$EC.set(t,n))):r=!1),!this.isUpdatePending&&r&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(o){Promise.reject(o)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var t;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach((r,i)=>this[i]=r),this._$Ei=void 0);let o=!1;const n=this._$AL;try{o=this.shouldUpdate(n),o?(this.willUpdate(n),(t=this._$ES)===null||t===void 0||t.forEach(r=>{var i;return(i=r.hostUpdate)===null||i===void 0?void 0:i.call(r)}),this.update(n)):this._$Ek()}catch(r){throw o=!1,this._$Ek(),r}o&&this._$AE(n)}willUpdate(t){}_$AE(t){var o;(o=this._$ES)===null||o===void 0||o.forEach(n=>{var r;return(r=n.hostUpdated)===null||r===void 0?void 0:r.call(n)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(t){return!0}update(t){this._$EC!==void 0&&(this._$EC.forEach((o,n)=>this._$EO(n,this[n],o)),this._$EC=void 0),this._$Ek()}updated(t){}firstUpdated(t){}};wt[ze]=!0,wt.elementProperties=new Map,wt.elementStyles=[],wt.shadowRootOptions={mode:"open"},To==null||To({ReactiveElement:wt}),((_e=ie.reactiveElementVersions)!==null&&_e!==void 0?_e:ie.reactiveElementVersions=[]).push("1.6.3");/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */var Ee;const se=window,_t=se.trustedTypes,Mo=_t?_t.createPolicy("lit-html",{createHTML:e=>e}):void 0,Fe="$lit$",Q=`lit$${(Math.random()+"").slice(9)}$`,sr="?"+Q,en=`<${sr}>`,ut=document,Wt=()=>ut.createComment(""),Ut=e=>e===null||typeof e!="object"&&typeof e!="function",lr=Array.isArray,on=e=>lr(e)||typeof(e==null?void 0:e[Symbol.iterator])=="function",Ae=`[ +\f\r]`,Dt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,So=/-->/g,Ro=/>/g,at=RegExp(`>|${Ae}(?:([^\\s"'>=/]+)(${Ae}*=${Ae}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Do=/'/g,Lo=/"/g,ar=/^(?:script|style|textarea|title)$/i,cr=e=>(t,...o)=>({_$litType$:e,strings:t,values:o}),u=cr(1),L=cr(2),mt=Symbol.for("lit-noChange"),B=Symbol.for("lit-nothing"),No=new WeakMap,ct=ut.createTreeWalker(ut,129,null,!1);function dr(e,t){if(!Array.isArray(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Mo!==void 0?Mo.createHTML(t):t}const rn=(e,t)=>{const o=e.length-1,n=[];let r,i=t===2?"":"",s=Dt;for(let l=0;l"?(s=r??Dt,y=-1):d[1]===void 0?y=-2:(y=s.lastIndex-d[2].length,c=d[1],s=d[3]===void 0?at:d[3]==='"'?Lo:Do):s===Lo||s===Do?s=at:s===So||s===Ro?s=Dt:(s=at,r=void 0);const p=s===at&&e[l+1].startsWith("/>")?" ":"";i+=s===Dt?a+en:y>=0?(n.push(c),a.slice(0,y)+Fe+a.slice(y)+Q+p):a+Q+(y===-2?(n.push(void 0),l):p)}return[dr(e,i+(e[o]||"")+(t===2?"":"")),n]};class jt{constructor({strings:t,_$litType$:o},n){let r;this.parts=[];let i=0,s=0;const l=t.length-1,a=this.parts,[c,d]=rn(t,o);if(this.el=jt.createElement(c,n),ct.currentNode=this.el.content,o===2){const y=this.el.content,h=y.firstChild;h.remove(),y.append(...h.childNodes)}for(;(r=ct.nextNode())!==null&&a.length0){r.textContent=_t?_t.emptyScript:"";for(let p=0;p2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=B}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,o=this,n,r){const i=this.strings;let s=!1;if(i===void 0)t=Ct(this,t,o,0),s=!Ut(t)||t!==this._$AH&&t!==mt,s&&(this._$AH=t);else{const l=t;let a,c;for(t=i[0],a=0;a{var n,r;const i=(n=o==null?void 0:o.renderBefore)!==null&&n!==void 0?n:t;let s=i._$litPart$;if(s===void 0){const l=(r=o==null?void 0:o.renderBefore)!==null&&r!==void 0?r:null;i._$litPart$=s=new Kt(t.insertBefore(Wt(),l),l,void 0,o??{})}return s._$AI(e),s};/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */var Oe,Pe;class E extends wt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t,o;const n=super.createRenderRoot();return(t=(o=this.renderOptions).renderBefore)!==null&&t!==void 0||(o.renderBefore=n.firstChild),n}update(t){const o=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=hn(o,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),(t=this._$Do)===null||t===void 0||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._$Do)===null||t===void 0||t.setConnected(!1)}render(){return mt}}E.finalized=!0,E._$litElement$=!0,(Oe=globalThis.litElementHydrateSupport)===null||Oe===void 0||Oe.call(globalThis,{LitElement:E});const Wo=globalThis.litElementPolyfillSupport;Wo==null||Wo({LitElement:E});((Pe=globalThis.litElementVersions)!==null&&Pe!==void 0?Pe:globalThis.litElementVersions=[]).push("3.3.3");/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const P=e=>t=>typeof t=="function"?((o,n)=>(customElements.define(o,n),n))(e,t):((o,n)=>{const{kind:r,elements:i}=n;return{kind:r,elements:i,finisher(s){customElements.define(o,s)}}})(e,t);/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const un=(e,t)=>t.kind==="method"&&t.descriptor&&!("value"in t.descriptor)?{...t,finisher(o){o.createProperty(t.key,e)}}:{kind:"field",key:Symbol(),placement:"own",descriptor:{},originalKey:t.key,initializer(){typeof t.initializer=="function"&&(this[t.key]=t.initializer.call(this))},finisher(o){o.createProperty(t.key,e)}},mn=(e,t,o)=>{t.constructor.createProperty(o,e)};function _(e){return(t,o)=>o!==void 0?mn(e,t,o):un(e,t)}/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */function H(e){return _({...e,state:!0})}/** + * @license + * Copyright 2021 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */var Ie;((Ie=window.HTMLSlotElement)===null||Ie===void 0?void 0:Ie.prototype.assignedElements)!=null;/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const fn={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},pn=e=>(...t)=>({_$litDirective$:e,values:t});class gn{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,o,n){this._$Ct=t,this._$AM=o,this._$Ci=n}_$AS(t,o){return this.update(t,o)}update(t,o){return this.render(...o)}}/** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const J=pn(class extends gn{constructor(e){var t;if(super(e),e.type!==fn.ATTRIBUTE||e.name!=="class"||((t=e.strings)===null||t===void 0?void 0:t.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(e){return" "+Object.keys(e).filter(t=>e[t]).join(" ")+" "}update(e,[t]){var o,n;if(this.it===void 0){this.it=new Set,e.strings!==void 0&&(this.nt=new Set(e.strings.join(" ").split(/\s/).filter(i=>i!=="")));for(const i in t)t[i]&&!(!((o=this.nt)===null||o===void 0)&&o.has(i))&&this.it.add(i);return this.render(t)}const r=e.element.classList;this.it.forEach(i=>{i in t||(r.remove(i),this.it.delete(i))});for(const i in t){const s=!!t[i];s===this.it.has(i)||!((n=this.nt)===null||n===void 0)&&n.has(i)||(s?(r.add(i),this.it.add(i)):(r.remove(i),this.it.delete(i)))}return mt}}),Te=new WeakMap;function hr(e){return Te.has(e)||Te.set(e,{transforms:[],values:new Map}),Te.get(e)}function wn(e,t){return e.has(t)||e.set(t,new Ur),e.get(t)}const vn=["","X","Y","Z"],bn=["translate","scale","rotate","skew"],le={x:"translateX",y:"translateY",z:"translateZ"},Uo={syntax:"",initialValue:"0deg",toDefaultUnit:e=>e+"deg"},yn={translate:{syntax:"",initialValue:"0px",toDefaultUnit:e=>e+"px"},rotate:Uo,scale:{syntax:"",initialValue:1,toDefaultUnit:et},skew:Uo},kt=new Map,go=e=>`--motion-${e}`,ae=["x","y","z"];bn.forEach(e=>{vn.forEach(t=>{ae.push(e+t),kt.set(go(e+t),yn[e])})});const $n=(e,t)=>ae.indexOf(e)-ae.indexOf(t),xn=new Set(ae),ur=e=>xn.has(e),_n=(e,t)=>{le[t]&&(t=le[t]);const{transforms:o}=hr(e);jr(o,t),e.style.transform=Cn(o)},Cn=e=>e.sort($n).reduce(En,"").trim(),En=(e,t)=>`${e} ${t}(var(${go(t)}))`,Ve=e=>e.startsWith("--"),jo=new Set;function An(e){if(!jo.has(e)){jo.add(e);try{const{syntax:t,initialValue:o}=kt.has(e)?kt.get(e):{};CSS.registerProperty({name:e,inherits:!1,syntax:t,initialValue:o})}catch{}}}const Me=(e,t)=>document.createElement("div").animate(e,t),ko={cssRegisterProperty:()=>typeof CSS<"u"&&Object.hasOwnProperty.call(CSS,"registerProperty"),waapi:()=>Object.hasOwnProperty.call(Element.prototype,"animate"),partialKeyframes:()=>{try{Me({opacity:[1]})}catch{return!1}return!0},finished:()=>!!Me({opacity:[0,1]},{duration:.001}).finished,linearEasing:()=>{try{Me({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0}},Se={},vt={};for(const e in ko)vt[e]=()=>(Se[e]===void 0&&(Se[e]=ko[e]()),Se[e]);const On=.015,Pn=(e,t)=>{let o="";const n=Math.round(t/On);for(let r=0;rxt(e)?vt.linearEasing()?`linear(${Pn(e,t)})`:V.easing:er(e)?In(e):e,In=([e,t,o,n])=>`cubic-bezier(${e}, ${t}, ${o}, ${n})`;function Tn(e,t){for(let o=0;oArray.isArray(e)?e:[e];function Ze(e){return le[e]&&(e=le[e]),ur(e)?go(e):e}const Xt={get:(e,t)=>{t=Ze(t);let o=Ve(t)?e.style.getPropertyValue(t):getComputedStyle(e)[t];if(!o&&o!==0){const n=kt.get(t);n&&(o=n.initialValue)}return o},set:(e,t,o)=>{t=Ze(t),Ve(t)?e.style.setProperty(t,o):e.style[t]=o}};function mr(e,t=!0){if(!(!e||e.playState==="finished"))try{e.stop?e.stop():(t&&e.commitStyles(),e.cancel())}catch{}}function Sn(e,t){var o;let n=(t==null?void 0:t.toDefaultUnit)||et;const r=e[e.length-1];if(Vr(r)){const i=((o=r.match(/(-?[\d.]+)([a-z%]*)/))===null||o===void 0?void 0:o[2])||"";i&&(n=s=>s+i)}return n}function Rn(){return window.__MOTION_DEV_TOOLS_RECORD}function Dn(e,t,o,n={},r){const i=Rn(),s=n.record!==!1&&i;let l,{duration:a=V.duration,delay:c=V.delay,endDelay:d=V.endDelay,repeat:y=V.repeat,easing:h=V.easing,persist:p=!1,direction:g,offset:f,allowWebkitAcceleration:O=!1,autoplay:m=!0}=n;const b=hr(e),w=ur(t);let v=vt.waapi();w&&_n(e,t);const C=Ze(t),S=wn(b.values,C),R=kt.get(C);return mr(S.animation,!(ke(h)&&S.generator)&&n.record!==!1),()=>{const U=()=>{var D,Y;return(Y=(D=Xt.get(e,C))!==null&&D!==void 0?D:R==null?void 0:R.initialValue)!==null&&Y!==void 0?Y:0};let M=Tn(Mn(o),U);const z=Sn(M,R);if(ke(h)){const D=h.createAnimation(M,t!=="opacity",U,C,S);h=D.easing,M=D.keyframes||M,a=D.duration||a}if(Ve(C)&&(vt.cssRegisterProperty()?An(C):v=!1),w&&!vt.linearEasing()&&(xt(h)||bt(h)&&h.some(xt))&&(v=!1),v){R&&(M=M.map(W=>ne(W)?R.toDefaultUnit(W):W)),M.length===1&&(!vt.partialKeyframes()||s)&&M.unshift(U());const D={delay:Nt.ms(c),duration:Nt.ms(a),endDelay:Nt.ms(d),easing:bt(h)?void 0:Ho(h,a),direction:g,iterations:y+1,fill:"both"};l=e.animate({[C]:M,offset:f,easing:bt(h)?h.map(W=>Ho(W,a)):void 0},D),l.finished||(l.finished=new Promise((W,Nr)=>{l.onfinish=W,l.oncancel=Nr}));const Y=M[M.length-1];l.finished.then(()=>{p||(Xt.set(e,C,Y),l.cancel())}).catch(Xo),O||(l.playbackRate=1.000001)}else if(r&&w)M=M.map(D=>typeof D=="string"?parseFloat(D):D),M.length===1&&M.unshift(parseFloat(U())),l=new r(D=>{Xt.set(e,C,z?z(D):D)},M,Object.assign(Object.assign({},n),{duration:a,easing:h}));else{const D=M[M.length-1];Xt.set(e,C,R&&ne(D)?R.toDefaultUnit(D):D)}return s&&i(e,t,M,{duration:a,delay:c,easing:h,repeat:y,offset:f},"motion-one"),S.setAnimation(l),l&&!m&&l.pause(),l}}const Ln=(e,t)=>e[t]?Object.assign(Object.assign({},e),e[t]):Object.assign({},e);function Nn(e,t){return typeof e=="string"?e=document.querySelectorAll(e):e instanceof Element&&(e=[e]),Array.from(e||[])}const Bn=e=>e(),fr=(e,t,o=V.duration)=>new Proxy({animations:e.map(Bn).filter(Boolean),duration:o,options:t},Un),Wn=e=>e.animations[0],Un={get:(e,t)=>{const o=Wn(e);switch(t){case"duration":return e.duration;case"currentTime":return Nt.s((o==null?void 0:o[t])||0);case"playbackRate":case"playState":return o==null?void 0:o[t];case"finished":return e.finished||(e.finished=Promise.all(e.animations.map(jn)).catch(Xo)),e.finished;case"stop":return()=>{e.animations.forEach(n=>mr(n))};case"forEachNative":return n=>{e.animations.forEach(r=>n(r,e))};default:return typeof(o==null?void 0:o[t])>"u"?void 0:()=>e.animations.forEach(n=>n[t]())}},set:(e,t,o)=>{switch(t){case"currentTime":o=Nt.ms(o);case"playbackRate":for(let n=0;ne.finished;function kn(e,t,o){return xt(e)?e(t,o):e}function Hn(e){return function(o,n,r={}){o=Nn(o);const i=o.length,s=[];for(let l=0;l{const o=new rr(e,[0,1],t);return o.finished.catch(()=>{}),o}],t,t.duration)}function dt(e,t,o){return(xt(e)?Fn:zn)(e,t,o)}/** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const j=e=>e??B;var qt={},Vn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},pr={},F={};let wo;const Zn=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];F.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17};F.getSymbolTotalCodewords=function(t){return Zn[t]};F.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t};F.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');wo=t};F.isKanjiModeEnabled=function(){return typeof wo<"u"};F.toSJIS=function(t){return wo(t)};var we={};(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+o)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,r){if(e.isValid(n))return n;try{return t(n)}catch{return r}}})(we);function gr(){this.buffer=[],this.length=0}gr.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let o=0;o>>t-o-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var Kn=gr;function Yt(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}Yt.prototype.set=function(e,t,o,n){const r=e*this.size+t;this.data[r]=o,n&&(this.reservedBit[r]=!0)};Yt.prototype.get=function(e,t){return this.data[e*this.size+t]};Yt.prototype.xor=function(e,t,o){this.data[e*this.size+t]^=o};Yt.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};var qn=Yt,wr={};(function(e){const t=F.getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const r=Math.floor(n/7)+2,i=t(n),s=i===145?26:Math.ceil((i-13)/(2*r-2))*2,l=[i-7];for(let a=1;a=0&&r<=7},e.from=function(r){return e.isValid(r)?parseInt(r,10):void 0},e.getPenaltyN1=function(r){const i=r.size;let s=0,l=0,a=0,c=null,d=null;for(let y=0;y=5&&(s+=t.N1+(l-5)),c=p,l=1),p=r.get(h,y),p===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=p,a=1)}l>=5&&(s+=t.N1+(l-5)),a>=5&&(s+=t.N1+(a-5))}return s},e.getPenaltyN2=function(r){const i=r.size;let s=0;for(let l=0;l=10&&(l===1488||l===93)&&s++,a=a<<1&2047|r.get(d,c),d>=10&&(a===1488||a===93)&&s++}return s*t.N3},e.getPenaltyN4=function(r){let i=0;const s=r.data.length;for(let a=0;a=0;){const s=i[0];for(let a=0;a0){const i=new Uint8Array(this.degree);return i.set(n,r),i}return n};var Gn=vo,xr={},st={},bo={};bo.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var q={};const _r="[0-9]+",Jn="[A-Z $%*+\\-./:]+";let Ht="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Ht=Ht.replace(/u/g,"\\u");const Qn="(?:(?![A-Z0-9 $%*+\\-./:]|"+Ht+`)(?:.|[\r +]))+`;q.KANJI=new RegExp(Ht,"g");q.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");q.BYTE=new RegExp(Qn,"g");q.NUMERIC=new RegExp(_r,"g");q.ALPHANUMERIC=new RegExp(Jn,"g");const Xn=new RegExp("^"+Ht+"$"),ti=new RegExp("^"+_r+"$"),ei=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");q.testKanji=function(t){return Xn.test(t)};q.testNumeric=function(t){return ti.test(t)};q.testAlphanumeric=function(t){return ei.test(t)};(function(e){const t=bo,o=q;e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(i,s){if(!i.ccBits)throw new Error("Invalid mode: "+i);if(!t.isValid(s))throw new Error("Invalid version: "+s);return s>=1&&s<10?i.ccBits[0]:s<27?i.ccBits[1]:i.ccBits[2]},e.getBestModeForData=function(i){return o.testNumeric(i)?e.NUMERIC:o.testAlphanumeric(i)?e.ALPHANUMERIC:o.testKanji(i)?e.KANJI:e.BYTE},e.toString=function(i){if(i&&i.id)return i.id;throw new Error("Invalid mode")},e.isValid=function(i){return i&&i.bit&&i.ccBits};function n(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+r)}}e.from=function(i,s){if(e.isValid(i))return i;try{return n(i)}catch{return s}}})(st);(function(e){const t=F,o=ve,n=we,r=st,i=bo,s=7973,l=t.getBCHDigit(s);function a(h,p,g){for(let f=1;f<=40;f++)if(p<=e.getCapacity(f,g,h))return f}function c(h,p){return r.getCharCountIndicator(h,p)+4}function d(h,p){let g=0;return h.forEach(function(f){const O=c(f.mode,p);g+=O+f.getBitsLength()}),g}function y(h,p){for(let g=1;g<=40;g++)if(d(h,g)<=e.getCapacity(g,p,r.MIXED))return g}e.from=function(p,g){return i.isValid(p)?parseInt(p,10):g},e.getCapacity=function(p,g,f){if(!i.isValid(p))throw new Error("Invalid QR Code version");typeof f>"u"&&(f=r.BYTE);const O=t.getSymbolTotalCodewords(p),m=o.getTotalCodewordsCount(p,g),b=(O-m)*8;if(f===r.MIXED)return b;const w=b-c(f,p);switch(f){case r.NUMERIC:return Math.floor(w/10*3);case r.ALPHANUMERIC:return Math.floor(w/11*2);case r.KANJI:return Math.floor(w/13);case r.BYTE:default:return Math.floor(w/8)}},e.getBestVersionForData=function(p,g){let f;const O=n.from(g,n.M);if(Array.isArray(p)){if(p.length>1)return y(p,O);if(p.length===0)return 1;f=p[0]}else f=p;return a(f.mode,f.getLength(),O)},e.getEncodedBits=function(p){if(!i.isValid(p)||p<7)throw new Error("Invalid QR Code version");let g=p<<12;for(;t.getBCHDigit(g)-l>=0;)g^=s<=0;)r^=Er<0&&(n=this.data.substr(o),r=parseInt(n,10),t.put(r,i*3+1))};var ni=Et;const ii=st,Re=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function At(e){this.mode=ii.ALPHANUMERIC,this.data=e}At.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};At.prototype.getLength=function(){return this.data.length};At.prototype.getBitsLength=function(){return At.getBitsLength(this.data.length)};At.prototype.write=function(t){let o;for(o=0;o+2<=this.data.length;o+=2){let n=Re.indexOf(this.data[o])*45;n+=Re.indexOf(this.data[o+1]),t.put(n,11)}this.data.length%2&&t.put(Re.indexOf(this.data[o]),6)};var si=At,li=function(t){for(var o=[],n=t.length,r=0;r=55296&&i<=56319&&n>r+1){var s=t.charCodeAt(r+1);s>=56320&&s<=57343&&(i=(i-55296)*1024+s-56320+65536,r+=1)}if(i<128){o.push(i);continue}if(i<2048){o.push(i>>6|192),o.push(i&63|128);continue}if(i<55296||i>=57344&&i<65536){o.push(i>>12|224),o.push(i>>6&63|128),o.push(i&63|128);continue}if(i>=65536&&i<=1114111){o.push(i>>18|240),o.push(i>>12&63|128),o.push(i>>6&63|128),o.push(i&63|128);continue}o.push(239,191,189)}return new Uint8Array(o).buffer};const ai=li,ci=st;function Ot(e){this.mode=ci.BYTE,typeof e=="string"&&(e=ai(e)),this.data=new Uint8Array(e)}Ot.getBitsLength=function(t){return t*8};Ot.prototype.getLength=function(){return this.data.length};Ot.prototype.getBitsLength=function(){return Ot.getBitsLength(this.data.length)};Ot.prototype.write=function(e){for(let t=0,o=this.data.length;t=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+` +Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),e.put(o,13)}};var mi=Pt;(function(e){const t=st,o=ni,n=si,r=di,i=mi,s=q,l=F,a=Wr;function c(m){return unescape(encodeURIComponent(m)).length}function d(m,b,w){const v=[];let C;for(;(C=m.exec(w))!==null;)v.push({data:C[0],index:C.index,mode:b,length:C[0].length});return v}function y(m){const b=d(s.NUMERIC,t.NUMERIC,m),w=d(s.ALPHANUMERIC,t.ALPHANUMERIC,m);let v,C;return l.isKanjiModeEnabled()?(v=d(s.BYTE,t.BYTE,m),C=d(s.KANJI,t.KANJI,m)):(v=d(s.BYTE_KANJI,t.BYTE,m),C=[]),b.concat(w,v,C).sort(function(R,U){return R.index-U.index}).map(function(R){return{data:R.data,mode:R.mode,length:R.length}})}function h(m,b){switch(b){case t.NUMERIC:return o.getBitsLength(m);case t.ALPHANUMERIC:return n.getBitsLength(m);case t.KANJI:return i.getBitsLength(m);case t.BYTE:return r.getBitsLength(m)}}function p(m){return m.reduce(function(b,w){const v=b.length-1>=0?b[b.length-1]:null;return v&&v.mode===w.mode?(b[b.length-1].data+=w.data,b):(b.push(w),b)},[])}function g(m){const b=[];for(let w=0;w=0&&l<=6&&(a===0||a===6)||a>=0&&a<=6&&(l===0||l===6)||l>=2&&l<=4&&a>=2&&a<=4?e.set(i+l,s+a,!0,!0):e.set(i+l,s+a,!1,!0))}}function xi(e){const t=e.size;for(let o=8;o>l&1)===1,e.set(r,i,s,!0),e.set(i,r,s,!0)}function Ne(e,t,o){const n=e.size,r=bi.getEncodedBits(t,o);let i,s;for(i=0;i<15;i++)s=(r>>i&1)===1,i<6?e.set(i,8,s,!0):i<8?e.set(i+1,8,s,!0):e.set(n-15+i,8,s,!0),i<8?e.set(8,n-i-1,s,!0):i<9?e.set(8,15-i-1+1,s,!0):e.set(8,15-i-1,s,!0);e.set(n-8,8,1,!0)}function Ei(e,t){const o=e.size;let n=-1,r=o-1,i=7,s=0;for(let l=o-1;l>0;l-=2)for(l===6&&l--;;){for(let a=0;a<2;a++)if(!e.isReserved(r,l-a)){let c=!1;s>>i&1)===1),e.set(r,l-a,c),i--,i===-1&&(s++,i=7)}if(r+=n,r<0||o<=r){r-=n,n=-n;break}}}function Ai(e,t,o){const n=new fi;o.forEach(function(a){n.put(a.mode.bit,4),n.put(a.getLength(),yi.getCharCountIndicator(a.mode,e)),a.write(n)});const r=ye.getSymbolTotalCodewords(e),i=Ye.getTotalCodewordsCount(e,t),s=(r-i)*8;for(n.getLengthInBits()+4<=s&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);const l=(s-n.getLengthInBits())/8;for(let a=0;a=7&&Ci(a,t),Ei(a,s),isNaN(n)&&(n=qe.getBestMask(a,Ne.bind(null,a,o))),qe.applyMask(n,a),Ne(a,o,n),{modules:a,version:t,errorCorrectionLevel:o,maskPattern:n,segments:r}}pr.create=function(t,o){if(typeof t>"u"||t==="")throw new Error("No input text");let n=De.M,r,i;return typeof o<"u"&&(n=De.from(o.errorCorrectionLevel,De.M),r=de.from(o.version),i=qe.from(o.maskPattern),o.toSJISFunc&&ye.setToSJISFunction(o.toSJISFunc)),Pi(t,r,n,i)};var Or={},yo={};(function(e){function t(o){if(typeof o=="number"&&(o=o.toString()),typeof o!="string")throw new Error("Color should be defined as hex string");let n=o.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+o);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(i){return[i,i]}))),n.length===6&&n.push("F","F");const r=parseInt(n.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const r=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,i=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:i,scale:i?4:s,margin:r,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,r){return r.width&&r.width>=n+r.margin*2?r.width/(n+r.margin*2):r.scale},e.getImageWidth=function(n,r){const i=e.getScale(n,r);return Math.floor((n+r.margin*2)*i)},e.qrToImageData=function(n,r,i){const s=r.modules.size,l=r.modules.data,a=e.getScale(s,i),c=Math.floor((s+i.margin*2)*a),d=i.margin*a,y=[i.color.light,i.color.dark];for(let h=0;h=d&&p>=d&&h"u"&&(!s||!s.getContext)&&(a=s,s=void 0),s||(c=n()),a=t.getOptions(a);const d=t.getImageWidth(i.modules.size,a),y=c.getContext("2d"),h=y.createImageData(d,d);return t.qrToImageData(h.data,i,a),o(y,c,d),y.putImageData(h,0,0),c},e.renderToDataURL=function(i,s,l){let a=l;typeof a>"u"&&(!s||!s.getContext)&&(a=s,s=void 0),a||(a={});const c=e.render(i,s,a),d=a.type||"image/png",y=a.rendererOpts||{};return c.toDataURL(d,y.quality)}})(Or);var Pr={};const Ii=yo;function Vo(e,t){const o=e.a/255,n=t+'="'+e.hex+'"';return o<1?n+" "+t+'-opacity="'+o.toFixed(2).slice(1)+'"':n}function Be(e,t,o){let n=e+t;return typeof o<"u"&&(n+=" "+o),n}function Ti(e,t,o){let n="",r=0,i=!1,s=0;for(let l=0;l0&&a>0&&e[l-1]||(n+=i?Be("M",a+o,.5+c+o):Be("m",r,0),r=0,i=!1),a+1':"",c="',d='viewBox="0 0 '+l+" "+l+'"',h=''+a+c+` +`;return typeof n=="function"&&n(null,h),h};const Mi=Vn,Ge=pr,Ir=Or,Si=Pr;function $o(e,t,o,n,r){const i=[].slice.call(arguments,1),s=i.length,l=typeof i[s-1]=="function";if(!l&&!Mi())throw new Error("Callback required as last argument");if(l){if(s<2)throw new Error("Too few arguments provided");s===2?(r=o,o=t,t=n=void 0):s===3&&(t.getContext&&typeof r>"u"?(r=n,n=void 0):(r=n,n=o,o=t,t=void 0))}else{if(s<1)throw new Error("Too few arguments provided");return s===1?(o=t,t=n=void 0):s===2&&!t.getContext&&(n=o,o=t,t=void 0),new Promise(function(a,c){try{const d=Ge.create(o,n);a(e(d,t,n))}catch(d){c(d)}})}try{const a=Ge.create(o,n);r(null,e(a,t,n))}catch(a){r(a)}}qt.create=Ge.create;qt.toCanvas=$o.bind(null,Ir.render);qt.toDataURL=$o.bind(null,Ir.renderToDataURL);qt.toString=$o.bind(null,function(e,t,o){return Si.render(e,o)});var Ri=Object.defineProperty,Zo=Object.getOwnPropertySymbols,Di=Object.prototype.hasOwnProperty,Li=Object.prototype.propertyIsEnumerable,Ko=(e,t,o)=>t in e?Ri(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,We=(e,t)=>{for(var o in t||(t={}))Di.call(t,o)&&Ko(e,o,t[o]);if(Zo)for(var o of Zo(t))Li.call(t,o)&&Ko(e,o,t[o]);return e};function Ni(){var e;const t=(e=$t.state.themeMode)!=null?e:"dark",n={light:{foreground:{1:"rgb(20,20,20)",2:"rgb(121,134,134)",3:"rgb(158,169,169)"},background:{1:"rgb(255,255,255)",2:"rgb(241,243,243)",3:"rgb(228,231,231)"},overlay:"rgba(0,0,0,0.1)"},dark:{foreground:{1:"rgb(228,231,231)",2:"rgb(148,158,158)",3:"rgb(110,119,119)"},background:{1:"rgb(20,20,20)",2:"rgb(39,42,42)",3:"rgb(59,64,64)"},overlay:"rgba(255,255,255,0.1)"}}[t];return{"--wcm-color-fg-1":n.foreground[1],"--wcm-color-fg-2":n.foreground[2],"--wcm-color-fg-3":n.foreground[3],"--wcm-color-bg-1":n.background[1],"--wcm-color-bg-2":n.background[2],"--wcm-color-bg-3":n.background[3],"--wcm-color-overlay":n.overlay}}function qo(){return{"--wcm-accent-color":"#3396FF","--wcm-accent-fill-color":"#FFFFFF","--wcm-z-index":"89","--wcm-background-color":"#3396FF","--wcm-background-border-radius":"8px","--wcm-container-border-radius":"30px","--wcm-wallet-icon-border-radius":"15px","--wcm-wallet-icon-large-border-radius":"30px","--wcm-wallet-icon-small-border-radius":"7px","--wcm-input-border-radius":"28px","--wcm-button-border-radius":"10px","--wcm-notification-border-radius":"36px","--wcm-secondary-button-border-radius":"28px","--wcm-icon-button-border-radius":"50%","--wcm-button-hover-highlight-border-radius":"10px","--wcm-text-big-bold-size":"20px","--wcm-text-big-bold-weight":"600","--wcm-text-big-bold-line-height":"24px","--wcm-text-big-bold-letter-spacing":"-0.03em","--wcm-text-big-bold-text-transform":"none","--wcm-text-xsmall-bold-size":"10px","--wcm-text-xsmall-bold-weight":"700","--wcm-text-xsmall-bold-line-height":"12px","--wcm-text-xsmall-bold-letter-spacing":"0.02em","--wcm-text-xsmall-bold-text-transform":"uppercase","--wcm-text-xsmall-regular-size":"12px","--wcm-text-xsmall-regular-weight":"600","--wcm-text-xsmall-regular-line-height":"14px","--wcm-text-xsmall-regular-letter-spacing":"-0.03em","--wcm-text-xsmall-regular-text-transform":"none","--wcm-text-small-thin-size":"14px","--wcm-text-small-thin-weight":"500","--wcm-text-small-thin-line-height":"16px","--wcm-text-small-thin-letter-spacing":"-0.03em","--wcm-text-small-thin-text-transform":"none","--wcm-text-small-regular-size":"14px","--wcm-text-small-regular-weight":"600","--wcm-text-small-regular-line-height":"16px","--wcm-text-small-regular-letter-spacing":"-0.03em","--wcm-text-small-regular-text-transform":"none","--wcm-text-medium-regular-size":"16px","--wcm-text-medium-regular-weight":"600","--wcm-text-medium-regular-line-height":"20px","--wcm-text-medium-regular-letter-spacing":"-0.03em","--wcm-text-medium-regular-text-transform":"none","--wcm-font-family":"-apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, 'Helvetica Neue', sans-serif","--wcm-font-feature-settings":"'tnum' on, 'lnum' on, 'case' on","--wcm-success-color":"rgb(38,181,98)","--wcm-error-color":"rgb(242, 90, 103)","--wcm-overlay-background-color":"rgba(0, 0, 0, 0.3)","--wcm-overlay-backdrop-filter":"none"}}const A={getPreset(e){return qo()[e]},setTheme(){const e=document.querySelector(":root"),{themeVariables:t}=$t.state;if(e){const o=We(We(We({},Ni()),qo()),t);Object.entries(o).forEach(([n,r])=>e.style.setProperty(n,r))}},globalCss:I`*,::after,::before{margin:0;padding:0;box-sizing:border-box;font-style:normal;text-rendering:optimizeSpeed;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-tap-highlight-color:transparent;backface-visibility:hidden}button{cursor:pointer;display:flex;justify-content:center;align-items:center;position:relative;border:none;background-color:transparent;transition:all .2s ease}@media (hover:hover) and (pointer:fine){button:active{transition:all .1s ease;transform:scale(.93)}}button::after{content:'';position:absolute;top:0;bottom:0;left:0;right:0;transition:background-color,.2s ease}button:disabled{cursor:not-allowed}button svg,button wcm-text{position:relative;z-index:1}input{border:none;outline:0;appearance:none}img{display:block}::selection{color:var(--wcm-accent-fill-color);background:var(--wcm-accent-color)}`},Bi=I`button{border-radius:var(--wcm-secondary-button-border-radius);height:28px;padding:0 10px;background-color:var(--wcm-accent-color)}button path{fill:var(--wcm-accent-fill-color)}button::after{border-radius:inherit;border:1px solid var(--wcm-color-overlay)}button:disabled::after{background-color:transparent}.wcm-icon-left svg{margin-right:5px}.wcm-icon-right svg{margin-left:5px}button:active::after{background-color:var(--wcm-color-overlay)}.wcm-ghost,.wcm-ghost:active::after,.wcm-outline{background-color:transparent}.wcm-ghost:active{opacity:.5}@media(hover:hover){button:hover::after{background-color:var(--wcm-color-overlay)}.wcm-ghost:hover::after{background-color:transparent}.wcm-ghost:hover{opacity:.5}}button:disabled{background-color:var(--wcm-color-bg-3);pointer-events:none}.wcm-ghost::after{border-color:transparent}.wcm-ghost path{fill:var(--wcm-color-fg-2)}.wcm-outline path{fill:var(--wcm-accent-color)}.wcm-outline:disabled{background-color:transparent;opacity:.5}`;var Wi=Object.defineProperty,Ui=Object.getOwnPropertyDescriptor,Mt=(e,t,o,n)=>{for(var r=n>1?void 0:n?Ui(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Wi(t,o,r),r};let rt=class extends E{constructor(){super(...arguments),this.disabled=!1,this.iconLeft=void 0,this.iconRight=void 0,this.onClick=()=>null,this.variant="default"}render(){const e={"wcm-icon-left":this.iconLeft!==void 0,"wcm-icon-right":this.iconRight!==void 0,"wcm-ghost":this.variant==="ghost","wcm-outline":this.variant==="outline"};let t="inverse";return this.variant==="ghost"&&(t="secondary"),this.variant==="outline"&&(t="accent"),u``}};rt.styles=[A.globalCss,Bi];Mt([_({type:Boolean})],rt.prototype,"disabled",2);Mt([_()],rt.prototype,"iconLeft",2);Mt([_()],rt.prototype,"iconRight",2);Mt([_()],rt.prototype,"onClick",2);Mt([_()],rt.prototype,"variant",2);rt=Mt([P("wcm-button")],rt);const ji=I`:host{display:inline-block}button{padding:0 15px 1px;height:40px;border-radius:var(--wcm-button-border-radius);color:var(--wcm-accent-fill-color);background-color:var(--wcm-accent-color)}button::after{content:'';top:0;bottom:0;left:0;right:0;position:absolute;background-color:transparent;border-radius:inherit;transition:background-color .2s ease;border:1px solid var(--wcm-color-overlay)}button:active::after{background-color:var(--wcm-color-overlay)}button:disabled{padding-bottom:0;background-color:var(--wcm-color-bg-3);color:var(--wcm-color-fg-3)}.wcm-secondary{color:var(--wcm-accent-color);background-color:transparent}.wcm-secondary::after{display:none}@media(hover:hover){button:hover::after{background-color:var(--wcm-color-overlay)}}`;var ki=Object.defineProperty,Hi=Object.getOwnPropertyDescriptor,xo=(e,t,o,n)=>{for(var r=n>1?void 0:n?Hi(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&ki(t,o,r),r};let zt=class extends E{constructor(){super(...arguments),this.disabled=!1,this.variant="primary"}render(){const e={"wcm-secondary":this.variant==="secondary"};return u``}};zt.styles=[A.globalCss,ji];xo([_({type:Boolean})],zt.prototype,"disabled",2);xo([_()],zt.prototype,"variant",2);zt=xo([P("wcm-button-big")],zt);const zi=I`:host{background-color:var(--wcm-color-bg-2);border-top:1px solid var(--wcm-color-bg-3)}div{padding:10px 20px;display:inherit;flex-direction:inherit;align-items:inherit;width:inherit;justify-content:inherit}`;var Fi=Object.defineProperty,Vi=Object.getOwnPropertyDescriptor,Zi=(e,t,o,n)=>{for(var r=n>1?void 0:n?Vi(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Fi(t,o,r),r};let Je=class extends E{render(){return u`
`}};Je.styles=[A.globalCss,zi];Je=Zi([P("wcm-info-footer")],Je);const T={CROSS_ICON:L``,WALLET_CONNECT_LOGO:L``,WALLET_CONNECT_ICON:L``,WALLET_CONNECT_ICON_COLORED:L``,BACK_ICON:L``,COPY_ICON:L``,RETRY_ICON:L``,DESKTOP_ICON:L``,MOBILE_ICON:L``,ARROW_DOWN_ICON:L``,ARROW_UP_RIGHT_ICON:L``,ARROW_RIGHT_ICON:L``,QRCODE_ICON:L``,SCAN_ICON:L``,CHECKMARK_ICON:L``,SEARCH_ICON:L``,WALLET_PLACEHOLDER:L``,GLOBE_ICON:L``},Ki=I`.wcm-toolbar-placeholder{top:0;bottom:0;left:0;right:0;width:100%;position:absolute;display:block;pointer-events:none;height:100px;border-radius:calc(var(--wcm-background-border-radius) * .9);background-color:var(--wcm-background-color);background-position:center;background-size:cover}.wcm-toolbar{height:38px;display:flex;position:relative;margin:5px 15px 5px 5px;justify-content:space-between;align-items:center}.wcm-toolbar img,.wcm-toolbar svg{height:28px;object-position:left center;object-fit:contain}#wcm-wc-logo path{fill:var(--wcm-accent-fill-color)}button{width:28px;height:28px;border-radius:var(--wcm-icon-button-border-radius);border:0;display:flex;justify-content:center;align-items:center;cursor:pointer;background-color:var(--wcm-color-bg-1);box-shadow:0 0 0 1px var(--wcm-color-overlay)}button:active{background-color:var(--wcm-color-bg-2)}button svg{display:block;object-position:center}button path{fill:var(--wcm-color-fg-1)}.wcm-toolbar div{display:flex}@media(hover:hover){button:hover{background-color:var(--wcm-color-bg-2)}}`;var qi=Object.defineProperty,Yi=Object.getOwnPropertyDescriptor,Gi=(e,t,o,n)=>{for(var r=n>1?void 0:n?Yi(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&qi(t,o,r),r};let Qe=class extends E{render(){return u`
${T.WALLET_CONNECT_LOGO}
`}};Qe.styles=[A.globalCss,Ki];Qe=Gi([P("wcm-modal-backcard")],Qe);const Ji=I`main{padding:20px;padding-top:0;width:100%}`;var Qi=Object.defineProperty,Xi=Object.getOwnPropertyDescriptor,ts=(e,t,o,n)=>{for(var r=n>1?void 0:n?Xi(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Qi(t,o,r),r};let Xe=class extends E{render(){return u`
`}};Xe.styles=[A.globalCss,Ji];Xe=ts([P("wcm-modal-content")],Xe);const es=I`footer{padding:10px;display:flex;flex-direction:column;align-items:inherit;justify-content:inherit;border-top:1px solid var(--wcm-color-bg-2)}`;var os=Object.defineProperty,rs=Object.getOwnPropertyDescriptor,ns=(e,t,o,n)=>{for(var r=n>1?void 0:n?rs(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&os(t,o,r),r};let to=class extends E{render(){return u`
`}};to.styles=[A.globalCss,es];to=ns([P("wcm-modal-footer")],to);const is=I`header{display:flex;justify-content:center;align-items:center;padding:20px;position:relative}.wcm-border{border-bottom:1px solid var(--wcm-color-bg-2);margin-bottom:20px}header button{padding:15px 20px}header button:active{opacity:.5}@media(hover:hover){header button:hover{opacity:.5}}.wcm-back-btn{position:absolute;left:0}.wcm-action-btn{position:absolute;right:0}path{fill:var(--wcm-accent-color)}`;var ss=Object.defineProperty,ls=Object.getOwnPropertyDescriptor,Gt=(e,t,o,n)=>{for(var r=n>1?void 0:n?ls(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&ss(t,o,r),r};let ft=class extends E{constructor(){super(...arguments),this.title="",this.onAction=void 0,this.actionIcon=void 0,this.border=!1}backBtnTemplate(){return u``}actionBtnTemplate(){return u``}render(){const e={"wcm-border":this.border},t=N.state.history.length>1,o=this.title?u`${this.title}`:u``;return u`
${t?this.backBtnTemplate():null} ${o} ${this.onAction?this.actionBtnTemplate():null}
`}};ft.styles=[A.globalCss,is];Gt([_()],ft.prototype,"title",2);Gt([_()],ft.prototype,"onAction",2);Gt([_()],ft.prototype,"actionIcon",2);Gt([_({type:Boolean})],ft.prototype,"border",2);ft=Gt([P("wcm-modal-header")],ft);const x={MOBILE_BREAKPOINT:600,WCM_RECENT_WALLET_DATA:"WCM_RECENT_WALLET_DATA",EXPLORER_WALLET_URL:"https://explorer.walletconnect.com/?type=wallet",getShadowRootElement(e,t){const o=e.renderRoot.querySelector(t);if(!o)throw new Error(`${t} not found`);return o},getWalletIcon({id:e,image_id:t}){const{walletImages:o}=ht.state;return o!=null&&o[e]?o[e]:t?k.getWalletImageUrl(t):""},getWalletName(e,t=!1){return t&&e.length>8?`${e.substring(0,8)}..`:e},isMobileAnimation(){return window.innerWidth<=x.MOBILE_BREAKPOINT},async preloadImage(e){const t=new Promise((o,n)=>{const r=new Image;r.onload=o,r.onerror=n,r.crossOrigin="anonymous",r.src=e});return Promise.race([t,$.wait(3e3)])},getErrorMessage(e){return e instanceof Error?e.message:"Unknown Error"},debounce(e,t=500){let o;return(...n)=>{function r(){e(...n)}o&&clearTimeout(o),o=setTimeout(r,t)}},handleMobileLinking(e,t="_self"){const{walletConnectUri:o}=Z.state,{mobile:n,name:r}=e,i=n==null?void 0:n.native,s=n==null?void 0:n.universal;x.setRecentWallet(e);function l(a){if(i){const c=$.formatNativeUrl(i,a,r);$.openHref(c,t)}else if(s){const c=$.formatUniversalUrl(s,a,r);$.openHref(c,t)}}o&&l(o)},handleAndroidLinking(){const{walletConnectUri:e}=Z.state;e&&($.setWalletConnectAndroidDeepLink(e),$.openHref(e,$.isTelegram()?"_blank":"_self"))},async handleUriCopy(){const{walletConnectUri:e}=Z.state;if(e)try{await navigator.clipboard.writeText(e),X.openToast("Link copied","success")}catch{X.openToast("Failed to copy","error")}},getCustomImageUrls(){const{walletImages:e}=ht.state,t=Object.values(e??{});return Object.values(t)},truncate(e,t=8){return e.length<=t?e:`${e.substring(0,4)}...${e.substring(e.length-4)}`},setRecentWallet(e){try{localStorage.setItem(x.WCM_RECENT_WALLET_DATA,JSON.stringify(e))}catch{console.info("Unable to set recent wallet")}},getRecentWallet(){try{const e=localStorage.getItem(x.WCM_RECENT_WALLET_DATA);return e?JSON.parse(e):void 0}catch{console.info("Unable to get recent wallet")}},caseSafeIncludes(e,t){return e.toUpperCase().includes(t.toUpperCase())},openWalletExplorerUrl(){$.openHref(x.EXPLORER_WALLET_URL,"_blank")},getCachedRouterWalletPlatforms(){const{desktop:e,mobile:t}=$.getWalletRouterData(),o=!!(e!=null&&e.native),n=!!(e!=null&&e.universal),r=!!(t!=null&&t.native)||!!(t!=null&&t.universal);return{isDesktop:o,isMobile:r,isWeb:n}},goToConnectingView(e){N.setData({Wallet:e});const t=$.isMobile(),{isDesktop:o,isWeb:n,isMobile:r}=x.getCachedRouterWalletPlatforms();t?r?(N.push("MobileConnecting"),!$.isAndroid()&&$.isTelegram()&&this.handleMobileLinking(e,"_blank")):n?N.push("WebConnecting"):N.push("InstallWallet"):o?N.push("DesktopConnecting"):n?N.push("WebConnecting"):r?N.push("MobileQrcodeConnecting"):N.push("InstallWallet")}},as=I`.wcm-router{overflow:hidden;will-change:transform}.wcm-content{display:flex;flex-direction:column}`;var cs=Object.defineProperty,ds=Object.getOwnPropertyDescriptor,_o=(e,t,o,n)=>{for(var r=n>1?void 0:n?ds(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&cs(t,o,r),r};let Ft=class extends E{constructor(){super(),this.view=N.state.view,this.prevView=N.state.view,this.unsubscribe=void 0,this.oldHeight="0px",this.resizeObserver=void 0,this.unsubscribe=N.subscribe(e=>{this.view!==e.view&&this.onChangeRoute()})}firstUpdated(){this.resizeObserver=new ResizeObserver(([e])=>{const t=`${e.contentRect.height}px`;this.oldHeight!=="0px"&&dt(this.routerEl,{height:[this.oldHeight,t]},{duration:.2}),this.oldHeight=t}),this.resizeObserver.observe(this.contentEl)}disconnectedCallback(){var e,t;(e=this.unsubscribe)==null||e.call(this),(t=this.resizeObserver)==null||t.disconnect()}get routerEl(){return x.getShadowRootElement(this,".wcm-router")}get contentEl(){return x.getShadowRootElement(this,".wcm-content")}viewTemplate(){switch(this.view){case"ConnectWallet":return u``;case"DesktopConnecting":return u``;case"MobileConnecting":return u``;case"WebConnecting":return u``;case"MobileQrcodeConnecting":return u``;case"WalletExplorer":return u``;case"Qrcode":return u``;case"InstallWallet":return u``;default:return u`
Not Found
`}}async onChangeRoute(){await dt(this.routerEl,{opacity:[1,0],scale:[1,1.02]},{duration:.15,delay:.1}).finished,this.view=N.state.view,dt(this.routerEl,{opacity:[0,1],scale:[.99,1]},{duration:.37,delay:.05})}render(){return u`
${this.viewTemplate()}
`}};Ft.styles=[A.globalCss,as];_o([H()],Ft.prototype,"view",2);_o([H()],Ft.prototype,"prevView",2);Ft=_o([P("wcm-modal-router")],Ft);const hs=I`div{height:36px;width:max-content;display:flex;justify-content:center;align-items:center;padding:9px 15px 11px;position:absolute;top:12px;box-shadow:0 6px 14px -6px rgba(10,16,31,.3),0 10px 32px -4px rgba(10,16,31,.15);z-index:2;left:50%;transform:translateX(-50%);pointer-events:none;backdrop-filter:blur(20px) saturate(1.8);-webkit-backdrop-filter:blur(20px) saturate(1.8);border-radius:var(--wcm-notification-border-radius);border:1px solid var(--wcm-color-overlay);background-color:var(--wcm-color-overlay)}svg{margin-right:5px}@-moz-document url-prefix(){div{background-color:var(--wcm-color-bg-3)}}.wcm-success path{fill:var(--wcm-accent-color)}.wcm-error path{fill:var(--wcm-error-color)}`;var us=Object.defineProperty,ms=Object.getOwnPropertyDescriptor,Tr=(e,t,o,n)=>{for(var r=n>1?void 0:n?ms(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&us(t,o,r),r};let he=class extends E{constructor(){super(),this.open=!1,this.unsubscribe=void 0,this.timeout=void 0,this.unsubscribe=X.subscribe(e=>{e.open?(this.open=!0,this.timeout=setTimeout(()=>X.closeToast(),2200)):(this.open=!1,clearTimeout(this.timeout))})}disconnectedCallback(){var e;(e=this.unsubscribe)==null||e.call(this),clearTimeout(this.timeout),X.closeToast()}render(){const{message:e,variant:t}=X.state,o={"wcm-success":t==="success","wcm-error":t==="error"};return this.open?u`
${t==="success"?T.CHECKMARK_ICON:null} ${t==="error"?T.CROSS_ICON:null}${e}
`:null}};he.styles=[A.globalCss,hs];Tr([H()],he.prototype,"open",2);he=Tr([P("wcm-modal-toast")],he);const fs=.1,Yo=2.5,G=7;function Ue(e,t,o){return e===t?!1:(e-t<0?t-e:e-t)<=o+fs}function ps(e,t){const o=Array.prototype.slice.call(qt.create(e,{errorCorrectionLevel:t}).modules.data,0),n=Math.sqrt(o.length);return o.reduce((r,i,s)=>(s%n===0?r.push([i]):r[r.length-1].push(i))&&r,[])}const gs={generate(e,t,o){const n="#141414",r="#ffffff",i=[],s=ps(e,"Q"),l=t/s.length,a=[{x:0,y:0},{x:1,y:0},{x:0,y:1}];a.forEach(({x:g,y:f})=>{const O=(s.length-G)*l*g,m=(s.length-G)*l*f,b=.45;for(let w=0;w`)}});const c=Math.floor((o+25)/l),d=s.length/2-c/2,y=s.length/2+c/2-1,h=[];s.forEach((g,f)=>{g.forEach((O,m)=>{if(s[f][m]&&!(fs.length-(G+1)&&ms.length-(G+1))&&!(f>d&&fd&&m{p[g]?p[g].push(f):p[g]=[f]}),Object.entries(p).map(([g,f])=>{const O=f.filter(m=>f.every(b=>!Ue(m,b,l)));return[Number(g),O]}).forEach(([g,f])=>{f.forEach(O=>{i.push(L``)})}),Object.entries(p).filter(([g,f])=>f.length>1).map(([g,f])=>{const O=f.filter(m=>f.some(b=>Ue(m,b,l)));return[Number(g),O]}).map(([g,f])=>{f.sort((m,b)=>mw.some(v=>Ue(m,v,l)));b?b.push(m):O.push([m])}return[g,O.map(m=>[m[0],m[m.length-1]])]}).forEach(([g,f])=>{f.forEach(([O,m])=>{i.push(L``)})}),i}},ws=I`@keyframes fadeIn{0%{opacity:0}100%{opacity:1}}div{position:relative;user-select:none;display:block;overflow:hidden;aspect-ratio:1/1;animation:fadeIn ease .2s}.wcm-dark{background-color:#fff;border-radius:var(--wcm-container-border-radius);padding:18px;box-shadow:0 2px 5px #000}svg:first-child,wcm-wallet-image{position:absolute;top:50%;left:50%;transform:translateY(-50%) translateX(-50%)}wcm-wallet-image{transform:translateY(-50%) translateX(-50%)}wcm-wallet-image{width:25%;height:25%;border-radius:var(--wcm-wallet-icon-border-radius)}svg:first-child{transform:translateY(-50%) translateX(-50%) scale(.9)}svg:first-child path:first-child{fill:var(--wcm-accent-color)}svg:first-child path:last-child{stroke:var(--wcm-color-overlay)}`;var vs=Object.defineProperty,bs=Object.getOwnPropertyDescriptor,St=(e,t,o,n)=>{for(var r=n>1?void 0:n?bs(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&vs(t,o,r),r};let nt=class extends E{constructor(){super(...arguments),this.uri="",this.size=0,this.imageId=void 0,this.walletId=void 0,this.imageUrl=void 0}svgTemplate(){const t=$t.state.themeMode==="light"?this.size:this.size-18*2;return L`${gs.generate(this.uri,t,t/4)}`}render(){const e={"wcm-dark":$t.state.themeMode==="dark"};return u`
${this.walletId||this.imageUrl?u``:T.WALLET_CONNECT_ICON_COLORED} ${this.svgTemplate()}
`}};nt.styles=[A.globalCss,ws];St([_()],nt.prototype,"uri",2);St([_({type:Number})],nt.prototype,"size",2);St([_()],nt.prototype,"imageId",2);St([_()],nt.prototype,"walletId",2);St([_()],nt.prototype,"imageUrl",2);nt=St([P("wcm-qrcode")],nt);const ys=I`:host{position:relative;height:28px;width:80%}input{width:100%;height:100%;line-height:28px!important;border-radius:var(--wcm-input-border-radius);font-style:normal;font-family:-apple-system,system-ui,BlinkMacSystemFont,'Segoe UI',Roboto,Ubuntu,'Helvetica Neue',sans-serif;font-feature-settings:'case' on;font-weight:500;font-size:16px;letter-spacing:-.03em;padding:0 10px 0 34px;transition:.2s all ease;color:var(--wcm-color-fg-1);background-color:var(--wcm-color-bg-3);box-shadow:inset 0 0 0 1px var(--wcm-color-overlay);caret-color:var(--wcm-accent-color)}input::placeholder{color:var(--wcm-color-fg-2)}svg{left:10px;top:4px;pointer-events:none;position:absolute;width:20px;height:20px}input:focus-within{box-shadow:inset 0 0 0 1px var(--wcm-accent-color)}path{fill:var(--wcm-color-fg-2)}`;var $s=Object.defineProperty,xs=Object.getOwnPropertyDescriptor,Mr=(e,t,o,n)=>{for(var r=n>1?void 0:n?xs(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&$s(t,o,r),r};let ue=class extends E{constructor(){super(...arguments),this.onChange=()=>null}render(){return u` ${T.SEARCH_ICON}`}};ue.styles=[A.globalCss,ys];Mr([_()],ue.prototype,"onChange",2);ue=Mr([P("wcm-search-input")],ue);const _s=I`@keyframes rotate{100%{transform:rotate(360deg)}}@keyframes dash{0%{stroke-dasharray:1,150;stroke-dashoffset:0}50%{stroke-dasharray:90,150;stroke-dashoffset:-35}100%{stroke-dasharray:90,150;stroke-dashoffset:-124}}svg{animation:rotate 2s linear infinite;display:flex;justify-content:center;align-items:center}svg circle{stroke-linecap:round;animation:dash 1.5s ease infinite;stroke:var(--wcm-accent-color)}`;var Cs=Object.defineProperty,Es=Object.getOwnPropertyDescriptor,As=(e,t,o,n)=>{for(var r=n>1?void 0:n?Es(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Cs(t,o,r),r};let eo=class extends E{render(){return u``}};eo.styles=[A.globalCss,_s];eo=As([P("wcm-spinner")],eo);const Os=I`span{font-style:normal;font-family:var(--wcm-font-family);font-feature-settings:var(--wcm-font-feature-settings)}.wcm-xsmall-bold{font-family:var(--wcm-text-xsmall-bold-font-family);font-weight:var(--wcm-text-xsmall-bold-weight);font-size:var(--wcm-text-xsmall-bold-size);line-height:var(--wcm-text-xsmall-bold-line-height);letter-spacing:var(--wcm-text-xsmall-bold-letter-spacing);text-transform:var(--wcm-text-xsmall-bold-text-transform)}.wcm-xsmall-regular{font-family:var(--wcm-text-xsmall-regular-font-family);font-weight:var(--wcm-text-xsmall-regular-weight);font-size:var(--wcm-text-xsmall-regular-size);line-height:var(--wcm-text-xsmall-regular-line-height);letter-spacing:var(--wcm-text-xsmall-regular-letter-spacing);text-transform:var(--wcm-text-xsmall-regular-text-transform)}.wcm-small-thin{font-family:var(--wcm-text-small-thin-font-family);font-weight:var(--wcm-text-small-thin-weight);font-size:var(--wcm-text-small-thin-size);line-height:var(--wcm-text-small-thin-line-height);letter-spacing:var(--wcm-text-small-thin-letter-spacing);text-transform:var(--wcm-text-small-thin-text-transform)}.wcm-small-regular{font-family:var(--wcm-text-small-regular-font-family);font-weight:var(--wcm-text-small-regular-weight);font-size:var(--wcm-text-small-regular-size);line-height:var(--wcm-text-small-regular-line-height);letter-spacing:var(--wcm-text-small-regular-letter-spacing);text-transform:var(--wcm-text-small-regular-text-transform)}.wcm-medium-regular{font-family:var(--wcm-text-medium-regular-font-family);font-weight:var(--wcm-text-medium-regular-weight);font-size:var(--wcm-text-medium-regular-size);line-height:var(--wcm-text-medium-regular-line-height);letter-spacing:var(--wcm-text-medium-regular-letter-spacing);text-transform:var(--wcm-text-medium-regular-text-transform)}.wcm-big-bold{font-family:var(--wcm-text-big-bold-font-family);font-weight:var(--wcm-text-big-bold-weight);font-size:var(--wcm-text-big-bold-size);line-height:var(--wcm-text-big-bold-line-height);letter-spacing:var(--wcm-text-big-bold-letter-spacing);text-transform:var(--wcm-text-big-bold-text-transform)}:host(*){color:var(--wcm-color-fg-1)}.wcm-color-primary{color:var(--wcm-color-fg-1)}.wcm-color-secondary{color:var(--wcm-color-fg-2)}.wcm-color-tertiary{color:var(--wcm-color-fg-3)}.wcm-color-inverse{color:var(--wcm-accent-fill-color)}.wcm-color-accnt{color:var(--wcm-accent-color)}.wcm-color-error{color:var(--wcm-error-color)}`;var Ps=Object.defineProperty,Is=Object.getOwnPropertyDescriptor,Co=(e,t,o,n)=>{for(var r=n>1?void 0:n?Is(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Ps(t,o,r),r};let Vt=class extends E{constructor(){super(...arguments),this.variant="medium-regular",this.color="primary"}render(){const e={"wcm-big-bold":this.variant==="big-bold","wcm-medium-regular":this.variant==="medium-regular","wcm-small-regular":this.variant==="small-regular","wcm-small-thin":this.variant==="small-thin","wcm-xsmall-regular":this.variant==="xsmall-regular","wcm-xsmall-bold":this.variant==="xsmall-bold","wcm-color-primary":this.color==="primary","wcm-color-secondary":this.color==="secondary","wcm-color-tertiary":this.color==="tertiary","wcm-color-inverse":this.color==="inverse","wcm-color-accnt":this.color==="accent","wcm-color-error":this.color==="error"};return u``}};Vt.styles=[A.globalCss,Os];Co([_()],Vt.prototype,"variant",2);Co([_()],Vt.prototype,"color",2);Vt=Co([P("wcm-text")],Vt);const Ts=I`button{width:100%;height:100%;border-radius:var(--wcm-button-hover-highlight-border-radius);display:flex;align-items:flex-start}button:active{background-color:var(--wcm-color-overlay)}@media(hover:hover){button:hover{background-color:var(--wcm-color-overlay)}}button>div{width:80px;padding:5px 0;display:flex;flex-direction:column;align-items:center}wcm-text{width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:center}wcm-wallet-image{height:60px;width:60px;transition:all .2s ease;border-radius:var(--wcm-wallet-icon-border-radius);margin-bottom:5px}.wcm-sublabel{margin-top:2px}`;var Ms=Object.defineProperty,Ss=Object.getOwnPropertyDescriptor,lt=(e,t,o,n)=>{for(var r=n>1?void 0:n?Ss(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Ms(t,o,r),r};let K=class extends E{constructor(){super(...arguments),this.onClick=()=>null,this.name="",this.walletId="",this.label=void 0,this.imageId=void 0,this.installed=!1,this.recent=!1}sublabelTemplate(){return this.recent?u`RECENT`:this.installed?u`INSTALLED`:null}handleClick(){Br.click({name:"WALLET_BUTTON",walletId:this.walletId}),this.onClick()}render(){var e;return u``}};K.styles=[A.globalCss,Ts];lt([_()],K.prototype,"onClick",2);lt([_()],K.prototype,"name",2);lt([_()],K.prototype,"walletId",2);lt([_()],K.prototype,"label",2);lt([_()],K.prototype,"imageId",2);lt([_({type:Boolean})],K.prototype,"installed",2);lt([_({type:Boolean})],K.prototype,"recent",2);K=lt([P("wcm-wallet-button")],K);const Rs=I`:host{display:block}div{overflow:hidden;position:relative;border-radius:inherit;width:100%;height:100%;background-color:var(--wcm-color-overlay)}svg{position:relative;width:100%;height:100%}div::after{content:'';position:absolute;top:0;bottom:0;left:0;right:0;border-radius:inherit;border:1px solid var(--wcm-color-overlay)}div img{width:100%;height:100%;object-fit:cover;object-position:center}#wallet-placeholder-fill{fill:var(--wcm-color-bg-3)}#wallet-placeholder-dash{stroke:var(--wcm-color-overlay)}`;var Ds=Object.defineProperty,Ls=Object.getOwnPropertyDescriptor,$e=(e,t,o,n)=>{for(var r=n>1?void 0:n?Ls(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Ds(t,o,r),r};let It=class extends E{constructor(){super(...arguments),this.walletId="",this.imageId=void 0,this.imageUrl=void 0}render(){var e;const t=(e=this.imageUrl)!=null&&e.length?this.imageUrl:x.getWalletIcon({id:this.walletId,image_id:this.imageId});return u`${t.length?u`
${this.id}
`:T.WALLET_PLACEHOLDER}`}};It.styles=[A.globalCss,Rs];$e([_()],It.prototype,"walletId",2);$e([_()],It.prototype,"imageId",2);$e([_()],It.prototype,"imageUrl",2);It=$e([P("wcm-wallet-image")],It);var Ns=Object.defineProperty,Bs=Object.getOwnPropertyDescriptor,Sr=(e,t,o,n)=>{for(var r=n>1?void 0:n?Bs(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Ns(t,o,r),r};let oo=class extends E{constructor(){super(),this.preload=!0,this.preloadData()}async loadImages(e){try{e!=null&&e.length&&await Promise.all(e.map(async t=>x.preloadImage(t)))}catch{console.info("Unsuccessful attempt at preloading some images",e)}}async preloadListings(){if(ht.state.enableExplorer){await k.getRecomendedWallets(),Z.setIsDataLoaded(!0);const{recomendedWallets:e}=k.state,t=e.map(o=>x.getWalletIcon(o));await this.loadImages(t)}else Z.setIsDataLoaded(!0)}async preloadCustomImages(){const e=x.getCustomImageUrls();await this.loadImages(e)}async preloadData(){try{this.preload&&(this.preload=!1,await Promise.all([this.preloadListings(),this.preloadCustomImages()]))}catch(e){console.error(e),X.openToast("Failed preloading","error")}}};Sr([H()],oo.prototype,"preload",2);oo=Sr([P("wcm-explorer-context")],oo);var Ws=Object.defineProperty,Us=Object.getOwnPropertyDescriptor,js=(e,t,o,n)=>{for(var r=n>1?void 0:n?Us(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Ws(t,o,r),r};let Go=class extends E{constructor(){super(),this.unsubscribeTheme=void 0,A.setTheme(),this.unsubscribeTheme=$t.subscribe(A.setTheme)}disconnectedCallback(){var e;(e=this.unsubscribeTheme)==null||e.call(this)}};Go=js([P("wcm-theme-context")],Go);const ks=I`@keyframes scroll{0%{transform:translate3d(0,0,0)}100%{transform:translate3d(calc(-70px * 9),0,0)}}.wcm-slider{position:relative;overflow-x:hidden;padding:10px 0;margin:0 -20px;width:calc(100% + 40px)}.wcm-track{display:flex;width:calc(70px * 18);animation:scroll 20s linear infinite;opacity:.7}.wcm-track svg{margin:0 5px}wcm-wallet-image{width:60px;height:60px;margin:0 5px;border-radius:var(--wcm-wallet-icon-border-radius)}.wcm-grid{display:grid;grid-template-columns:repeat(4,80px);justify-content:space-between}.wcm-title{display:flex;align-items:center;margin-bottom:10px}.wcm-title svg{margin-right:6px}.wcm-title path{fill:var(--wcm-accent-color)}wcm-modal-footer .wcm-title{padding:0 10px}wcm-button-big{position:absolute;top:50%;left:50%;transform:translateY(-50%) translateX(-50%);filter:drop-shadow(0 0 17px var(--wcm-color-bg-1))}wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-info-footer wcm-text{text-align:center;margin-bottom:15px}#wallet-placeholder-fill{fill:var(--wcm-color-bg-3)}#wallet-placeholder-dash{stroke:var(--wcm-color-overlay)}`;var Hs=Object.defineProperty,zs=Object.getOwnPropertyDescriptor,Fs=(e,t,o,n)=>{for(var r=n>1?void 0:n?zs(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Hs(t,o,r),r};let ro=class extends E{onGoToQrcode(){N.push("Qrcode")}render(){const{recomendedWallets:e}=k.state,t=[...e,...e],o=$.RECOMMENDED_WALLET_AMOUNT*2;return u`
${T.MOBILE_ICON}WalletConnect
${[...Array(o)].map((n,r)=>{const i=t[r%t.length];return i?u``:T.WALLET_PLACEHOLDER})}
Select Wallet
Choose WalletConnect to see supported apps on your device`}};ro.styles=[A.globalCss,ks];ro=Fs([P("wcm-android-wallet-selection")],ro);const Vs=I`@keyframes loading{to{stroke-dashoffset:0}}@keyframes shake{10%,90%{transform:translate3d(-1px,0,0)}20%,80%{transform:translate3d(1px,0,0)}30%,50%,70%{transform:translate3d(-2px,0,0)}40%,60%{transform:translate3d(2px,0,0)}}:host{display:flex;flex-direction:column;align-items:center}div{position:relative;width:110px;height:110px;display:flex;justify-content:center;align-items:center;margin:40px 0 20px 0;transform:translate3d(0,0,0)}svg{position:absolute;width:110px;height:110px;fill:none;stroke:transparent;stroke-linecap:round;stroke-width:2px;top:0;left:0}use{stroke:var(--wcm-accent-color);animation:loading 1s linear infinite}wcm-wallet-image{border-radius:var(--wcm-wallet-icon-large-border-radius);width:90px;height:90px}wcm-text{margin-bottom:40px}.wcm-error svg{stroke:var(--wcm-error-color)}.wcm-error use{display:none}.wcm-error{animation:shake .4s cubic-bezier(.36,.07,.19,.97) both}.wcm-stale svg,.wcm-stale use{display:none}`;var Zs=Object.defineProperty,Ks=Object.getOwnPropertyDescriptor,Rt=(e,t,o,n)=>{for(var r=n>1?void 0:n?Ks(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Zs(t,o,r),r};let it=class extends E{constructor(){super(...arguments),this.walletId=void 0,this.imageId=void 0,this.isError=!1,this.isStale=!1,this.label=""}svgLoaderTemplate(){var e,t;const i=(t=(e=$t.state.themeVariables)==null?void 0:e["--wcm-wallet-icon-large-border-radius"])!=null?t:A.getPreset("--wcm-wallet-icon-large-border-radius");let s=0;i.includes("%")?s=88/100*parseInt(i,10):s=parseInt(i,10),s*=1.17;const l=317-s*1.57,a=425-s*1.8;return u``}render(){const e={"wcm-error":this.isError,"wcm-stale":this.isStale};return u`
${this.svgLoaderTemplate()}
${this.isError?"Connection declined":this.label}`}};it.styles=[A.globalCss,Vs];Rt([_()],it.prototype,"walletId",2);Rt([_()],it.prototype,"imageId",2);Rt([_({type:Boolean})],it.prototype,"isError",2);Rt([_({type:Boolean})],it.prototype,"isStale",2);Rt([_()],it.prototype,"label",2);it=Rt([P("wcm-connector-waiting")],it);const yt={manualWallets(){var e,t;const{mobileWallets:o,desktopWallets:n}=ht.state,r=(e=yt.recentWallet())==null?void 0:e.id,i=$.isMobile()?o:n,s=i==null?void 0:i.filter(l=>r!==l.id);return(t=$.isMobile()?s==null?void 0:s.map(({id:l,name:a,links:c})=>({id:l,name:a,mobile:c,links:c})):s==null?void 0:s.map(({id:l,name:a,links:c})=>({id:l,name:a,desktop:c,links:c})))!=null?t:[]},recentWallet(){return x.getRecentWallet()},recomendedWallets(e=!1){var t;const o=e||(t=yt.recentWallet())==null?void 0:t.id,{recomendedWallets:n}=k.state;return n.filter(i=>o!==i.id)}},ot={onConnecting(e){x.goToConnectingView(e)},manualWalletsTemplate(){return yt.manualWallets().map(t=>u``)},recomendedWalletsTemplate(e=!1){return yt.recomendedWallets(e).map(o=>u``)},recentWalletTemplate(){const e=yt.recentWallet();if(e)return u``}},qs=I`.wcm-grid{display:grid;grid-template-columns:repeat(4,80px);justify-content:space-between}.wcm-desktop-title,.wcm-mobile-title{display:flex;align-items:center}.wcm-mobile-title{justify-content:space-between;margin-bottom:20px;margin-top:-10px}.wcm-desktop-title{margin-bottom:10px;padding:0 10px}.wcm-subtitle{display:flex;align-items:center}.wcm-subtitle:last-child path{fill:var(--wcm-color-fg-3)}.wcm-desktop-title svg,.wcm-mobile-title svg{margin-right:6px}.wcm-desktop-title path,.wcm-mobile-title path{fill:var(--wcm-accent-color)}`;var Ys=Object.defineProperty,Gs=Object.getOwnPropertyDescriptor,Js=(e,t,o,n)=>{for(var r=n>1?void 0:n?Gs(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Ys(t,o,r),r};let no=class extends E{render(){const{explorerExcludedWalletIds:e,enableExplorer:t}=ht.state,o=e!=="ALL"&&t,n=ot.manualWalletsTemplate(),r=ot.recomendedWalletsTemplate();let s=[ot.recentWalletTemplate(),...n,...r];s=s.filter(Boolean);const l=s.length>4||o;let a=[];l?a=s.slice(0,3):a=s;const c=!!a.length;return u`
${T.MOBILE_ICON}Mobile
${T.SCAN_ICON}Scan with your wallet
${c?u`
${T.DESKTOP_ICON}Desktop
${a} ${l?u``:null}
`:null}`}};no.styles=[A.globalCss,qs];no=Js([P("wcm-desktop-wallet-selection")],no);const Qs=I`div{background-color:var(--wcm-color-bg-2);padding:10px 20px 15px 20px;border-top:1px solid var(--wcm-color-bg-3);text-align:center}a{color:var(--wcm-accent-color);text-decoration:none;transition:opacity .2s ease-in-out;display:inline}a:active{opacity:.8}@media(hover:hover){a:hover{opacity:.8}}`;var Xs=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,el=(e,t,o,n)=>{for(var r=n>1?void 0:n?tl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Xs(t,o,r),r};let io=class extends E{render(){const{termsOfServiceUrl:e,privacyPolicyUrl:t}=ht.state;return e??t?u`
By connecting your wallet to this app, you agree to the app's ${e?u`Terms of Service`:null} ${e&&t?"and":null} ${t?u`Privacy Policy`:null}
`:null}};io.styles=[A.globalCss,Qs];io=el([P("wcm-legal-notice")],io);const ol=I`div{display:grid;grid-template-columns:repeat(4,80px);margin:0 -10px;justify-content:space-between;row-gap:10px}`;var rl=Object.defineProperty,nl=Object.getOwnPropertyDescriptor,il=(e,t,o,n)=>{for(var r=n>1?void 0:n?nl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&rl(t,o,r),r};let so=class extends E{onQrcode(){N.push("Qrcode")}render(){const{explorerExcludedWalletIds:e,enableExplorer:t}=ht.state,o=e!=="ALL"&&t,n=ot.manualWalletsTemplate(),r=ot.recomendedWalletsTemplate();let s=[ot.recentWalletTemplate(),...n,...r];s=s.filter(Boolean);const l=s.length>8||o;let a=[];l?a=s.slice(0,7):a=s;const c=!!a.length;return u`${c?u`
${a} ${l?u``:null}
`:null}`}};so.styles=[A.globalCss,ol];so=il([P("wcm-mobile-wallet-selection")],so);const sl=I`:host{all:initial}.wcm-overlay{top:0;bottom:0;left:0;right:0;position:fixed;z-index:var(--wcm-z-index);overflow:hidden;display:flex;justify-content:center;align-items:center;opacity:0;pointer-events:none;background-color:var(--wcm-overlay-background-color);backdrop-filter:var(--wcm-overlay-backdrop-filter)}@media(max-height:720px) and (orientation:landscape){.wcm-overlay{overflow:scroll;align-items:flex-start;padding:20px 0}}.wcm-active{pointer-events:auto}.wcm-container{position:relative;max-width:360px;width:100%;outline:0;border-radius:var(--wcm-background-border-radius) var(--wcm-background-border-radius) var(--wcm-container-border-radius) var(--wcm-container-border-radius);border:1px solid var(--wcm-color-overlay);overflow:hidden}.wcm-card{width:100%;position:relative;border-radius:var(--wcm-container-border-radius);overflow:hidden;box-shadow:0 6px 14px -6px rgba(10,16,31,.12),0 10px 32px -4px rgba(10,16,31,.1),0 0 0 1px var(--wcm-color-overlay);background-color:var(--wcm-color-bg-1);color:var(--wcm-color-fg-1)}@media(max-width:600px){.wcm-container{max-width:440px;border-radius:var(--wcm-background-border-radius) var(--wcm-background-border-radius) 0 0}.wcm-card{border-radius:var(--wcm-container-border-radius) var(--wcm-container-border-radius) 0 0}.wcm-overlay{align-items:flex-end}}@media(max-width:440px){.wcm-container{border:0}}`;var ll=Object.defineProperty,al=Object.getOwnPropertyDescriptor,Eo=(e,t,o,n)=>{for(var r=n>1?void 0:n?al(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&ll(t,o,r),r};let Zt=class extends E{constructor(){super(),this.open=!1,this.active=!1,this.unsubscribeModal=void 0,this.abortController=void 0,this.unsubscribeModal=oe.subscribe(e=>{e.open?this.onOpenModalEvent():this.onCloseModalEvent()})}disconnectedCallback(){var e;(e=this.unsubscribeModal)==null||e.call(this)}get overlayEl(){return x.getShadowRootElement(this,".wcm-overlay")}get containerEl(){return x.getShadowRootElement(this,".wcm-container")}toggleBodyScroll(e){if(document.querySelector("body"))if(e){const o=document.getElementById("wcm-styles");o==null||o.remove()}else document.head.insertAdjacentHTML("beforeend",'')}onCloseModal(e){e.target===e.currentTarget&&oe.close()}onOpenModalEvent(){this.toggleBodyScroll(!1),this.addKeyboardEvents(),this.open=!0,setTimeout(async()=>{const e=x.isMobileAnimation()?{y:["50vh","0vh"]}:{scale:[.98,1]},t=.1,o=.2;await Promise.all([dt(this.overlayEl,{opacity:[0,1]},{delay:t,duration:o}).finished,dt(this.containerEl,e,{delay:t,duration:o}).finished]),this.active=!0},0)}async onCloseModalEvent(){this.toggleBodyScroll(!0),this.removeKeyboardEvents();const e=x.isMobileAnimation()?{y:["0vh","50vh"]}:{scale:[1,.98]},t=.2;await Promise.all([dt(this.overlayEl,{opacity:[1,0]},{duration:t}).finished,dt(this.containerEl,e,{duration:t}).finished]),this.containerEl.removeAttribute("style"),this.active=!1,this.open=!1}addKeyboardEvents(){this.abortController=new AbortController,window.addEventListener("keydown",e=>{var t;e.key==="Escape"?oe.close():e.key==="Tab"&&((t=e.target)!=null&&t.tagName.includes("wcm-")||this.containerEl.focus())},this.abortController),this.containerEl.focus()}removeKeyboardEvents(){var e;(e=this.abortController)==null||e.abort(),this.abortController=void 0}render(){const e={"wcm-overlay":!0,"wcm-active":this.active};return u`
${this.open?u`
`:null}
`}};Zt.styles=[A.globalCss,sl];Eo([H()],Zt.prototype,"open",2);Eo([H()],Zt.prototype,"active",2);Zt=Eo([P("wcm-modal")],Zt);const cl=I`div{display:flex;margin-top:15px}slot{display:inline-block;margin:0 5px}wcm-button{margin:0 5px}`;var dl=Object.defineProperty,hl=Object.getOwnPropertyDescriptor,Jt=(e,t,o,n)=>{for(var r=n>1?void 0:n?hl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&dl(t,o,r),r};let pt=class extends E{constructor(){super(...arguments),this.isMobile=!1,this.isDesktop=!1,this.isWeb=!1,this.isRetry=!1}onMobile(){$.isMobile()?N.replace("MobileConnecting"):N.replace("MobileQrcodeConnecting")}onDesktop(){N.replace("DesktopConnecting")}onWeb(){N.replace("WebConnecting")}render(){return u`
${this.isRetry?u``:null} ${this.isMobile?u`Mobile`:null} ${this.isDesktop?u`Desktop`:null} ${this.isWeb?u`Web`:null}
`}};pt.styles=[A.globalCss,cl];Jt([_({type:Boolean})],pt.prototype,"isMobile",2);Jt([_({type:Boolean})],pt.prototype,"isDesktop",2);Jt([_({type:Boolean})],pt.prototype,"isWeb",2);Jt([_({type:Boolean})],pt.prototype,"isRetry",2);pt=Jt([P("wcm-platform-selection")],pt);const ul=I`button{display:flex;flex-direction:column;padding:5px 10px;border-radius:var(--wcm-button-hover-highlight-border-radius);height:100%;justify-content:flex-start}.wcm-icons{width:60px;height:60px;display:flex;flex-wrap:wrap;padding:7px;border-radius:var(--wcm-wallet-icon-border-radius);justify-content:space-between;align-items:center;margin-bottom:5px;background-color:var(--wcm-color-bg-2);box-shadow:inset 0 0 0 1px var(--wcm-color-overlay)}button:active{background-color:var(--wcm-color-overlay)}@media(hover:hover){button:hover{background-color:var(--wcm-color-overlay)}}.wcm-icons img{width:21px;height:21px;object-fit:cover;object-position:center;border-radius:calc(var(--wcm-wallet-icon-border-radius)/ 2);border:1px solid var(--wcm-color-overlay)}.wcm-icons svg{width:21px;height:21px}.wcm-icons img:nth-child(1),.wcm-icons img:nth-child(2),.wcm-icons svg:nth-child(1),.wcm-icons svg:nth-child(2){margin-bottom:4px}wcm-text{width:100%;text-align:center}#wallet-placeholder-fill{fill:var(--wcm-color-bg-3)}#wallet-placeholder-dash{stroke:var(--wcm-color-overlay)}`;var ml=Object.defineProperty,fl=Object.getOwnPropertyDescriptor,pl=(e,t,o,n)=>{for(var r=n>1?void 0:n?fl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&ml(t,o,r),r};let lo=class extends E{onClick(){N.push("WalletExplorer")}render(){const{recomendedWallets:e}=k.state,t=yt.manualWallets(),o=[...e,...t].reverse().slice(0,4);return u``}};lo.styles=[A.globalCss,ul];lo=pl([P("wcm-view-all-wallets-button")],lo);const gl=I`.wcm-qr-container{width:100%;display:flex;justify-content:center;align-items:center;aspect-ratio:1/1}`;var wl=Object.defineProperty,vl=Object.getOwnPropertyDescriptor,xe=(e,t,o,n)=>{for(var r=n>1?void 0:n?vl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&wl(t,o,r),r};let Tt=class extends E{constructor(){super(),this.walletId="",this.imageId="",this.uri="",setTimeout(()=>{const{walletConnectUri:e}=Z.state;this.uri=e},0)}get overlayEl(){return x.getShadowRootElement(this,".wcm-qr-container")}render(){return u`
${this.uri?u``:u``}
`}};Tt.styles=[A.globalCss,gl];xe([_()],Tt.prototype,"walletId",2);xe([_()],Tt.prototype,"imageId",2);xe([H()],Tt.prototype,"uri",2);Tt=xe([P("wcm-walletconnect-qr")],Tt);var bl=Object.defineProperty,yl=Object.getOwnPropertyDescriptor,$l=(e,t,o,n)=>{for(var r=n>1?void 0:n?yl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&bl(t,o,r),r};let ao=class extends E{viewTemplate(){return $.isAndroid()&&!$.isTelegram()?u``:$.isMobile()?u``:u``}render(){return u`${this.viewTemplate()}`}};ao.styles=[A.globalCss];ao=$l([P("wcm-connect-wallet-view")],ao);const xl=I`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}`;var _l=Object.defineProperty,Cl=Object.getOwnPropertyDescriptor,Rr=(e,t,o,n)=>{for(var r=n>1?void 0:n?Cl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&_l(t,o,r),r};let me=class extends E{constructor(){super(),this.isError=!1,this.openDesktopApp()}onFormatAndRedirect(e){const{desktop:t,name:o}=$.getWalletRouterData(),n=t==null?void 0:t.native,r=t==null?void 0:t.universal;if(n){const i=$.formatNativeUrl(n,e,o);$.openHref(i,"_self")}else if(r){const i=$.formatUniversalUrl(r,e,o);$.openHref(i,"_blank")}}openDesktopApp(){const{walletConnectUri:e}=Z.state,t=$.getWalletRouterData();x.setRecentWallet(t),e&&this.onFormatAndRedirect(e)}render(){const{name:e,id:t,image_id:o}=$.getWalletRouterData(),{isMobile:n,isWeb:r}=x.getCachedRouterWalletPlatforms();return u`${`Connection can continue loading if ${e} is not installed on your device`}Retry`}};me.styles=[A.globalCss,xl];Rr([H()],me.prototype,"isError",2);me=Rr([P("wcm-desktop-connecting-view")],me);const El=I`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}wcm-button{margin-top:15px}`;var Al=Object.defineProperty,Ol=Object.getOwnPropertyDescriptor,Pl=(e,t,o,n)=>{for(var r=n>1?void 0:n?Ol(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Al(t,o,r),r};let co=class extends E{onInstall(e){e&&$.openHref(e,"_blank")}render(){const{name:e,id:t,image_id:o,homepage:n}=$.getWalletRouterData();return u`${`Download ${e} to continue. If multiple browser extensions are installed, disable non ${e} ones and try again`}Download`}};co.styles=[A.globalCss,El];co=Pl([P("wcm-install-wallet-view")],co);const Il=I`wcm-wallet-image{border-radius:var(--wcm-wallet-icon-large-border-radius);width:96px;height:96px;margin-bottom:20px}wcm-info-footer{display:flex;width:100%}.wcm-app-store{justify-content:space-between}.wcm-app-store wcm-wallet-image{margin-right:10px;margin-bottom:0;width:28px;height:28px;border-radius:var(--wcm-wallet-icon-small-border-radius)}.wcm-app-store div{display:flex;align-items:center}.wcm-app-store wcm-button{margin-right:-10px}.wcm-note{flex-direction:column;align-items:center;padding:5px 0}.wcm-note wcm-text{text-align:center}wcm-platform-selection{margin-top:-15px}.wcm-note wcm-text{margin-top:15px}.wcm-note wcm-text span{color:var(--wcm-accent-color)}`;var Tl=Object.defineProperty,Ml=Object.getOwnPropertyDescriptor,Dr=(e,t,o,n)=>{for(var r=n>1?void 0:n?Ml(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Tl(t,o,r),r};let fe=class extends E{constructor(){super(),this.isError=!1,this.openMobileApp()}onFormatAndRedirect(e,t=!1){const{mobile:o,name:n}=$.getWalletRouterData(),r=o==null?void 0:o.native,i=o==null?void 0:o.universal,s=$.isTelegram()?"_blank":"_self";if(e=$.isTelegram()&&$.isAndroid()?encodeURIComponent(e):e,r&&!t){const l=$.formatNativeUrl(r,e,n);$.openHref(l,s)}else if(i){const l=$.formatUniversalUrl(i,e,n);$.openHref(l,s)}}openMobileApp(e=!1){const{walletConnectUri:t}=Z.state,o=$.getWalletRouterData();t&&this.onFormatAndRedirect(t,e),x.setRecentWallet(o)}onGoToAppStore(e){e&&$.openHref(e,"_blank")}render(){const{name:e,id:t,image_id:o,app:n,mobile:r}=$.getWalletRouterData(),{isWeb:i}=x.getCachedRouterWalletPlatforms(),s=n==null?void 0:n.ios,l=r==null?void 0:r.universal;return u`Retry${l?u`Still doesn't work? Try this alternate link`:null}
${`Get ${e}`}
App Store
`}};fe.styles=[A.globalCss,Il];Dr([H()],fe.prototype,"isError",2);fe=Dr([P("wcm-mobile-connecting-view")],fe);const Sl=I`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}`;var Rl=Object.defineProperty,Dl=Object.getOwnPropertyDescriptor,Ll=(e,t,o,n)=>{for(var r=n>1?void 0:n?Dl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Rl(t,o,r),r};let ho=class extends E{render(){const{name:e,id:t,image_id:o}=$.getWalletRouterData(),{isDesktop:n,isWeb:r}=x.getCachedRouterWalletPlatforms();return u`${`Scan this QR Code with your phone's camera or inside ${e} app`}`}};ho.styles=[A.globalCss,Sl];ho=Ll([P("wcm-mobile-qr-connecting-view")],ho);var Nl=Object.defineProperty,Bl=Object.getOwnPropertyDescriptor,Wl=(e,t,o,n)=>{for(var r=n>1?void 0:n?Bl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&Nl(t,o,r),r};let uo=class extends E{render(){return u``}};uo.styles=[A.globalCss];uo=Wl([P("wcm-qrcode-view")],uo);const Ul=I`wcm-modal-content{height:clamp(200px,60vh,600px);display:block;overflow:scroll;scrollbar-width:none;position:relative;margin-top:1px}.wcm-grid{display:grid;grid-template-columns:repeat(4,80px);justify-content:space-between;margin:-15px -10px;padding-top:20px}wcm-modal-content::after,wcm-modal-content::before{content:'';position:fixed;pointer-events:none;z-index:1;width:100%;height:20px;opacity:1}wcm-modal-content::before{box-shadow:0 -1px 0 0 var(--wcm-color-bg-1);background:linear-gradient(var(--wcm-color-bg-1),rgba(255,255,255,0))}wcm-modal-content::after{box-shadow:0 1px 0 0 var(--wcm-color-bg-1);background:linear-gradient(rgba(255,255,255,0),var(--wcm-color-bg-1));top:calc(100% - 20px)}wcm-modal-content::-webkit-scrollbar{display:none}.wcm-placeholder-block{display:flex;justify-content:center;align-items:center;height:100px;overflow:hidden}.wcm-empty,.wcm-loading{display:flex}.wcm-loading .wcm-placeholder-block{height:100%}.wcm-end-reached .wcm-placeholder-block{height:0;opacity:0}.wcm-empty .wcm-placeholder-block{opacity:1;height:100%}wcm-wallet-button{margin:calc((100% - 60px)/ 3) 0}`;var jl=Object.defineProperty,kl=Object.getOwnPropertyDescriptor,Qt=(e,t,o,n)=>{for(var r=n>1?void 0:n?kl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&jl(t,o,r),r};const je=40;let gt=class extends E{constructor(){super(...arguments),this.loading=!k.state.wallets.listings.length,this.firstFetch=!k.state.wallets.listings.length,this.search="",this.endReached=!1,this.intersectionObserver=void 0,this.searchDebounce=x.debounce(e=>{e.length>=1?(this.firstFetch=!0,this.endReached=!1,this.search=e,k.resetSearch(),this.fetchWallets()):this.search&&(this.search="",this.endReached=this.isLastPage(),k.resetSearch())})}firstUpdated(){this.createPaginationObserver()}disconnectedCallback(){var e;(e=this.intersectionObserver)==null||e.disconnect()}get placeholderEl(){return x.getShadowRootElement(this,".wcm-placeholder-block")}createPaginationObserver(){this.intersectionObserver=new IntersectionObserver(([e])=>{e.isIntersecting&&!(this.search&&this.firstFetch)&&this.fetchWallets()}),this.intersectionObserver.observe(this.placeholderEl)}isLastPage(){const{wallets:e,search:t}=k.state,{listings:o,total:n}=this.search?t:e;return n<=je||o.length>=n}async fetchWallets(){var e;const{wallets:t,search:o}=k.state,{listings:n,total:r,page:i}=this.search?o:t;if(!this.endReached&&(this.firstFetch||r>je&&n.lengthx.getWalletIcon(c));await Promise.all([...a.map(async c=>x.preloadImage(c)),$.wait(300)]),this.endReached=this.isLastPage()}catch(s){console.error(s),X.openToast(x.getErrorMessage(s),"error")}finally{this.loading=!1,this.firstFetch=!1}}onConnect(e){$.isAndroid()?x.handleMobileLinking(e):x.goToConnectingView(e)}onSearchChange(e){const{value:t}=e.target;this.searchDebounce(t)}render(){const{wallets:e,search:t}=k.state,{listings:o}=this.search?t:e,n=this.loading&&!o.length,r=this.search.length>=3;let i=ot.manualWalletsTemplate(),s=ot.recomendedWalletsTemplate(!0);r&&(i=i.filter(({values:c})=>x.caseSafeIncludes(c[0],this.search)),s=s.filter(({values:c})=>x.caseSafeIncludes(c[0],this.search)));const l=!this.loading&&!o.length&&!s.length,a={"wcm-loading":n,"wcm-end-reached":this.endReached||!this.loading,"wcm-empty":l};return u`
${n?null:i} ${n?null:s} ${n?null:o.map(c=>u`${c?u``:null}`)}
${l?u`No results found`:null} ${!l&&this.loading?u``:null}
`}};gt.styles=[A.globalCss,Ul];Qt([H()],gt.prototype,"loading",2);Qt([H()],gt.prototype,"firstFetch",2);Qt([H()],gt.prototype,"search",2);Qt([H()],gt.prototype,"endReached",2);gt=Qt([P("wcm-wallet-explorer-view")],gt);const Hl=I`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}`;var zl=Object.defineProperty,Fl=Object.getOwnPropertyDescriptor,Lr=(e,t,o,n)=>{for(var r=n>1?void 0:n?Fl(t,o):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=(n?s(t,o,r):s(r))||r);return n&&r&&zl(t,o,r),r};let pe=class extends E{constructor(){super(),this.isError=!1,this.openWebWallet()}onFormatAndRedirect(e){const{desktop:t,name:o}=$.getWalletRouterData(),n=t==null?void 0:t.universal;if(n){const r=$.formatUniversalUrl(n,e,o);$.openHref(r,"_blank")}}openWebWallet(){const{walletConnectUri:e}=Z.state,t=$.getWalletRouterData();x.setRecentWallet(t),e&&this.onFormatAndRedirect(e)}render(){const{name:e,id:t,image_id:o}=$.getWalletRouterData(),{isMobile:n,isDesktop:r}=x.getCachedRouterWalletPlatforms(),i=$.isMobile();return u`${`${e} web app has opened in a new tab. Go there, accept the connection, and come back`}Retry`}};pe.styles=[A.globalCss,Hl];Lr([H()],pe.prototype,"isError",2);pe=Lr([P("wcm-web-connecting-view")],pe);export{Zt as WcmModal,nt as WcmQrCode}; diff --git a/buddybook/assets/index.es-KLKTVizS.js b/buddybook/assets/index.es-KLKTVizS.js new file mode 100644 index 0000000..f6bc8c1 --- /dev/null +++ b/buddybook/assets/index.es-KLKTVizS.js @@ -0,0 +1,70 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DY1ObU95.js","assets/index-B-6Lwopd.js","assets/index-Dt_CGZqf.css"])))=>i.map(i=>d[i]); +import{g as Tv,o as U4,p as $4,d as ji,q as Ar,r as z4,h as S0,_ as j4}from"./index-B-6Lwopd.js";import{e as Hi,J as I0}from"./events-BzDGR98G.js";import{r as M0,i as xh}from"./inherits_browser-BwZ6FBWK.js";var xe={};/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */var Vl=function(r,e){return Vl=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])},Vl(r,e)};function k4(r,e){Vl(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var Gl=function(){return Gl=Object.assign||function(e){for(var t,i=1,n=arguments.length;i=0;u--)(f=r[u])&&(a=(n<3?f(a):n>3?f(e,t,a):f(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a}function V4(r,e){return function(t,i){e(t,i,r)}}function G4(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function W4(r,e,t,i){function n(a){return a instanceof t?a:new t(function(f){f(a)})}return new(t||(t=Promise))(function(a,f){function u(y){try{p(i.next(y))}catch(A){f(A)}}function b(y){try{p(i.throw(y))}catch(A){f(A)}}function p(y){y.done?a(y.value):n(y.value).then(u,b)}p((i=i.apply(r,e||[])).next())})}function J4(r,e){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,n,a,f;return f={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function u(p){return function(y){return b([p,y])}}function b(p){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,n&&(a=p[0]&2?n.return:p[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,p[1])).done)return a;switch(n=0,a&&(p=[p[0]&2,a.value]),p[0]){case 0:case 1:a=p;break;case 4:return t.label++,{value:p[1],done:!1};case 5:t.label++,n=p[1],p=[0];continue;case 7:p=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(p[0]===6||p[0]===2)){t=0;continue}if(p[0]===3&&(!a||p[1]>a[0]&&p[1]=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Dv(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),n,a=[],f;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(u){f={error:u}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(f)throw f.error}}return a}function X4(){for(var r=[],e=0;e1||u(R,O)})})}function u(R,O){try{b(i[R](O))}catch(N){A(a[0][3],N)}}function b(R){R.value instanceof lc?Promise.resolve(R.value.v).then(p,y):A(a[0][2],R)}function p(R){u("next",R)}function y(R){u("throw",R)}function A(R,O){R(O),a.shift(),a.length&&u(a[0][0],a[0][1])}}function t8(r){var e,t;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,a){e[n]=r[n]?function(f){return(t=!t)?{value:lc(r[n](f)),done:n==="return"}:a?a(f):f}:a}}function r8(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Wl=="function"?Wl(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(a){t[a]=r[a]&&function(f){return new Promise(function(u,b){f=r[a](f),n(u,b,f.done,f.value)})}}function n(a,f,u,b){Promise.resolve(b).then(function(p){a({value:p,done:u})},f)}}function i8(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function n8(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function s8(r){return r&&r.__esModule?r:{default:r}}function a8(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function o8(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}const c8=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Gl},__asyncDelegator:t8,__asyncGenerator:e8,__asyncValues:r8,__await:lc,__awaiter:W4,__classPrivateFieldGet:a8,__classPrivateFieldSet:o8,__createBinding:Y4,__decorate:K4,__exportStar:Q4,__extends:k4,__generator:J4,__importDefault:s8,__importStar:n8,__makeTemplateObject:i8,__metadata:G4,__param:V4,__read:Dv,__rest:H4,__spread:X4,__spreadArrays:Z4,__values:Wl},Symbol.toStringTag,{value:"Module"})),Sh=Tv(c8);var sl={},ko={},s1;function f8(){if(s1)return ko;s1=1,Object.defineProperty(ko,"__esModule",{value:!0}),ko.delay=void 0;function r(e){return new Promise(t=>{setTimeout(()=>{t(!0)},e)})}return ko.delay=r,ko}var ra={},al={},ia={},a1;function h8(){return a1||(a1=1,Object.defineProperty(ia,"__esModule",{value:!0}),ia.ONE_THOUSAND=ia.ONE_HUNDRED=void 0,ia.ONE_HUNDRED=100,ia.ONE_THOUSAND=1e3),ia}var ol={},o1;function u8(){return o1||(o1=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.ONE_YEAR=r.FOUR_WEEKS=r.THREE_WEEKS=r.TWO_WEEKS=r.ONE_WEEK=r.THIRTY_DAYS=r.SEVEN_DAYS=r.FIVE_DAYS=r.THREE_DAYS=r.ONE_DAY=r.TWENTY_FOUR_HOURS=r.TWELVE_HOURS=r.SIX_HOURS=r.THREE_HOURS=r.ONE_HOUR=r.SIXTY_MINUTES=r.THIRTY_MINUTES=r.TEN_MINUTES=r.FIVE_MINUTES=r.ONE_MINUTE=r.SIXTY_SECONDS=r.THIRTY_SECONDS=r.TEN_SECONDS=r.FIVE_SECONDS=r.ONE_SECOND=void 0,r.ONE_SECOND=1,r.FIVE_SECONDS=5,r.TEN_SECONDS=10,r.THIRTY_SECONDS=30,r.SIXTY_SECONDS=60,r.ONE_MINUTE=r.SIXTY_SECONDS,r.FIVE_MINUTES=r.ONE_MINUTE*5,r.TEN_MINUTES=r.ONE_MINUTE*10,r.THIRTY_MINUTES=r.ONE_MINUTE*30,r.SIXTY_MINUTES=r.ONE_MINUTE*60,r.ONE_HOUR=r.SIXTY_MINUTES,r.THREE_HOURS=r.ONE_HOUR*3,r.SIX_HOURS=r.ONE_HOUR*6,r.TWELVE_HOURS=r.ONE_HOUR*12,r.TWENTY_FOUR_HOURS=r.ONE_HOUR*24,r.ONE_DAY=r.TWENTY_FOUR_HOURS,r.THREE_DAYS=r.ONE_DAY*3,r.FIVE_DAYS=r.ONE_DAY*5,r.SEVEN_DAYS=r.ONE_DAY*7,r.THIRTY_DAYS=r.ONE_DAY*30,r.ONE_WEEK=r.SEVEN_DAYS,r.TWO_WEEKS=r.ONE_WEEK*2,r.THREE_WEEKS=r.ONE_WEEK*3,r.FOUR_WEEKS=r.ONE_WEEK*4,r.ONE_YEAR=r.ONE_DAY*365}(ol)),ol}var c1;function Fv(){return c1||(c1=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=Sh;e.__exportStar(h8(),r),e.__exportStar(u8(),r)}(al)),al}var f1;function l8(){if(f1)return ra;f1=1,Object.defineProperty(ra,"__esModule",{value:!0}),ra.fromMiliseconds=ra.toMiliseconds=void 0;const r=Fv();function e(i){return i*r.ONE_THOUSAND}ra.toMiliseconds=e;function t(i){return Math.floor(i/r.ONE_THOUSAND)}return ra.fromMiliseconds=t,ra}var h1;function d8(){return h1||(h1=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=Sh;e.__exportStar(f8(),r),e.__exportStar(l8(),r)}(sl)),sl}var Ha={},u1;function p8(){if(u1)return Ha;u1=1,Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.Watch=void 0;class r{constructor(){this.timestamps=new Map}start(t){if(this.timestamps.has(t))throw new Error(`Watch already started for label: ${t}`);this.timestamps.set(t,{started:Date.now()})}stop(t){const i=this.get(t);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${t}`);const n=Date.now()-i.started;this.timestamps.set(t,{started:i.started,elapsed:n})}get(t){const i=this.timestamps.get(t);if(typeof i>"u")throw new Error(`No timestamp found for label: ${t}`);return i}elapsed(t){const i=this.get(t);return i.elapsed||Date.now()-i.started}}return Ha.Watch=r,Ha.default=r,Ha}var cl={},Ho={},l1;function g8(){if(l1)return Ho;l1=1,Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.IWatch=void 0;class r{}return Ho.IWatch=r,Ho}var d1;function v8(){return d1||(d1=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),Sh.__exportStar(g8(),r)}(cl)),cl}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=Sh;e.__exportStar(d8(),r),e.__exportStar(p8(),r),e.__exportStar(v8(),r),e.__exportStar(Fv(),r)})(xe);var Vt={};Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getLocalStorage=Vt.getLocalStorageOrThrow=Vt.getCrypto=Vt.getCryptoOrThrow=Bv=Vt.getLocation=Vt.getLocationOrThrow=P0=Vt.getNavigator=Vt.getNavigatorOrThrow=Ih=Vt.getDocument=Vt.getDocumentOrThrow=Vt.getFromWindowOrThrow=Vt.getFromWindow=void 0;function ma(r){let e;return typeof window<"u"&&typeof window[r]<"u"&&(e=window[r]),e}Vt.getFromWindow=ma;function co(r){const e=ma(r);if(!e)throw new Error(`${r} is not defined in Window`);return e}Vt.getFromWindowOrThrow=co;function b8(){return co("document")}Vt.getDocumentOrThrow=b8;function m8(){return ma("document")}var Ih=Vt.getDocument=m8;function y8(){return co("navigator")}Vt.getNavigatorOrThrow=y8;function w8(){return ma("navigator")}var P0=Vt.getNavigator=w8;function _8(){return co("location")}Vt.getLocationOrThrow=_8;function A8(){return ma("location")}var Bv=Vt.getLocation=A8;function E8(){return co("crypto")}Vt.getCryptoOrThrow=E8;function x8(){return ma("crypto")}Vt.getCrypto=x8;function S8(){return co("localStorage")}Vt.getLocalStorageOrThrow=S8;function I8(){return ma("localStorage")}Vt.getLocalStorage=I8;var O0={};Object.defineProperty(O0,"__esModule",{value:!0});var qv=O0.getWindowMetadata=void 0;const p1=Vt;function M8(){let r,e;try{r=p1.getDocumentOrThrow(),e=p1.getLocationOrThrow()}catch{return null}function t(){const A=r.getElementsByTagName("link"),R=[];for(let O=0;O-1){const W=N.getAttribute("href");if(W)if(W.toLowerCase().indexOf("https:")===-1&&W.toLowerCase().indexOf("http:")===-1&&W.indexOf("//")!==0){let Q=e.protocol+"//"+e.host;if(W.indexOf("/")===0)Q+=W;else{const j=e.pathname.split("/");j.pop();const Y=j.join("/");Q+=Y+"/"+W}R.push(Q)}else if(W.indexOf("//")===0){const Q=e.protocol+W;R.push(Q)}else R.push(W)}}return R}function i(...A){const R=r.getElementsByTagName("meta");for(let O=0;ON.getAttribute(W)).filter(W=>W?A.includes(W):!1);if(K.length&&K){const W=N.getAttribute("content");if(W)return W}}return""}function n(){let A=i("name","og:site_name","og:title","twitter:title");return A||(A=r.title),A}function a(){return i("description","og:description","twitter:description","keywords")}const f=n(),u=a(),b=e.origin,p=t();return{description:u,url:b,icons:p,name:f}}qv=O0.getWindowMetadata=M8;var dc={},P8=r=>encodeURIComponent(r).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Lv="%[a-f0-9]{2}",g1=new RegExp("("+Lv+")|([^%]+?)","gi"),v1=new RegExp("("+Lv+")+","gi");function Jl(r,e){try{return[decodeURIComponent(r.join(""))]}catch{}if(r.length===1)return r;e=e||1;var t=r.slice(0,e),i=r.slice(e);return Array.prototype.concat.call([],Jl(t),Jl(i))}function O8(r){try{return decodeURIComponent(r)}catch{for(var e=r.match(g1)||[],t=1;t{if(!(typeof r=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[r];const t=r.indexOf(e);return t===-1?[r]:[r.slice(0,t),r.slice(t+e.length)]},T8=function(r,e){for(var t={},i=Object.keys(r),n=Array.isArray(e),a=0;aj==null,f=Symbol("encodeFragmentIdentifier");function u(j){switch(j.arrayFormat){case"index":return Y=>(U,k)=>{const G=U.length;return k===void 0||j.skipNull&&k===null||j.skipEmptyString&&k===""?U:k===null?[...U,[y(Y,j),"[",G,"]"].join("")]:[...U,[y(Y,j),"[",y(G,j),"]=",y(k,j)].join("")]};case"bracket":return Y=>(U,k)=>k===void 0||j.skipNull&&k===null||j.skipEmptyString&&k===""?U:k===null?[...U,[y(Y,j),"[]"].join("")]:[...U,[y(Y,j),"[]=",y(k,j)].join("")];case"colon-list-separator":return Y=>(U,k)=>k===void 0||j.skipNull&&k===null||j.skipEmptyString&&k===""?U:k===null?[...U,[y(Y,j),":list="].join("")]:[...U,[y(Y,j),":list=",y(k,j)].join("")];case"comma":case"separator":case"bracket-separator":{const Y=j.arrayFormat==="bracket-separator"?"[]=":"=";return U=>(k,G)=>G===void 0||j.skipNull&&G===null||j.skipEmptyString&&G===""?k:(G=G===null?"":G,k.length===0?[[y(U,j),Y,y(G,j)].join("")]:[[k,y(G,j)].join(j.arrayFormatSeparator)])}default:return Y=>(U,k)=>k===void 0||j.skipNull&&k===null||j.skipEmptyString&&k===""?U:k===null?[...U,y(Y,j)]:[...U,[y(Y,j),"=",y(k,j)].join("")]}}function b(j){let Y;switch(j.arrayFormat){case"index":return(U,k,G)=>{if(Y=/\[(\d*)\]$/.exec(U),U=U.replace(/\[\d*\]$/,""),!Y){G[U]=k;return}G[U]===void 0&&(G[U]={}),G[U][Y[1]]=k};case"bracket":return(U,k,G)=>{if(Y=/(\[\])$/.exec(U),U=U.replace(/\[\]$/,""),!Y){G[U]=k;return}if(G[U]===void 0){G[U]=[k];return}G[U]=[].concat(G[U],k)};case"colon-list-separator":return(U,k,G)=>{if(Y=/(:list)$/.exec(U),U=U.replace(/:list$/,""),!Y){G[U]=k;return}if(G[U]===void 0){G[U]=[k];return}G[U]=[].concat(G[U],k)};case"comma":case"separator":return(U,k,G)=>{const x=typeof k=="string"&&k.includes(j.arrayFormatSeparator),B=typeof k=="string"&&!x&&A(k,j).includes(j.arrayFormatSeparator);k=B?A(k,j):k;const ae=x||B?k.split(j.arrayFormatSeparator).map(le=>A(le,j)):k===null?k:A(k,j);G[U]=ae};case"bracket-separator":return(U,k,G)=>{const x=/(\[\])$/.test(U);if(U=U.replace(/\[\]$/,""),!x){G[U]=k&&A(k,j);return}const B=k===null?[]:k.split(j.arrayFormatSeparator).map(ae=>A(ae,j));if(G[U]===void 0){G[U]=B;return}G[U]=[].concat(G[U],B)};default:return(U,k,G)=>{if(G[U]===void 0){G[U]=k;return}G[U]=[].concat(G[U],k)}}}function p(j){if(typeof j!="string"||j.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function y(j,Y){return Y.encode?Y.strict?e(j):encodeURIComponent(j):j}function A(j,Y){return Y.decode?t(j):j}function R(j){return Array.isArray(j)?j.sort():typeof j=="object"?R(Object.keys(j)).sort((Y,U)=>Number(Y)-Number(U)).map(Y=>j[Y]):j}function O(j){const Y=j.indexOf("#");return Y!==-1&&(j=j.slice(0,Y)),j}function N(j){let Y="";const U=j.indexOf("#");return U!==-1&&(Y=j.slice(U)),Y}function K(j){j=O(j);const Y=j.indexOf("?");return Y===-1?"":j.slice(Y+1)}function W(j,Y){return Y.parseNumbers&&!Number.isNaN(Number(j))&&typeof j=="string"&&j.trim()!==""?j=Number(j):Y.parseBooleans&&j!==null&&(j.toLowerCase()==="true"||j.toLowerCase()==="false")&&(j=j.toLowerCase()==="true"),j}function Q(j,Y){Y=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},Y),p(Y.arrayFormatSeparator);const U=b(Y),k=Object.create(null);if(typeof j!="string"||(j=j.trim().replace(/^[?#&]/,""),!j))return k;for(const G of j.split("&")){if(G==="")continue;let[x,B]=i(Y.decode?G.replace(/\+/g," "):G,"=");B=B===void 0?null:["comma","separator","bracket-separator"].includes(Y.arrayFormat)?B:A(B,Y),U(A(x,Y),B,k)}for(const G of Object.keys(k)){const x=k[G];if(typeof x=="object"&&x!==null)for(const B of Object.keys(x))x[B]=W(x[B],Y);else k[G]=W(x,Y)}return Y.sort===!1?k:(Y.sort===!0?Object.keys(k).sort():Object.keys(k).sort(Y.sort)).reduce((G,x)=>{const B=k[x];return B&&typeof B=="object"&&!Array.isArray(B)?G[x]=R(B):G[x]=B,G},Object.create(null))}r.extract=K,r.parse=Q,r.stringify=(j,Y)=>{if(!j)return"";Y=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},Y),p(Y.arrayFormatSeparator);const U=B=>Y.skipNull&&a(j[B])||Y.skipEmptyString&&j[B]==="",k=u(Y),G={};for(const B of Object.keys(j))U(B)||(G[B]=j[B]);const x=Object.keys(G);return Y.sort!==!1&&x.sort(Y.sort),x.map(B=>{const ae=j[B];return ae===void 0?"":ae===null?y(B,Y):Array.isArray(ae)?ae.length===0&&Y.arrayFormat==="bracket-separator"?y(B,Y)+"[]":ae.reduce(k(B),[]).join("&"):y(B,Y)+"="+y(ae,Y)}).filter(B=>B.length>0).join("&")},r.parseUrl=(j,Y)=>{Y=Object.assign({decode:!0},Y);const[U,k]=i(j,"#");return Object.assign({url:U.split("?")[0]||"",query:Q(K(j),Y)},Y&&Y.parseFragmentIdentifier&&k?{fragmentIdentifier:A(k,Y)}:{})},r.stringifyUrl=(j,Y)=>{Y=Object.assign({encode:!0,strict:!0,[f]:!0},Y);const U=O(j.url).split("?")[0]||"",k=r.extract(j.url),G=r.parse(k,{sort:!1}),x=Object.assign(G,j.query);let B=r.stringify(x,Y);B&&(B=`?${B}`);let ae=N(j.url);return j.fragmentIdentifier&&(ae=`#${Y[f]?y(j.fragmentIdentifier,Y):j.fragmentIdentifier}`),`${U}${B}${ae}`},r.pick=(j,Y,U)=>{U=Object.assign({parseFragmentIdentifier:!0,[f]:!1},U);const{url:k,query:G,fragmentIdentifier:x}=r.parseUrl(j,U);return r.stringifyUrl({url:k,query:n(G,Y),fragmentIdentifier:x},U)},r.exclude=(j,Y,U)=>{const k=Array.isArray(Y)?G=>!Y.includes(G):(G,x)=>!Y(G,x);return r.pick(j,k,U)}})(dc);var R0={},Mh={},mt={},Uv={};(function(r){Object.defineProperty(r,"__esModule",{value:!0});function e(u,b){var p=u>>>16&65535,y=u&65535,A=b>>>16&65535,R=b&65535;return y*R+(p*R+y*A<<16>>>0)|0}r.mul=Math.imul||e;function t(u,b){return u+b|0}r.add=t;function i(u,b){return u-b|0}r.sub=i;function n(u,b){return u<>>32-b}r.rotl=n;function a(u,b){return u<<32-b|u>>>b}r.rotr=a;function f(u){return typeof u=="number"&&isFinite(u)&&Math.floor(u)===u}r.isInteger=Number.isInteger||f,r.MAX_SAFE_INTEGER=9007199254740991,r.isSafeInteger=function(u){return r.isInteger(u)&&u>=-r.MAX_SAFE_INTEGER&&u<=r.MAX_SAFE_INTEGER}})(Uv);Object.defineProperty(mt,"__esModule",{value:!0});var $v=Uv;function D8(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])<<16>>16}mt.readInt16BE=D8;function F8(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])>>>0}mt.readUint16BE=F8;function B8(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])<<16>>16}mt.readInt16LE=B8;function q8(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])>>>0}mt.readUint16LE=q8;function zv(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>8,e[t+1]=r>>>0,e}mt.writeUint16BE=zv;mt.writeInt16BE=zv;function jv(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e}mt.writeUint16LE=jv;mt.writeInt16LE=jv;function Yl(r,e){return e===void 0&&(e=0),r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}mt.readInt32BE=Yl;function Ql(r,e){return e===void 0&&(e=0),(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}mt.readUint32BE=Ql;function Xl(r,e){return e===void 0&&(e=0),r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e]}mt.readInt32LE=Xl;function Zl(r,e){return e===void 0&&(e=0),(r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e])>>>0}mt.readUint32LE=Zl;function ah(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>24,e[t+1]=r>>>16,e[t+2]=r>>>8,e[t+3]=r>>>0,e}mt.writeUint32BE=ah;mt.writeInt32BE=ah;function oh(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e[t+2]=r>>>16,e[t+3]=r>>>24,e}mt.writeUint32LE=oh;mt.writeInt32LE=oh;function L8(r,e){e===void 0&&(e=0);var t=Yl(r,e),i=Yl(r,e+4);return t*4294967296+i-(i>>31)*4294967296}mt.readInt64BE=L8;function U8(r,e){e===void 0&&(e=0);var t=Ql(r,e),i=Ql(r,e+4);return t*4294967296+i}mt.readUint64BE=U8;function $8(r,e){e===void 0&&(e=0);var t=Xl(r,e),i=Xl(r,e+4);return i*4294967296+t-(t>>31)*4294967296}mt.readInt64LE=$8;function z8(r,e){e===void 0&&(e=0);var t=Zl(r,e),i=Zl(r,e+4);return i*4294967296+t}mt.readUint64LE=z8;function kv(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),ah(r/4294967296>>>0,e,t),ah(r>>>0,e,t+4),e}mt.writeUint64BE=kv;mt.writeInt64BE=kv;function Hv(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),oh(r>>>0,e,t),oh(r/4294967296>>>0,e,t+4),e}mt.writeUint64LE=Hv;mt.writeInt64LE=Hv;function j8(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintBE: array is too short for the given bitLength");for(var i=0,n=1,a=r/8+t-1;a>=t;a--)i+=e[a]*n,n*=256;return i}mt.readUintBE=j8;function k8(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintLE: array is too short for the given bitLength");for(var i=0,n=1,a=t;a=i;a--)t[a]=e/n&255,n*=256;return t}mt.writeUintBE=H8;function K8(r,e,t,i){if(t===void 0&&(t=new Uint8Array(r/8)),i===void 0&&(i=0),r%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!$v.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var n=1,a=i;a>>16|v<<16,F=F+v|0,x^=F,x=x>>>20|x<<12,U=U+B|0,_^=U,_=_>>>16|_<<16,m=m+_|0,B^=m,B=B>>>20|B<<12,k=k+ae|0,I^=k,I=I>>>16|I<<16,c=c+I|0,ae^=c,ae=ae>>>20|ae<<12,G=G+le|0,M^=G,M=M>>>16|M<<16,h=h+M|0,le^=h,le=le>>>20|le<<12,k=k+ae|0,I^=k,I=I>>>24|I<<8,c=c+I|0,ae^=c,ae=ae>>>25|ae<<7,G=G+le|0,M^=G,M=M>>>24|M<<8,h=h+M|0,le^=h,le=le>>>25|le<<7,U=U+B|0,_^=U,_=_>>>24|_<<8,m=m+_|0,B^=m,B=B>>>25|B<<7,Y=Y+x|0,v^=Y,v=v>>>24|v<<8,F=F+v|0,x^=F,x=x>>>25|x<<7,Y=Y+B|0,M^=Y,M=M>>>16|M<<16,c=c+M|0,B^=c,B=B>>>20|B<<12,U=U+ae|0,v^=U,v=v>>>16|v<<16,h=h+v|0,ae^=h,ae=ae>>>20|ae<<12,k=k+le|0,_^=k,_=_>>>16|_<<16,F=F+_|0,le^=F,le=le>>>20|le<<12,G=G+x|0,I^=G,I=I>>>16|I<<16,m=m+I|0,x^=m,x=x>>>20|x<<12,k=k+le|0,_^=k,_=_>>>24|_<<8,F=F+_|0,le^=F,le=le>>>25|le<<7,G=G+x|0,I^=G,I=I>>>24|I<<8,m=m+I|0,x^=m,x=x>>>25|x<<7,U=U+ae|0,v^=U,v=v>>>24|v<<8,h=h+v|0,ae^=h,ae=ae>>>25|ae<<7,Y=Y+B|0,M^=Y,M=M>>>24|M<<8,c=c+M|0,B^=c,B=B>>>25|B<<7;Ur.writeUint32LE(Y+i|0,r,0),Ur.writeUint32LE(U+n|0,r,4),Ur.writeUint32LE(k+a|0,r,8),Ur.writeUint32LE(G+f|0,r,12),Ur.writeUint32LE(x+u|0,r,16),Ur.writeUint32LE(B+b|0,r,20),Ur.writeUint32LE(ae+p|0,r,24),Ur.writeUint32LE(le+y|0,r,28),Ur.writeUint32LE(F+A|0,r,32),Ur.writeUint32LE(m+R|0,r,36),Ur.writeUint32LE(c+O|0,r,40),Ur.writeUint32LE(h+N|0,r,44),Ur.writeUint32LE(v+K|0,r,48),Ur.writeUint32LE(_+W|0,r,52),Ur.writeUint32LE(I+Q|0,r,56),Ur.writeUint32LE(M+j|0,r,60)}function Kv(r,e,t,i,n){if(n===void 0&&(n=0),r.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(i.length>>=8,e++;if(i>0)throw new Error("ChaCha: counter overflow")}var Vv={},Us={};Object.defineProperty(Us,"__esModule",{value:!0});function s_(r,e,t){return~(r-1)&e|r-1&t}Us.select=s_;function a_(r,e){return(r|0)-(e|0)-1>>>31&1}Us.lessOrEqual=a_;function Gv(r,e){if(r.length!==e.length)return 0;for(var t=0,i=0;i>>8}Us.compare=Gv;function o_(r,e){return r.length===0||e.length===0?!1:Gv(r,e)!==0}Us.equal=o_;(function(r){Object.defineProperty(r,"__esModule",{value:!0});var e=Us,t=Ei;r.DIGEST_LENGTH=16;var i=function(){function f(u){this.digestLength=r.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var b=u[0]|u[1]<<8;this._r[0]=b&8191;var p=u[2]|u[3]<<8;this._r[1]=(b>>>13|p<<3)&8191;var y=u[4]|u[5]<<8;this._r[2]=(p>>>10|y<<6)&7939;var A=u[6]|u[7]<<8;this._r[3]=(y>>>7|A<<9)&8191;var R=u[8]|u[9]<<8;this._r[4]=(A>>>4|R<<12)&255,this._r[5]=R>>>1&8190;var O=u[10]|u[11]<<8;this._r[6]=(R>>>14|O<<2)&8191;var N=u[12]|u[13]<<8;this._r[7]=(O>>>11|N<<5)&8065;var K=u[14]|u[15]<<8;this._r[8]=(N>>>8|K<<8)&8191,this._r[9]=K>>>5&127,this._pad[0]=u[16]|u[17]<<8,this._pad[1]=u[18]|u[19]<<8,this._pad[2]=u[20]|u[21]<<8,this._pad[3]=u[22]|u[23]<<8,this._pad[4]=u[24]|u[25]<<8,this._pad[5]=u[26]|u[27]<<8,this._pad[6]=u[28]|u[29]<<8,this._pad[7]=u[30]|u[31]<<8}return f.prototype._blocks=function(u,b,p){for(var y=this._fin?0:2048,A=this._h[0],R=this._h[1],O=this._h[2],N=this._h[3],K=this._h[4],W=this._h[5],Q=this._h[6],j=this._h[7],Y=this._h[8],U=this._h[9],k=this._r[0],G=this._r[1],x=this._r[2],B=this._r[3],ae=this._r[4],le=this._r[5],F=this._r[6],m=this._r[7],c=this._r[8],h=this._r[9];p>=16;){var v=u[b+0]|u[b+1]<<8;A+=v&8191;var _=u[b+2]|u[b+3]<<8;R+=(v>>>13|_<<3)&8191;var I=u[b+4]|u[b+5]<<8;O+=(_>>>10|I<<6)&8191;var M=u[b+6]|u[b+7]<<8;N+=(I>>>7|M<<9)&8191;var S=u[b+8]|u[b+9]<<8;K+=(M>>>4|S<<12)&8191,W+=S>>>1&8191;var d=u[b+10]|u[b+11]<<8;Q+=(S>>>14|d<<2)&8191;var g=u[b+12]|u[b+13]<<8;j+=(d>>>11|g<<5)&8191;var T=u[b+14]|u[b+15]<<8;Y+=(g>>>8|T<<8)&8191,U+=T>>>5|y;var Z=0,se=Z;se+=A*k,se+=R*(5*h),se+=O*(5*c),se+=N*(5*m),se+=K*(5*F),Z=se>>>13,se&=8191,se+=W*(5*le),se+=Q*(5*ae),se+=j*(5*B),se+=Y*(5*x),se+=U*(5*G),Z+=se>>>13,se&=8191;var P=Z;P+=A*G,P+=R*k,P+=O*(5*h),P+=N*(5*c),P+=K*(5*m),Z=P>>>13,P&=8191,P+=W*(5*F),P+=Q*(5*le),P+=j*(5*ae),P+=Y*(5*B),P+=U*(5*x),Z+=P>>>13,P&=8191;var ee=Z;ee+=A*x,ee+=R*G,ee+=O*k,ee+=N*(5*h),ee+=K*(5*c),Z=ee>>>13,ee&=8191,ee+=W*(5*m),ee+=Q*(5*F),ee+=j*(5*le),ee+=Y*(5*ae),ee+=U*(5*B),Z+=ee>>>13,ee&=8191;var q=Z;q+=A*B,q+=R*x,q+=O*G,q+=N*k,q+=K*(5*h),Z=q>>>13,q&=8191,q+=W*(5*c),q+=Q*(5*m),q+=j*(5*F),q+=Y*(5*le),q+=U*(5*ae),Z+=q>>>13,q&=8191;var z=Z;z+=A*ae,z+=R*B,z+=O*x,z+=N*G,z+=K*k,Z=z>>>13,z&=8191,z+=W*(5*h),z+=Q*(5*c),z+=j*(5*m),z+=Y*(5*F),z+=U*(5*le),Z+=z>>>13,z&=8191;var H=Z;H+=A*le,H+=R*ae,H+=O*B,H+=N*x,H+=K*G,Z=H>>>13,H&=8191,H+=W*k,H+=Q*(5*h),H+=j*(5*c),H+=Y*(5*m),H+=U*(5*F),Z+=H>>>13,H&=8191;var w=Z;w+=A*F,w+=R*le,w+=O*ae,w+=N*B,w+=K*x,Z=w>>>13,w&=8191,w+=W*G,w+=Q*k,w+=j*(5*h),w+=Y*(5*c),w+=U*(5*m),Z+=w>>>13,w&=8191;var $=Z;$+=A*m,$+=R*F,$+=O*le,$+=N*ae,$+=K*B,Z=$>>>13,$&=8191,$+=W*x,$+=Q*G,$+=j*k,$+=Y*(5*h),$+=U*(5*c),Z+=$>>>13,$&=8191;var ne=Z;ne+=A*c,ne+=R*m,ne+=O*F,ne+=N*le,ne+=K*ae,Z=ne>>>13,ne&=8191,ne+=W*B,ne+=Q*x,ne+=j*G,ne+=Y*k,ne+=U*(5*h),Z+=ne>>>13,ne&=8191;var ce=Z;ce+=A*h,ce+=R*c,ce+=O*m,ce+=N*F,ce+=K*le,Z=ce>>>13,ce&=8191,ce+=W*ae,ce+=Q*B,ce+=j*x,ce+=Y*G,ce+=U*k,Z+=ce>>>13,ce&=8191,Z=(Z<<2)+Z|0,Z=Z+se|0,se=Z&8191,Z=Z>>>13,P+=Z,A=se,R=P,O=ee,N=q,K=z,W=H,Q=w,j=$,Y=ne,U=ce,b+=16,p-=16}this._h[0]=A,this._h[1]=R,this._h[2]=O,this._h[3]=N,this._h[4]=K,this._h[5]=W,this._h[6]=Q,this._h[7]=j,this._h[8]=Y,this._h[9]=U},f.prototype.finish=function(u,b){b===void 0&&(b=0);var p=new Uint16Array(10),y,A,R,O;if(this._leftover){for(O=this._leftover,this._buffer[O++]=1;O<16;O++)this._buffer[O]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(y=this._h[1]>>>13,this._h[1]&=8191,O=2;O<10;O++)this._h[O]+=y,y=this._h[O]>>>13,this._h[O]&=8191;for(this._h[0]+=y*5,y=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=y,y=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=y,p[0]=this._h[0]+5,y=p[0]>>>13,p[0]&=8191,O=1;O<10;O++)p[O]=this._h[O]+y,y=p[O]>>>13,p[O]&=8191;for(p[9]-=8192,A=(y^1)-1,O=0;O<10;O++)p[O]&=A;for(A=~A,O=0;O<10;O++)this._h[O]=this._h[O]&A|p[O];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,R=this._h[0]+this._pad[0],this._h[0]=R&65535,O=1;O<8;O++)R=(this._h[O]+this._pad[O]|0)+(R>>>16)|0,this._h[O]=R&65535;return u[b+0]=this._h[0]>>>0,u[b+1]=this._h[0]>>>8,u[b+2]=this._h[1]>>>0,u[b+3]=this._h[1]>>>8,u[b+4]=this._h[2]>>>0,u[b+5]=this._h[2]>>>8,u[b+6]=this._h[3]>>>0,u[b+7]=this._h[3]>>>8,u[b+8]=this._h[4]>>>0,u[b+9]=this._h[4]>>>8,u[b+10]=this._h[5]>>>0,u[b+11]=this._h[5]>>>8,u[b+12]=this._h[6]>>>0,u[b+13]=this._h[6]>>>8,u[b+14]=this._h[7]>>>0,u[b+15]=this._h[7]>>>8,this._finished=!0,this},f.prototype.update=function(u){var b=0,p=u.length,y;if(this._leftover){y=16-this._leftover,y>p&&(y=p);for(var A=0;A=16&&(y=p-p%16,this._blocks(u,b,y),b+=y,p-=y),p){for(var A=0;A16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var O=new Uint8Array(16);O.set(p,O.length-p.length);var N=new Uint8Array(32);e.stream(this._key,O,N,4);var K=y.length+this.tagLength,W;if(R){if(R.length!==K)throw new Error("ChaCha20Poly1305: incorrect destination length");W=R}else W=new Uint8Array(K);return e.streamXOR(this._key,O,y,W,4),this._authenticate(W.subarray(W.length-this.tagLength,W.length),N,W.subarray(0,W.length-this.tagLength),A),i.wipe(O),W},b.prototype.open=function(p,y,A,R){if(p.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(y.length0&&O.update(f.subarray(R.length%16))),O.update(A),A.length%16>0&&O.update(f.subarray(A.length%16));var N=new Uint8Array(8);R&&n.writeUint64LE(R.length,N),O.update(N),n.writeUint64LE(A.length,N),O.update(N);for(var K=O.digest(),W=0;Wthis.blockSize?this._inner.update(t).finish(i).clean():i.set(t);for(var n=0;n1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},r.prototype.expand=function(e){for(var t=new Uint8Array(e),i=0;i256)throw new Error("randomString charset is too long");let R="";const O=y.length,N=256-256%O;for(;p>0;){const K=n(Math.ceil(p*256/N),A);for(let W=0;W0;W++){const Q=K[W];Q0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=b[y++],p--;this._bufferLength===this.blockSize&&(a(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(p>=this.blockSize&&(y=a(this._temp,this._state,b,y,p),p%=this.blockSize);p>0;)this._buffer[this._bufferLength++]=b[y++],p--;return this},u.prototype.finish=function(b){if(!this._finished){var p=this._bytesHashed,y=this._bufferLength,A=p/536870912|0,R=p<<3,O=p%64<56?64:128;this._buffer[y]=128;for(var N=y+1;N0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},u.prototype.restoreState=function(b){return this._state.set(b.state),this._bufferLength=b.bufferLength,b.buffer&&this._buffer.set(b.buffer),this._bytesHashed=b.bytesHashed,this._finished=!1,this},u.prototype.cleanSavedState=function(b){t.wipe(b.state),b.buffer&&t.wipe(b.buffer),b.bufferLength=0,b.bytesHashed=0},u}();r.SHA256=i;var n=new Int32Array([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 a(u,b,p,y,A){for(;A>=64;){for(var R=b[0],O=b[1],N=b[2],K=b[3],W=b[4],Q=b[5],j=b[6],Y=b[7],U=0;U<16;U++){var k=y+U*4;u[U]=e.readUint32BE(p,k)}for(var U=16;U<64;U++){var G=u[U-2],x=(G>>>17|G<<15)^(G>>>19|G<<13)^G>>>10;G=u[U-15];var B=(G>>>7|G<<25)^(G>>>18|G<<14)^G>>>3;u[U]=(x+u[U-7]|0)+(B+u[U-16]|0)}for(var U=0;U<64;U++){var x=(((W>>>6|W<<26)^(W>>>11|W<<21)^(W>>>25|W<<7))+(W&Q^~W&j)|0)+(Y+(n[U]+u[U]|0)|0)|0,B=((R>>>2|R<<30)^(R>>>13|R<<19)^(R>>>22|R<<10))+(R&O^R&N^O&N)|0;Y=j,j=Q,Q=W,W=K+x|0,K=N,N=O,O=R,R=x+B|0}b[0]+=R,b[1]+=O,b[2]+=N,b[3]+=K,b[4]+=W,b[5]+=Q,b[6]+=j,b[7]+=Y,y+=64,A-=64}return y}function f(u){var b=new i;b.update(u);var p=b.digest();return b.clean(),p}r.hash=f})(Ac);var C0={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.sharedKey=r.generateKeyPair=r.generateKeyPairFromSeed=r.scalarMultBase=r.scalarMult=r.SHARED_KEY_LENGTH=r.SECRET_KEY_LENGTH=r.PUBLIC_KEY_LENGTH=void 0;const e=$s,t=Ei;r.PUBLIC_KEY_LENGTH=32,r.SECRET_KEY_LENGTH=32,r.SHARED_KEY_LENGTH=32;function i(U){const k=new Float64Array(16);if(U)for(let G=0;G>16&1),G[le-1]&=65535;G[15]=x[15]-32767-(G[14]>>16&1);const ae=G[15]>>16&1;G[14]&=65535,u(x,G,1-ae)}for(let B=0;B<16;B++)U[2*B]=x[B]&255,U[2*B+1]=x[B]>>8}function p(U,k){for(let G=0;G<16;G++)U[G]=k[2*G]+(k[2*G+1]<<8);U[15]&=32767}function y(U,k,G){for(let x=0;x<16;x++)U[x]=k[x]+G[x]}function A(U,k,G){for(let x=0;x<16;x++)U[x]=k[x]-G[x]}function R(U,k,G){let x,B,ae=0,le=0,F=0,m=0,c=0,h=0,v=0,_=0,I=0,M=0,S=0,d=0,g=0,T=0,Z=0,se=0,P=0,ee=0,q=0,z=0,H=0,w=0,$=0,ne=0,ce=0,he=0,ye=0,we=0,Ce=0,Qe=0,Oe=0,Te=G[0],Ie=G[1],me=G[2],Re=G[3],De=G[4],ve=G[5],Ne=G[6],Se=G[7],be=G[8],Le=G[9],Me=G[10],_e=G[11],He=G[12],Ve=G[13],Ee=G[14],Ke=G[15];x=k[0],ae+=x*Te,le+=x*Ie,F+=x*me,m+=x*Re,c+=x*De,h+=x*ve,v+=x*Ne,_+=x*Se,I+=x*be,M+=x*Le,S+=x*Me,d+=x*_e,g+=x*He,T+=x*Ve,Z+=x*Ee,se+=x*Ke,x=k[1],le+=x*Te,F+=x*Ie,m+=x*me,c+=x*Re,h+=x*De,v+=x*ve,_+=x*Ne,I+=x*Se,M+=x*be,S+=x*Le,d+=x*Me,g+=x*_e,T+=x*He,Z+=x*Ve,se+=x*Ee,P+=x*Ke,x=k[2],F+=x*Te,m+=x*Ie,c+=x*me,h+=x*Re,v+=x*De,_+=x*ve,I+=x*Ne,M+=x*Se,S+=x*be,d+=x*Le,g+=x*Me,T+=x*_e,Z+=x*He,se+=x*Ve,P+=x*Ee,ee+=x*Ke,x=k[3],m+=x*Te,c+=x*Ie,h+=x*me,v+=x*Re,_+=x*De,I+=x*ve,M+=x*Ne,S+=x*Se,d+=x*be,g+=x*Le,T+=x*Me,Z+=x*_e,se+=x*He,P+=x*Ve,ee+=x*Ee,q+=x*Ke,x=k[4],c+=x*Te,h+=x*Ie,v+=x*me,_+=x*Re,I+=x*De,M+=x*ve,S+=x*Ne,d+=x*Se,g+=x*be,T+=x*Le,Z+=x*Me,se+=x*_e,P+=x*He,ee+=x*Ve,q+=x*Ee,z+=x*Ke,x=k[5],h+=x*Te,v+=x*Ie,_+=x*me,I+=x*Re,M+=x*De,S+=x*ve,d+=x*Ne,g+=x*Se,T+=x*be,Z+=x*Le,se+=x*Me,P+=x*_e,ee+=x*He,q+=x*Ve,z+=x*Ee,H+=x*Ke,x=k[6],v+=x*Te,_+=x*Ie,I+=x*me,M+=x*Re,S+=x*De,d+=x*ve,g+=x*Ne,T+=x*Se,Z+=x*be,se+=x*Le,P+=x*Me,ee+=x*_e,q+=x*He,z+=x*Ve,H+=x*Ee,w+=x*Ke,x=k[7],_+=x*Te,I+=x*Ie,M+=x*me,S+=x*Re,d+=x*De,g+=x*ve,T+=x*Ne,Z+=x*Se,se+=x*be,P+=x*Le,ee+=x*Me,q+=x*_e,z+=x*He,H+=x*Ve,w+=x*Ee,$+=x*Ke,x=k[8],I+=x*Te,M+=x*Ie,S+=x*me,d+=x*Re,g+=x*De,T+=x*ve,Z+=x*Ne,se+=x*Se,P+=x*be,ee+=x*Le,q+=x*Me,z+=x*_e,H+=x*He,w+=x*Ve,$+=x*Ee,ne+=x*Ke,x=k[9],M+=x*Te,S+=x*Ie,d+=x*me,g+=x*Re,T+=x*De,Z+=x*ve,se+=x*Ne,P+=x*Se,ee+=x*be,q+=x*Le,z+=x*Me,H+=x*_e,w+=x*He,$+=x*Ve,ne+=x*Ee,ce+=x*Ke,x=k[10],S+=x*Te,d+=x*Ie,g+=x*me,T+=x*Re,Z+=x*De,se+=x*ve,P+=x*Ne,ee+=x*Se,q+=x*be,z+=x*Le,H+=x*Me,w+=x*_e,$+=x*He,ne+=x*Ve,ce+=x*Ee,he+=x*Ke,x=k[11],d+=x*Te,g+=x*Ie,T+=x*me,Z+=x*Re,se+=x*De,P+=x*ve,ee+=x*Ne,q+=x*Se,z+=x*be,H+=x*Le,w+=x*Me,$+=x*_e,ne+=x*He,ce+=x*Ve,he+=x*Ee,ye+=x*Ke,x=k[12],g+=x*Te,T+=x*Ie,Z+=x*me,se+=x*Re,P+=x*De,ee+=x*ve,q+=x*Ne,z+=x*Se,H+=x*be,w+=x*Le,$+=x*Me,ne+=x*_e,ce+=x*He,he+=x*Ve,ye+=x*Ee,we+=x*Ke,x=k[13],T+=x*Te,Z+=x*Ie,se+=x*me,P+=x*Re,ee+=x*De,q+=x*ve,z+=x*Ne,H+=x*Se,w+=x*be,$+=x*Le,ne+=x*Me,ce+=x*_e,he+=x*He,ye+=x*Ve,we+=x*Ee,Ce+=x*Ke,x=k[14],Z+=x*Te,se+=x*Ie,P+=x*me,ee+=x*Re,q+=x*De,z+=x*ve,H+=x*Ne,w+=x*Se,$+=x*be,ne+=x*Le,ce+=x*Me,he+=x*_e,ye+=x*He,we+=x*Ve,Ce+=x*Ee,Qe+=x*Ke,x=k[15],se+=x*Te,P+=x*Ie,ee+=x*me,q+=x*Re,z+=x*De,H+=x*ve,w+=x*Ne,$+=x*Se,ne+=x*be,ce+=x*Le,he+=x*Me,ye+=x*_e,we+=x*He,Ce+=x*Ve,Qe+=x*Ee,Oe+=x*Ke,ae+=38*P,le+=38*ee,F+=38*q,m+=38*z,c+=38*H,h+=38*w,v+=38*$,_+=38*ne,I+=38*ce,M+=38*he,S+=38*ye,d+=38*we,g+=38*Ce,T+=38*Qe,Z+=38*Oe,B=1,x=ae+B+65535,B=Math.floor(x/65536),ae=x-B*65536,x=le+B+65535,B=Math.floor(x/65536),le=x-B*65536,x=F+B+65535,B=Math.floor(x/65536),F=x-B*65536,x=m+B+65535,B=Math.floor(x/65536),m=x-B*65536,x=c+B+65535,B=Math.floor(x/65536),c=x-B*65536,x=h+B+65535,B=Math.floor(x/65536),h=x-B*65536,x=v+B+65535,B=Math.floor(x/65536),v=x-B*65536,x=_+B+65535,B=Math.floor(x/65536),_=x-B*65536,x=I+B+65535,B=Math.floor(x/65536),I=x-B*65536,x=M+B+65535,B=Math.floor(x/65536),M=x-B*65536,x=S+B+65535,B=Math.floor(x/65536),S=x-B*65536,x=d+B+65535,B=Math.floor(x/65536),d=x-B*65536,x=g+B+65535,B=Math.floor(x/65536),g=x-B*65536,x=T+B+65535,B=Math.floor(x/65536),T=x-B*65536,x=Z+B+65535,B=Math.floor(x/65536),Z=x-B*65536,x=se+B+65535,B=Math.floor(x/65536),se=x-B*65536,ae+=B-1+37*(B-1),B=1,x=ae+B+65535,B=Math.floor(x/65536),ae=x-B*65536,x=le+B+65535,B=Math.floor(x/65536),le=x-B*65536,x=F+B+65535,B=Math.floor(x/65536),F=x-B*65536,x=m+B+65535,B=Math.floor(x/65536),m=x-B*65536,x=c+B+65535,B=Math.floor(x/65536),c=x-B*65536,x=h+B+65535,B=Math.floor(x/65536),h=x-B*65536,x=v+B+65535,B=Math.floor(x/65536),v=x-B*65536,x=_+B+65535,B=Math.floor(x/65536),_=x-B*65536,x=I+B+65535,B=Math.floor(x/65536),I=x-B*65536,x=M+B+65535,B=Math.floor(x/65536),M=x-B*65536,x=S+B+65535,B=Math.floor(x/65536),S=x-B*65536,x=d+B+65535,B=Math.floor(x/65536),d=x-B*65536,x=g+B+65535,B=Math.floor(x/65536),g=x-B*65536,x=T+B+65535,B=Math.floor(x/65536),T=x-B*65536,x=Z+B+65535,B=Math.floor(x/65536),Z=x-B*65536,x=se+B+65535,B=Math.floor(x/65536),se=x-B*65536,ae+=B-1+37*(B-1),U[0]=ae,U[1]=le,U[2]=F,U[3]=m,U[4]=c,U[5]=h,U[6]=v,U[7]=_,U[8]=I,U[9]=M,U[10]=S,U[11]=d,U[12]=g,U[13]=T,U[14]=Z,U[15]=se}function O(U,k){R(U,k,k)}function N(U,k){const G=i();for(let x=0;x<16;x++)G[x]=k[x];for(let x=253;x>=0;x--)O(G,G),x!==2&&x!==4&&R(G,G,k);for(let x=0;x<16;x++)U[x]=G[x]}function K(U,k){const G=new Uint8Array(32),x=new Float64Array(80),B=i(),ae=i(),le=i(),F=i(),m=i(),c=i();for(let I=0;I<31;I++)G[I]=U[I];G[31]=U[31]&127|64,G[0]&=248,p(x,k);for(let I=0;I<16;I++)ae[I]=x[I];B[0]=F[0]=1;for(let I=254;I>=0;--I){const M=G[I>>>3]>>>(I&7)&1;u(B,ae,M),u(le,F,M),y(m,B,le),A(B,B,le),y(le,ae,F),A(ae,ae,F),O(F,m),O(c,B),R(B,le,B),R(le,ae,m),y(m,B,le),A(B,B,le),O(ae,B),A(le,F,c),R(B,le,a),y(B,B,F),R(le,le,B),R(B,F,c),R(F,ae,x),O(ae,m),u(B,ae,M),u(le,F,M)}for(let I=0;I<16;I++)x[I+16]=B[I],x[I+32]=le[I],x[I+48]=ae[I],x[I+64]=F[I];const h=x.subarray(32),v=x.subarray(16);N(h,h),R(v,v,h);const _=new Uint8Array(32);return b(_,v),_}r.scalarMult=K;function W(U){return K(U,n)}r.scalarMultBase=W;function Q(U){if(U.length!==r.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${r.SECRET_KEY_LENGTH} bytes`);const k=new Uint8Array(U);return{publicKey:W(k),secretKey:k}}r.generateKeyPairFromSeed=Q;function j(U){const k=(0,e.randomBytes)(32,U),G=Q(k);return(0,t.wipe)(k),G}r.generateKeyPair=j;function Y(U,k,G=!1){if(U.length!==r.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(k.length!==r.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");const x=K(U,k);if(G){let B=0;for(let ae=0;aen+a.length,0));const t=U4(e);let i=0;for(const n of r)t.set(n,i),i+=n.length;return t}function Er(r,e="utf8"){const t=$4[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var Yv={};const __="elliptic",A_="6.5.7",E_="EC cryptography",x_="lib/elliptic.js",S_=["lib"],I_={lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},M_={type:"git",url:"git@github.com:indutny/elliptic"},P_=["EC","Elliptic","curve","Cryptography"],O_="Fedor Indutny ",R_="MIT",N_={url:"https://github.com/indutny/elliptic/issues"},C_="https://github.com/indutny/elliptic",T_={brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},D_={"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"},F_={name:__,version:A_,description:E_,main:x_,files:S_,scripts:I_,repository:M_,keywords:P_,author:O_,license:R_,bugs:N_,homepage:C_,devDependencies:T_,dependencies:D_};var xi={},T0={exports:{}};T0.exports;(function(r){(function(e,t){function i(F,m){if(!F)throw new Error(m||"Assertion failed")}function n(F,m){F.super_=m;var c=function(){};c.prototype=m.prototype,F.prototype=new c,F.prototype.constructor=F}function a(F,m,c){if(a.isBN(F))return F;this.negative=0,this.words=null,this.length=0,this.red=null,F!==null&&((m==="le"||m==="be")&&(c=m,m=10),this._init(F||0,m||10,c||"be"))}typeof e=="object"?e.exports=a:t.BN=a,a.BN=a,a.wordSize=26;var f;try{typeof window<"u"&&typeof window.Buffer<"u"?f=window.Buffer:f=M0.Buffer}catch{}a.isBN=function(m){return m instanceof a?!0:m!==null&&typeof m=="object"&&m.constructor.wordSize===a.wordSize&&Array.isArray(m.words)},a.max=function(m,c){return m.cmp(c)>0?m:c},a.min=function(m,c){return m.cmp(c)<0?m:c},a.prototype._init=function(m,c,h){if(typeof m=="number")return this._initNumber(m,c,h);if(typeof m=="object")return this._initArray(m,c,h);c==="hex"&&(c=16),i(c===(c|0)&&c>=2&&c<=36),m=m.toString().replace(/\s+/g,"");var v=0;m[0]==="-"&&(v++,this.negative=1),v=0;v-=3)I=m[v]|m[v-1]<<8|m[v-2]<<16,this.words[_]|=I<>>26-M&67108863,M+=24,M>=26&&(M-=26,_++);else if(h==="le")for(v=0,_=0;v>>26-M&67108863,M+=24,M>=26&&(M-=26,_++);return this.strip()};function u(F,m){var c=F.charCodeAt(m);return c>=65&&c<=70?c-55:c>=97&&c<=102?c-87:c-48&15}function b(F,m,c){var h=u(F,c);return c-1>=m&&(h|=u(F,c-1)<<4),h}a.prototype._parseHex=function(m,c,h){this.length=Math.ceil((m.length-c)/6),this.words=new Array(this.length);for(var v=0;v=c;v-=2)M=b(m,c,v)<<_,this.words[I]|=M&67108863,_>=18?(_-=18,I+=1,this.words[I]|=M>>>26):_+=8;else{var S=m.length-c;for(v=S%2===0?c+1:c;v=18?(_-=18,I+=1,this.words[I]|=M>>>26):_+=8}this.strip()};function p(F,m,c,h){for(var v=0,_=Math.min(F.length,c),I=m;I<_;I++){var M=F.charCodeAt(I)-48;v*=h,M>=49?v+=M-49+10:M>=17?v+=M-17+10:v+=M}return v}a.prototype._parseBase=function(m,c,h){this.words=[0],this.length=1;for(var v=0,_=1;_<=67108863;_*=c)v++;v--,_=_/c|0;for(var I=m.length-h,M=I%v,S=Math.min(I,I-M)+h,d=0,g=h;g1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},a.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},a.prototype.inspect=function(){return(this.red?""};var y=["","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"],A=[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],R=[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];a.prototype.toString=function(m,c){m=m||10,c=c|0||1;var h;if(m===16||m==="hex"){h="";for(var v=0,_=0,I=0;I>>24-v&16777215,_!==0||I!==this.length-1?h=y[6-S.length]+S+h:h=S+h,v+=2,v>=26&&(v-=26,I--)}for(_!==0&&(h=_.toString(16)+h);h.length%c!==0;)h="0"+h;return this.negative!==0&&(h="-"+h),h}if(m===(m|0)&&m>=2&&m<=36){var d=A[m],g=R[m];h="";var T=this.clone();for(T.negative=0;!T.isZero();){var Z=T.modn(g).toString(m);T=T.idivn(g),T.isZero()?h=Z+h:h=y[d-Z.length]+Z+h}for(this.isZero()&&(h="0"+h);h.length%c!==0;)h="0"+h;return this.negative!==0&&(h="-"+h),h}i(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var m=this.words[0];return this.length===2?m+=this.words[1]*67108864:this.length===3&&this.words[2]===1?m+=4503599627370496+this.words[1]*67108864:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-m:m},a.prototype.toJSON=function(){return this.toString(16)},a.prototype.toBuffer=function(m,c){return i(typeof f<"u"),this.toArrayLike(f,m,c)},a.prototype.toArray=function(m,c){return this.toArrayLike(Array,m,c)},a.prototype.toArrayLike=function(m,c,h){var v=this.byteLength(),_=h||Math.max(1,v);i(v<=_,"byte array longer than desired length"),i(_>0,"Requested array length <= 0"),this.strip();var I=c==="le",M=new m(_),S,d,g=this.clone();if(I){for(d=0;!g.isZero();d++)S=g.andln(255),g.iushrn(8),M[d]=S;for(;d<_;d++)M[d]=0}else{for(d=0;d<_-v;d++)M[d]=0;for(d=0;!g.isZero();d++)S=g.andln(255),g.iushrn(8),M[_-d-1]=S}return M},Math.clz32?a.prototype._countBits=function(m){return 32-Math.clz32(m)}:a.prototype._countBits=function(m){var c=m,h=0;return c>=4096&&(h+=13,c>>>=13),c>=64&&(h+=7,c>>>=7),c>=8&&(h+=4,c>>>=4),c>=2&&(h+=2,c>>>=2),h+c},a.prototype._zeroBits=function(m){if(m===0)return 26;var c=m,h=0;return c&8191||(h+=13,c>>>=13),c&127||(h+=7,c>>>=7),c&15||(h+=4,c>>>=4),c&3||(h+=2,c>>>=2),c&1||h++,h},a.prototype.bitLength=function(){var m=this.words[this.length-1],c=this._countBits(m);return(this.length-1)*26+c};function O(F){for(var m=new Array(F.bitLength()),c=0;c>>v}return m}a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var m=0,c=0;cm.length?this.clone().ior(m):m.clone().ior(this)},a.prototype.uor=function(m){return this.length>m.length?this.clone().iuor(m):m.clone().iuor(this)},a.prototype.iuand=function(m){var c;this.length>m.length?c=m:c=this;for(var h=0;hm.length?this.clone().iand(m):m.clone().iand(this)},a.prototype.uand=function(m){return this.length>m.length?this.clone().iuand(m):m.clone().iuand(this)},a.prototype.iuxor=function(m){var c,h;this.length>m.length?(c=this,h=m):(c=m,h=this);for(var v=0;vm.length?this.clone().ixor(m):m.clone().ixor(this)},a.prototype.uxor=function(m){return this.length>m.length?this.clone().iuxor(m):m.clone().iuxor(this)},a.prototype.inotn=function(m){i(typeof m=="number"&&m>=0);var c=Math.ceil(m/26)|0,h=m%26;this._expand(c),h>0&&c--;for(var v=0;v0&&(this.words[v]=~this.words[v]&67108863>>26-h),this.strip()},a.prototype.notn=function(m){return this.clone().inotn(m)},a.prototype.setn=function(m,c){i(typeof m=="number"&&m>=0);var h=m/26|0,v=m%26;return this._expand(h+1),c?this.words[h]=this.words[h]|1<m.length?(h=this,v=m):(h=m,v=this);for(var _=0,I=0;I>>26;for(;_!==0&&I>>26;if(this.length=h.length,_!==0)this.words[this.length]=_,this.length++;else if(h!==this)for(;Im.length?this.clone().iadd(m):m.clone().iadd(this)},a.prototype.isub=function(m){if(m.negative!==0){m.negative=0;var c=this.iadd(m);return m.negative=1,c._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(m),this.negative=1,this._normSign();var h=this.cmp(m);if(h===0)return this.negative=0,this.length=1,this.words[0]=0,this;var v,_;h>0?(v=this,_=m):(v=m,_=this);for(var I=0,M=0;M<_.length;M++)c=(v.words[M]|0)-(_.words[M]|0)+I,I=c>>26,this.words[M]=c&67108863;for(;I!==0&&M>26,this.words[M]=c&67108863;if(I===0&&M>>26,T=S&67108863,Z=Math.min(d,m.length-1),se=Math.max(0,d-F.length+1);se<=Z;se++){var P=d-se|0;v=F.words[P]|0,_=m.words[se]|0,I=v*_+T,g+=I/67108864|0,T=I&67108863}c.words[d]=T|0,S=g|0}return S!==0?c.words[d]=S|0:c.length--,c.strip()}var K=function(m,c,h){var v=m.words,_=c.words,I=h.words,M=0,S,d,g,T=v[0]|0,Z=T&8191,se=T>>>13,P=v[1]|0,ee=P&8191,q=P>>>13,z=v[2]|0,H=z&8191,w=z>>>13,$=v[3]|0,ne=$&8191,ce=$>>>13,he=v[4]|0,ye=he&8191,we=he>>>13,Ce=v[5]|0,Qe=Ce&8191,Oe=Ce>>>13,Te=v[6]|0,Ie=Te&8191,me=Te>>>13,Re=v[7]|0,De=Re&8191,ve=Re>>>13,Ne=v[8]|0,Se=Ne&8191,be=Ne>>>13,Le=v[9]|0,Me=Le&8191,_e=Le>>>13,He=_[0]|0,Ve=He&8191,Ee=He>>>13,Ke=_[1]|0,ut=Ke&8191,Ge=Ke>>>13,_t=_[2]|0,lt=_t&8191,Je=_t>>>13,Et=_[3]|0,It=Et&8191,Fe=Et>>>13,Xe=_[4]|0,tt=Xe&8191,Be=Xe>>>13,et=_[5]|0,Ze=et&8191,$e=et>>>13,ft=_[6]|0,rt=ft&8191,ze=ft>>>13,it=_[7]|0,st=it&8191,qe=it>>>13,Ye=_[8]|0,ht=Ye&8191,je=Ye>>>13,Tt=_[9]|0,Dt=Tt&8191,at=Tt>>>13;h.negative=m.negative^c.negative,h.length=19,S=Math.imul(Z,Ve),d=Math.imul(Z,Ee),d=d+Math.imul(se,Ve)|0,g=Math.imul(se,Ee);var bt=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(bt>>>26)|0,bt&=67108863,S=Math.imul(ee,Ve),d=Math.imul(ee,Ee),d=d+Math.imul(q,Ve)|0,g=Math.imul(q,Ee),S=S+Math.imul(Z,ut)|0,d=d+Math.imul(Z,Ge)|0,d=d+Math.imul(se,ut)|0,g=g+Math.imul(se,Ge)|0;var Cr=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Cr>>>26)|0,Cr&=67108863,S=Math.imul(H,Ve),d=Math.imul(H,Ee),d=d+Math.imul(w,Ve)|0,g=Math.imul(w,Ee),S=S+Math.imul(ee,ut)|0,d=d+Math.imul(ee,Ge)|0,d=d+Math.imul(q,ut)|0,g=g+Math.imul(q,Ge)|0,S=S+Math.imul(Z,lt)|0,d=d+Math.imul(Z,Je)|0,d=d+Math.imul(se,lt)|0,g=g+Math.imul(se,Je)|0;var Tr=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Tr>>>26)|0,Tr&=67108863,S=Math.imul(ne,Ve),d=Math.imul(ne,Ee),d=d+Math.imul(ce,Ve)|0,g=Math.imul(ce,Ee),S=S+Math.imul(H,ut)|0,d=d+Math.imul(H,Ge)|0,d=d+Math.imul(w,ut)|0,g=g+Math.imul(w,Ge)|0,S=S+Math.imul(ee,lt)|0,d=d+Math.imul(ee,Je)|0,d=d+Math.imul(q,lt)|0,g=g+Math.imul(q,Je)|0,S=S+Math.imul(Z,It)|0,d=d+Math.imul(Z,Fe)|0,d=d+Math.imul(se,It)|0,g=g+Math.imul(se,Fe)|0;var Dr=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Dr>>>26)|0,Dr&=67108863,S=Math.imul(ye,Ve),d=Math.imul(ye,Ee),d=d+Math.imul(we,Ve)|0,g=Math.imul(we,Ee),S=S+Math.imul(ne,ut)|0,d=d+Math.imul(ne,Ge)|0,d=d+Math.imul(ce,ut)|0,g=g+Math.imul(ce,Ge)|0,S=S+Math.imul(H,lt)|0,d=d+Math.imul(H,Je)|0,d=d+Math.imul(w,lt)|0,g=g+Math.imul(w,Je)|0,S=S+Math.imul(ee,It)|0,d=d+Math.imul(ee,Fe)|0,d=d+Math.imul(q,It)|0,g=g+Math.imul(q,Fe)|0,S=S+Math.imul(Z,tt)|0,d=d+Math.imul(Z,Be)|0,d=d+Math.imul(se,tt)|0,g=g+Math.imul(se,Be)|0;var Fr=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Fr>>>26)|0,Fr&=67108863,S=Math.imul(Qe,Ve),d=Math.imul(Qe,Ee),d=d+Math.imul(Oe,Ve)|0,g=Math.imul(Oe,Ee),S=S+Math.imul(ye,ut)|0,d=d+Math.imul(ye,Ge)|0,d=d+Math.imul(we,ut)|0,g=g+Math.imul(we,Ge)|0,S=S+Math.imul(ne,lt)|0,d=d+Math.imul(ne,Je)|0,d=d+Math.imul(ce,lt)|0,g=g+Math.imul(ce,Je)|0,S=S+Math.imul(H,It)|0,d=d+Math.imul(H,Fe)|0,d=d+Math.imul(w,It)|0,g=g+Math.imul(w,Fe)|0,S=S+Math.imul(ee,tt)|0,d=d+Math.imul(ee,Be)|0,d=d+Math.imul(q,tt)|0,g=g+Math.imul(q,Be)|0,S=S+Math.imul(Z,Ze)|0,d=d+Math.imul(Z,$e)|0,d=d+Math.imul(se,Ze)|0,g=g+Math.imul(se,$e)|0;var Br=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Br>>>26)|0,Br&=67108863,S=Math.imul(Ie,Ve),d=Math.imul(Ie,Ee),d=d+Math.imul(me,Ve)|0,g=Math.imul(me,Ee),S=S+Math.imul(Qe,ut)|0,d=d+Math.imul(Qe,Ge)|0,d=d+Math.imul(Oe,ut)|0,g=g+Math.imul(Oe,Ge)|0,S=S+Math.imul(ye,lt)|0,d=d+Math.imul(ye,Je)|0,d=d+Math.imul(we,lt)|0,g=g+Math.imul(we,Je)|0,S=S+Math.imul(ne,It)|0,d=d+Math.imul(ne,Fe)|0,d=d+Math.imul(ce,It)|0,g=g+Math.imul(ce,Fe)|0,S=S+Math.imul(H,tt)|0,d=d+Math.imul(H,Be)|0,d=d+Math.imul(w,tt)|0,g=g+Math.imul(w,Be)|0,S=S+Math.imul(ee,Ze)|0,d=d+Math.imul(ee,$e)|0,d=d+Math.imul(q,Ze)|0,g=g+Math.imul(q,$e)|0,S=S+Math.imul(Z,rt)|0,d=d+Math.imul(Z,ze)|0,d=d+Math.imul(se,rt)|0,g=g+Math.imul(se,ze)|0;var er=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(er>>>26)|0,er&=67108863,S=Math.imul(De,Ve),d=Math.imul(De,Ee),d=d+Math.imul(ve,Ve)|0,g=Math.imul(ve,Ee),S=S+Math.imul(Ie,ut)|0,d=d+Math.imul(Ie,Ge)|0,d=d+Math.imul(me,ut)|0,g=g+Math.imul(me,Ge)|0,S=S+Math.imul(Qe,lt)|0,d=d+Math.imul(Qe,Je)|0,d=d+Math.imul(Oe,lt)|0,g=g+Math.imul(Oe,Je)|0,S=S+Math.imul(ye,It)|0,d=d+Math.imul(ye,Fe)|0,d=d+Math.imul(we,It)|0,g=g+Math.imul(we,Fe)|0,S=S+Math.imul(ne,tt)|0,d=d+Math.imul(ne,Be)|0,d=d+Math.imul(ce,tt)|0,g=g+Math.imul(ce,Be)|0,S=S+Math.imul(H,Ze)|0,d=d+Math.imul(H,$e)|0,d=d+Math.imul(w,Ze)|0,g=g+Math.imul(w,$e)|0,S=S+Math.imul(ee,rt)|0,d=d+Math.imul(ee,ze)|0,d=d+Math.imul(q,rt)|0,g=g+Math.imul(q,ze)|0,S=S+Math.imul(Z,st)|0,d=d+Math.imul(Z,qe)|0,d=d+Math.imul(se,st)|0,g=g+Math.imul(se,qe)|0;var Qr=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Qr>>>26)|0,Qr&=67108863,S=Math.imul(Se,Ve),d=Math.imul(Se,Ee),d=d+Math.imul(be,Ve)|0,g=Math.imul(be,Ee),S=S+Math.imul(De,ut)|0,d=d+Math.imul(De,Ge)|0,d=d+Math.imul(ve,ut)|0,g=g+Math.imul(ve,Ge)|0,S=S+Math.imul(Ie,lt)|0,d=d+Math.imul(Ie,Je)|0,d=d+Math.imul(me,lt)|0,g=g+Math.imul(me,Je)|0,S=S+Math.imul(Qe,It)|0,d=d+Math.imul(Qe,Fe)|0,d=d+Math.imul(Oe,It)|0,g=g+Math.imul(Oe,Fe)|0,S=S+Math.imul(ye,tt)|0,d=d+Math.imul(ye,Be)|0,d=d+Math.imul(we,tt)|0,g=g+Math.imul(we,Be)|0,S=S+Math.imul(ne,Ze)|0,d=d+Math.imul(ne,$e)|0,d=d+Math.imul(ce,Ze)|0,g=g+Math.imul(ce,$e)|0,S=S+Math.imul(H,rt)|0,d=d+Math.imul(H,ze)|0,d=d+Math.imul(w,rt)|0,g=g+Math.imul(w,ze)|0,S=S+Math.imul(ee,st)|0,d=d+Math.imul(ee,qe)|0,d=d+Math.imul(q,st)|0,g=g+Math.imul(q,qe)|0,S=S+Math.imul(Z,ht)|0,d=d+Math.imul(Z,je)|0,d=d+Math.imul(se,ht)|0,g=g+Math.imul(se,je)|0;var Gi=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Gi>>>26)|0,Gi&=67108863,S=Math.imul(Me,Ve),d=Math.imul(Me,Ee),d=d+Math.imul(_e,Ve)|0,g=Math.imul(_e,Ee),S=S+Math.imul(Se,ut)|0,d=d+Math.imul(Se,Ge)|0,d=d+Math.imul(be,ut)|0,g=g+Math.imul(be,Ge)|0,S=S+Math.imul(De,lt)|0,d=d+Math.imul(De,Je)|0,d=d+Math.imul(ve,lt)|0,g=g+Math.imul(ve,Je)|0,S=S+Math.imul(Ie,It)|0,d=d+Math.imul(Ie,Fe)|0,d=d+Math.imul(me,It)|0,g=g+Math.imul(me,Fe)|0,S=S+Math.imul(Qe,tt)|0,d=d+Math.imul(Qe,Be)|0,d=d+Math.imul(Oe,tt)|0,g=g+Math.imul(Oe,Be)|0,S=S+Math.imul(ye,Ze)|0,d=d+Math.imul(ye,$e)|0,d=d+Math.imul(we,Ze)|0,g=g+Math.imul(we,$e)|0,S=S+Math.imul(ne,rt)|0,d=d+Math.imul(ne,ze)|0,d=d+Math.imul(ce,rt)|0,g=g+Math.imul(ce,ze)|0,S=S+Math.imul(H,st)|0,d=d+Math.imul(H,qe)|0,d=d+Math.imul(w,st)|0,g=g+Math.imul(w,qe)|0,S=S+Math.imul(ee,ht)|0,d=d+Math.imul(ee,je)|0,d=d+Math.imul(q,ht)|0,g=g+Math.imul(q,je)|0,S=S+Math.imul(Z,Dt)|0,d=d+Math.imul(Z,at)|0,d=d+Math.imul(se,Dt)|0,g=g+Math.imul(se,at)|0;var Xr=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,S=Math.imul(Me,ut),d=Math.imul(Me,Ge),d=d+Math.imul(_e,ut)|0,g=Math.imul(_e,Ge),S=S+Math.imul(Se,lt)|0,d=d+Math.imul(Se,Je)|0,d=d+Math.imul(be,lt)|0,g=g+Math.imul(be,Je)|0,S=S+Math.imul(De,It)|0,d=d+Math.imul(De,Fe)|0,d=d+Math.imul(ve,It)|0,g=g+Math.imul(ve,Fe)|0,S=S+Math.imul(Ie,tt)|0,d=d+Math.imul(Ie,Be)|0,d=d+Math.imul(me,tt)|0,g=g+Math.imul(me,Be)|0,S=S+Math.imul(Qe,Ze)|0,d=d+Math.imul(Qe,$e)|0,d=d+Math.imul(Oe,Ze)|0,g=g+Math.imul(Oe,$e)|0,S=S+Math.imul(ye,rt)|0,d=d+Math.imul(ye,ze)|0,d=d+Math.imul(we,rt)|0,g=g+Math.imul(we,ze)|0,S=S+Math.imul(ne,st)|0,d=d+Math.imul(ne,qe)|0,d=d+Math.imul(ce,st)|0,g=g+Math.imul(ce,qe)|0,S=S+Math.imul(H,ht)|0,d=d+Math.imul(H,je)|0,d=d+Math.imul(w,ht)|0,g=g+Math.imul(w,je)|0,S=S+Math.imul(ee,Dt)|0,d=d+Math.imul(ee,at)|0,d=d+Math.imul(q,Dt)|0,g=g+Math.imul(q,at)|0;var Wi=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Wi>>>26)|0,Wi&=67108863,S=Math.imul(Me,lt),d=Math.imul(Me,Je),d=d+Math.imul(_e,lt)|0,g=Math.imul(_e,Je),S=S+Math.imul(Se,It)|0,d=d+Math.imul(Se,Fe)|0,d=d+Math.imul(be,It)|0,g=g+Math.imul(be,Fe)|0,S=S+Math.imul(De,tt)|0,d=d+Math.imul(De,Be)|0,d=d+Math.imul(ve,tt)|0,g=g+Math.imul(ve,Be)|0,S=S+Math.imul(Ie,Ze)|0,d=d+Math.imul(Ie,$e)|0,d=d+Math.imul(me,Ze)|0,g=g+Math.imul(me,$e)|0,S=S+Math.imul(Qe,rt)|0,d=d+Math.imul(Qe,ze)|0,d=d+Math.imul(Oe,rt)|0,g=g+Math.imul(Oe,ze)|0,S=S+Math.imul(ye,st)|0,d=d+Math.imul(ye,qe)|0,d=d+Math.imul(we,st)|0,g=g+Math.imul(we,qe)|0,S=S+Math.imul(ne,ht)|0,d=d+Math.imul(ne,je)|0,d=d+Math.imul(ce,ht)|0,g=g+Math.imul(ce,je)|0,S=S+Math.imul(H,Dt)|0,d=d+Math.imul(H,at)|0,d=d+Math.imul(w,Dt)|0,g=g+Math.imul(w,at)|0;var Ji=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Ji>>>26)|0,Ji&=67108863,S=Math.imul(Me,It),d=Math.imul(Me,Fe),d=d+Math.imul(_e,It)|0,g=Math.imul(_e,Fe),S=S+Math.imul(Se,tt)|0,d=d+Math.imul(Se,Be)|0,d=d+Math.imul(be,tt)|0,g=g+Math.imul(be,Be)|0,S=S+Math.imul(De,Ze)|0,d=d+Math.imul(De,$e)|0,d=d+Math.imul(ve,Ze)|0,g=g+Math.imul(ve,$e)|0,S=S+Math.imul(Ie,rt)|0,d=d+Math.imul(Ie,ze)|0,d=d+Math.imul(me,rt)|0,g=g+Math.imul(me,ze)|0,S=S+Math.imul(Qe,st)|0,d=d+Math.imul(Qe,qe)|0,d=d+Math.imul(Oe,st)|0,g=g+Math.imul(Oe,qe)|0,S=S+Math.imul(ye,ht)|0,d=d+Math.imul(ye,je)|0,d=d+Math.imul(we,ht)|0,g=g+Math.imul(we,je)|0,S=S+Math.imul(ne,Dt)|0,d=d+Math.imul(ne,at)|0,d=d+Math.imul(ce,Dt)|0,g=g+Math.imul(ce,at)|0;var Zr=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Zr>>>26)|0,Zr&=67108863,S=Math.imul(Me,tt),d=Math.imul(Me,Be),d=d+Math.imul(_e,tt)|0,g=Math.imul(_e,Be),S=S+Math.imul(Se,Ze)|0,d=d+Math.imul(Se,$e)|0,d=d+Math.imul(be,Ze)|0,g=g+Math.imul(be,$e)|0,S=S+Math.imul(De,rt)|0,d=d+Math.imul(De,ze)|0,d=d+Math.imul(ve,rt)|0,g=g+Math.imul(ve,ze)|0,S=S+Math.imul(Ie,st)|0,d=d+Math.imul(Ie,qe)|0,d=d+Math.imul(me,st)|0,g=g+Math.imul(me,qe)|0,S=S+Math.imul(Qe,ht)|0,d=d+Math.imul(Qe,je)|0,d=d+Math.imul(Oe,ht)|0,g=g+Math.imul(Oe,je)|0,S=S+Math.imul(ye,Dt)|0,d=d+Math.imul(ye,at)|0,d=d+Math.imul(we,Dt)|0,g=g+Math.imul(we,at)|0;var Si=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Si>>>26)|0,Si&=67108863,S=Math.imul(Me,Ze),d=Math.imul(Me,$e),d=d+Math.imul(_e,Ze)|0,g=Math.imul(_e,$e),S=S+Math.imul(Se,rt)|0,d=d+Math.imul(Se,ze)|0,d=d+Math.imul(be,rt)|0,g=g+Math.imul(be,ze)|0,S=S+Math.imul(De,st)|0,d=d+Math.imul(De,qe)|0,d=d+Math.imul(ve,st)|0,g=g+Math.imul(ve,qe)|0,S=S+Math.imul(Ie,ht)|0,d=d+Math.imul(Ie,je)|0,d=d+Math.imul(me,ht)|0,g=g+Math.imul(me,je)|0,S=S+Math.imul(Qe,Dt)|0,d=d+Math.imul(Qe,at)|0,d=d+Math.imul(Oe,Dt)|0,g=g+Math.imul(Oe,at)|0;var Ii=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Ii>>>26)|0,Ii&=67108863,S=Math.imul(Me,rt),d=Math.imul(Me,ze),d=d+Math.imul(_e,rt)|0,g=Math.imul(_e,ze),S=S+Math.imul(Se,st)|0,d=d+Math.imul(Se,qe)|0,d=d+Math.imul(be,st)|0,g=g+Math.imul(be,qe)|0,S=S+Math.imul(De,ht)|0,d=d+Math.imul(De,je)|0,d=d+Math.imul(ve,ht)|0,g=g+Math.imul(ve,je)|0,S=S+Math.imul(Ie,Dt)|0,d=d+Math.imul(Ie,at)|0,d=d+Math.imul(me,Dt)|0,g=g+Math.imul(me,at)|0;var lr=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(lr>>>26)|0,lr&=67108863,S=Math.imul(Me,st),d=Math.imul(Me,qe),d=d+Math.imul(_e,st)|0,g=Math.imul(_e,qe),S=S+Math.imul(Se,ht)|0,d=d+Math.imul(Se,je)|0,d=d+Math.imul(be,ht)|0,g=g+Math.imul(be,je)|0,S=S+Math.imul(De,Dt)|0,d=d+Math.imul(De,at)|0,d=d+Math.imul(ve,Dt)|0,g=g+Math.imul(ve,at)|0;var Yi=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Yi>>>26)|0,Yi&=67108863,S=Math.imul(Me,ht),d=Math.imul(Me,je),d=d+Math.imul(_e,ht)|0,g=Math.imul(_e,je),S=S+Math.imul(Se,Dt)|0,d=d+Math.imul(Se,at)|0,d=d+Math.imul(be,Dt)|0,g=g+Math.imul(be,at)|0;var Qi=(M+S|0)+((d&8191)<<13)|0;M=(g+(d>>>13)|0)+(Qi>>>26)|0,Qi&=67108863,S=Math.imul(Me,Dt),d=Math.imul(Me,at),d=d+Math.imul(_e,Dt)|0,g=Math.imul(_e,at);var Xi=(M+S|0)+((d&8191)<<13)|0;return M=(g+(d>>>13)|0)+(Xi>>>26)|0,Xi&=67108863,I[0]=bt,I[1]=Cr,I[2]=Tr,I[3]=Dr,I[4]=Fr,I[5]=Br,I[6]=er,I[7]=Qr,I[8]=Gi,I[9]=Xr,I[10]=Wi,I[11]=Ji,I[12]=Zr,I[13]=Si,I[14]=Ii,I[15]=lr,I[16]=Yi,I[17]=Qi,I[18]=Xi,M!==0&&(I[19]=M,h.length++),h};Math.imul||(K=N);function W(F,m,c){c.negative=m.negative^F.negative,c.length=F.length+m.length;for(var h=0,v=0,_=0;_>>26)|0,v+=I>>>26,I&=67108863}c.words[_]=M,h=I,I=v}return h!==0?c.words[_]=h:c.length--,c.strip()}function Q(F,m,c){var h=new j;return h.mulp(F,m,c)}a.prototype.mulTo=function(m,c){var h,v=this.length+m.length;return this.length===10&&m.length===10?h=K(this,m,c):v<63?h=N(this,m,c):v<1024?h=W(this,m,c):h=Q(this,m,c),h};function j(F,m){this.x=F,this.y=m}j.prototype.makeRBT=function(m){for(var c=new Array(m),h=a.prototype._countBits(m)-1,v=0;v>=1;return v},j.prototype.permute=function(m,c,h,v,_,I){for(var M=0;M>>1)_++;return 1<<_+1+v},j.prototype.conjugate=function(m,c,h){if(!(h<=1))for(var v=0;v>>13,h[2*I+1]=_&8191,_=_>>>13;for(I=2*c;I>=26,c+=v/67108864|0,c+=_>>>26,this.words[h]=_&67108863}return c!==0&&(this.words[h]=c,this.length++),this},a.prototype.muln=function(m){return this.clone().imuln(m)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(m){var c=O(m);if(c.length===0)return new a(1);for(var h=this,v=0;v=0);var c=m%26,h=(m-c)/26,v=67108863>>>26-c<<26-c,_;if(c!==0){var I=0;for(_=0;_>>26-c}I&&(this.words[_]=I,this.length++)}if(h!==0){for(_=this.length-1;_>=0;_--)this.words[_+h]=this.words[_];for(_=0;_=0);var v;c?v=(c-c%26)/26:v=0;var _=m%26,I=Math.min((m-_)/26,this.length),M=67108863^67108863>>>_<<_,S=h;if(v-=I,v=Math.max(0,v),S){for(var d=0;dI)for(this.length-=I,d=0;d=0&&(g!==0||d>=v);d--){var T=this.words[d]|0;this.words[d]=g<<26-_|T>>>_,g=T&M}return S&&g!==0&&(S.words[S.length++]=g),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},a.prototype.ishrn=function(m,c,h){return i(this.negative===0),this.iushrn(m,c,h)},a.prototype.shln=function(m){return this.clone().ishln(m)},a.prototype.ushln=function(m){return this.clone().iushln(m)},a.prototype.shrn=function(m){return this.clone().ishrn(m)},a.prototype.ushrn=function(m){return this.clone().iushrn(m)},a.prototype.testn=function(m){i(typeof m=="number"&&m>=0);var c=m%26,h=(m-c)/26,v=1<=0);var c=m%26,h=(m-c)/26;if(i(this.negative===0,"imaskn works only with positive numbers"),this.length<=h)return this;if(c!==0&&h++,this.length=Math.min(h,this.length),c!==0){var v=67108863^67108863>>>c<=67108864;c++)this.words[c]-=67108864,c===this.length-1?this.words[c+1]=1:this.words[c+1]++;return this.length=Math.max(this.length,c+1),this},a.prototype.isubn=function(m){if(i(typeof m=="number"),i(m<67108864),m<0)return this.iaddn(-m);if(this.negative!==0)return this.negative=0,this.iaddn(m),this.negative=1,this;if(this.words[0]-=m,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var c=0;c>26)-(S/67108864|0),this.words[_+h]=I&67108863}for(;_>26,this.words[_+h]=I&67108863;if(M===0)return this.strip();for(i(M===-1),M=0,_=0;_>26,this.words[_]=I&67108863;return this.negative=1,this.strip()},a.prototype._wordDiv=function(m,c){var h=this.length-m.length,v=this.clone(),_=m,I=_.words[_.length-1]|0,M=this._countBits(I);h=26-M,h!==0&&(_=_.ushln(h),v.iushln(h),I=_.words[_.length-1]|0);var S=v.length-_.length,d;if(c!=="mod"){d=new a(null),d.length=S+1,d.words=new Array(d.length);for(var g=0;g=0;Z--){var se=(v.words[_.length+Z]|0)*67108864+(v.words[_.length+Z-1]|0);for(se=Math.min(se/I|0,67108863),v._ishlnsubmul(_,se,Z);v.negative!==0;)se--,v.negative=0,v._ishlnsubmul(_,1,Z),v.isZero()||(v.negative^=1);d&&(d.words[Z]=se)}return d&&d.strip(),v.strip(),c!=="div"&&h!==0&&v.iushrn(h),{div:d||null,mod:v}},a.prototype.divmod=function(m,c,h){if(i(!m.isZero()),this.isZero())return{div:new a(0),mod:new a(0)};var v,_,I;return this.negative!==0&&m.negative===0?(I=this.neg().divmod(m,c),c!=="mod"&&(v=I.div.neg()),c!=="div"&&(_=I.mod.neg(),h&&_.negative!==0&&_.iadd(m)),{div:v,mod:_}):this.negative===0&&m.negative!==0?(I=this.divmod(m.neg(),c),c!=="mod"&&(v=I.div.neg()),{div:v,mod:I.mod}):this.negative&m.negative?(I=this.neg().divmod(m.neg(),c),c!=="div"&&(_=I.mod.neg(),h&&_.negative!==0&&_.isub(m)),{div:I.div,mod:_}):m.length>this.length||this.cmp(m)<0?{div:new a(0),mod:this}:m.length===1?c==="div"?{div:this.divn(m.words[0]),mod:null}:c==="mod"?{div:null,mod:new a(this.modn(m.words[0]))}:{div:this.divn(m.words[0]),mod:new a(this.modn(m.words[0]))}:this._wordDiv(m,c)},a.prototype.div=function(m){return this.divmod(m,"div",!1).div},a.prototype.mod=function(m){return this.divmod(m,"mod",!1).mod},a.prototype.umod=function(m){return this.divmod(m,"mod",!0).mod},a.prototype.divRound=function(m){var c=this.divmod(m);if(c.mod.isZero())return c.div;var h=c.div.negative!==0?c.mod.isub(m):c.mod,v=m.ushrn(1),_=m.andln(1),I=h.cmp(v);return I<0||_===1&&I===0?c.div:c.div.negative!==0?c.div.isubn(1):c.div.iaddn(1)},a.prototype.modn=function(m){i(m<=67108863);for(var c=(1<<26)%m,h=0,v=this.length-1;v>=0;v--)h=(c*h+(this.words[v]|0))%m;return h},a.prototype.idivn=function(m){i(m<=67108863);for(var c=0,h=this.length-1;h>=0;h--){var v=(this.words[h]|0)+c*67108864;this.words[h]=v/m|0,c=v%m}return this.strip()},a.prototype.divn=function(m){return this.clone().idivn(m)},a.prototype.egcd=function(m){i(m.negative===0),i(!m.isZero());var c=this,h=m.clone();c.negative!==0?c=c.umod(m):c=c.clone();for(var v=new a(1),_=new a(0),I=new a(0),M=new a(1),S=0;c.isEven()&&h.isEven();)c.iushrn(1),h.iushrn(1),++S;for(var d=h.clone(),g=c.clone();!c.isZero();){for(var T=0,Z=1;!(c.words[0]&Z)&&T<26;++T,Z<<=1);if(T>0)for(c.iushrn(T);T-- >0;)(v.isOdd()||_.isOdd())&&(v.iadd(d),_.isub(g)),v.iushrn(1),_.iushrn(1);for(var se=0,P=1;!(h.words[0]&P)&&se<26;++se,P<<=1);if(se>0)for(h.iushrn(se);se-- >0;)(I.isOdd()||M.isOdd())&&(I.iadd(d),M.isub(g)),I.iushrn(1),M.iushrn(1);c.cmp(h)>=0?(c.isub(h),v.isub(I),_.isub(M)):(h.isub(c),I.isub(v),M.isub(_))}return{a:I,b:M,gcd:h.iushln(S)}},a.prototype._invmp=function(m){i(m.negative===0),i(!m.isZero());var c=this,h=m.clone();c.negative!==0?c=c.umod(m):c=c.clone();for(var v=new a(1),_=new a(0),I=h.clone();c.cmpn(1)>0&&h.cmpn(1)>0;){for(var M=0,S=1;!(c.words[0]&S)&&M<26;++M,S<<=1);if(M>0)for(c.iushrn(M);M-- >0;)v.isOdd()&&v.iadd(I),v.iushrn(1);for(var d=0,g=1;!(h.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(h.iushrn(d);d-- >0;)_.isOdd()&&_.iadd(I),_.iushrn(1);c.cmp(h)>=0?(c.isub(h),v.isub(_)):(h.isub(c),_.isub(v))}var T;return c.cmpn(1)===0?T=v:T=_,T.cmpn(0)<0&&T.iadd(m),T},a.prototype.gcd=function(m){if(this.isZero())return m.abs();if(m.isZero())return this.abs();var c=this.clone(),h=m.clone();c.negative=0,h.negative=0;for(var v=0;c.isEven()&&h.isEven();v++)c.iushrn(1),h.iushrn(1);do{for(;c.isEven();)c.iushrn(1);for(;h.isEven();)h.iushrn(1);var _=c.cmp(h);if(_<0){var I=c;c=h,h=I}else if(_===0||h.cmpn(1)===0)break;c.isub(h)}while(!0);return h.iushln(v)},a.prototype.invm=function(m){return this.egcd(m).a.umod(m)},a.prototype.isEven=function(){return(this.words[0]&1)===0},a.prototype.isOdd=function(){return(this.words[0]&1)===1},a.prototype.andln=function(m){return this.words[0]&m},a.prototype.bincn=function(m){i(typeof m=="number");var c=m%26,h=(m-c)/26,v=1<>>26,M&=67108863,this.words[I]=M}return _!==0&&(this.words[I]=_,this.length++),this},a.prototype.isZero=function(){return this.length===1&&this.words[0]===0},a.prototype.cmpn=function(m){var c=m<0;if(this.negative!==0&&!c)return-1;if(this.negative===0&&c)return 1;this.strip();var h;if(this.length>1)h=1;else{c&&(m=-m),i(m<=67108863,"Number is too big");var v=this.words[0]|0;h=v===m?0:vm.length)return 1;if(this.length=0;h--){var v=this.words[h]|0,_=m.words[h]|0;if(v!==_){v<_?c=-1:v>_&&(c=1);break}}return c},a.prototype.gtn=function(m){return this.cmpn(m)===1},a.prototype.gt=function(m){return this.cmp(m)===1},a.prototype.gten=function(m){return this.cmpn(m)>=0},a.prototype.gte=function(m){return this.cmp(m)>=0},a.prototype.ltn=function(m){return this.cmpn(m)===-1},a.prototype.lt=function(m){return this.cmp(m)===-1},a.prototype.lten=function(m){return this.cmpn(m)<=0},a.prototype.lte=function(m){return this.cmp(m)<=0},a.prototype.eqn=function(m){return this.cmpn(m)===0},a.prototype.eq=function(m){return this.cmp(m)===0},a.red=function(m){return new ae(m)},a.prototype.toRed=function(m){return i(!this.red,"Already a number in reduction context"),i(this.negative===0,"red works only with positives"),m.convertTo(this)._forceRed(m)},a.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(m){return this.red=m,this},a.prototype.forceRed=function(m){return i(!this.red,"Already a number in reduction context"),this._forceRed(m)},a.prototype.redAdd=function(m){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,m)},a.prototype.redIAdd=function(m){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,m)},a.prototype.redSub=function(m){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,m)},a.prototype.redISub=function(m){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,m)},a.prototype.redShl=function(m){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,m)},a.prototype.redMul=function(m){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,m),this.red.mul(this,m)},a.prototype.redIMul=function(m){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,m),this.red.imul(this,m)},a.prototype.redSqr=function(){return i(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return i(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return i(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return i(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return i(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(m){return i(this.red&&!m.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,m)};var Y={k256:null,p224:null,p192:null,p25519:null};function U(F,m){this.name=F,this.p=new a(m,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}U.prototype._tmp=function(){var m=new a(null);return m.words=new Array(Math.ceil(this.n/13)),m},U.prototype.ireduce=function(m){var c=m,h;do this.split(c,this.tmp),c=this.imulK(c),c=c.iadd(this.tmp),h=c.bitLength();while(h>this.n);var v=h0?c.isub(this.p):c.strip!==void 0?c.strip():c._strip(),c},U.prototype.split=function(m,c){m.iushrn(this.n,0,c)},U.prototype.imulK=function(m){return m.imul(this.k)};function k(){U.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(k,U),k.prototype.split=function(m,c){for(var h=4194303,v=Math.min(m.length,9),_=0;_>>22,I=M}I>>>=22,m.words[_-10]=I,I===0&&m.length>10?m.length-=10:m.length-=9},k.prototype.imulK=function(m){m.words[m.length]=0,m.words[m.length+1]=0,m.length+=2;for(var c=0,h=0;h>>=26,m.words[h]=_,c=v}return c!==0&&(m.words[m.length++]=c),m},a._prime=function(m){if(Y[m])return Y[m];var c;if(m==="k256")c=new k;else if(m==="p224")c=new G;else if(m==="p192")c=new x;else if(m==="p25519")c=new B;else throw new Error("Unknown prime "+m);return Y[m]=c,c};function ae(F){if(typeof F=="string"){var m=a._prime(F);this.m=m.p,this.prime=m}else i(F.gtn(1),"modulus must be greater than 1"),this.m=F,this.prime=null}ae.prototype._verify1=function(m){i(m.negative===0,"red works only with positives"),i(m.red,"red works only with red numbers")},ae.prototype._verify2=function(m,c){i((m.negative|c.negative)===0,"red works only with positives"),i(m.red&&m.red===c.red,"red works only with red numbers")},ae.prototype.imod=function(m){return this.prime?this.prime.ireduce(m)._forceRed(this):m.umod(this.m)._forceRed(this)},ae.prototype.neg=function(m){return m.isZero()?m.clone():this.m.sub(m)._forceRed(this)},ae.prototype.add=function(m,c){this._verify2(m,c);var h=m.add(c);return h.cmp(this.m)>=0&&h.isub(this.m),h._forceRed(this)},ae.prototype.iadd=function(m,c){this._verify2(m,c);var h=m.iadd(c);return h.cmp(this.m)>=0&&h.isub(this.m),h},ae.prototype.sub=function(m,c){this._verify2(m,c);var h=m.sub(c);return h.cmpn(0)<0&&h.iadd(this.m),h._forceRed(this)},ae.prototype.isub=function(m,c){this._verify2(m,c);var h=m.isub(c);return h.cmpn(0)<0&&h.iadd(this.m),h},ae.prototype.shl=function(m,c){return this._verify1(m),this.imod(m.ushln(c))},ae.prototype.imul=function(m,c){return this._verify2(m,c),this.imod(m.imul(c))},ae.prototype.mul=function(m,c){return this._verify2(m,c),this.imod(m.mul(c))},ae.prototype.isqr=function(m){return this.imul(m,m.clone())},ae.prototype.sqr=function(m){return this.mul(m,m)},ae.prototype.sqrt=function(m){if(m.isZero())return m.clone();var c=this.m.andln(3);if(i(c%2===1),c===3){var h=this.m.add(new a(1)).iushrn(2);return this.pow(m,h)}for(var v=this.m.subn(1),_=0;!v.isZero()&&v.andln(1)===0;)_++,v.iushrn(1);i(!v.isZero());var I=new a(1).toRed(this),M=I.redNeg(),S=this.m.subn(1).iushrn(1),d=this.m.bitLength();for(d=new a(2*d*d).toRed(this);this.pow(d,S).cmp(M)!==0;)d.redIAdd(M);for(var g=this.pow(d,v),T=this.pow(m,v.addn(1).iushrn(1)),Z=this.pow(m,v),se=_;Z.cmp(I)!==0;){for(var P=Z,ee=0;P.cmp(I)!==0;ee++)P=P.redSqr();i(ee=0;_--){for(var g=c.words[_],T=d-1;T>=0;T--){var Z=g>>T&1;if(I!==v[0]&&(I=this.sqr(I)),Z===0&&M===0){S=0;continue}M<<=1,M|=Z,S++,!(S!==h&&(_!==0||T!==0))&&(I=this.mul(I,v[M]),S=0,M=0)}d=26}return I},ae.prototype.convertTo=function(m){var c=m.umod(this.m);return c===m?c.clone():c},ae.prototype.convertFrom=function(m){var c=m.clone();return c.red=null,c},a.mont=function(m){return new le(m)};function le(F){ae.call(this,F),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new a(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)}n(le,ae),le.prototype.convertTo=function(m){return this.imod(m.ushln(this.shift))},le.prototype.convertFrom=function(m){var c=this.imod(m.mul(this.rinv));return c.red=null,c},le.prototype.imul=function(m,c){if(m.isZero()||c.isZero())return m.words[0]=0,m.length=1,m;var h=m.imul(c),v=h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),_=h.isub(v).iushrn(this.shift),I=_;return _.cmp(this.m)>=0?I=_.isub(this.m):_.cmpn(0)<0&&(I=_.iadd(this.m)),I._forceRed(this)},le.prototype.mul=function(m,c){if(m.isZero()||c.isZero())return new a(0)._forceRed(this);var h=m.mul(c),v=h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),_=h.isub(v).iushrn(this.shift),I=_;return _.cmp(this.m)>=0?I=_.isub(this.m):_.cmpn(0)<0&&(I=_.iadd(this.m)),I._forceRed(this)},le.prototype.invm=function(m){var c=this.imod(m._invmp(this.m).mul(this.r2));return c._forceRed(this)}})(r,ji)})(T0);var bs=T0.exports,ya=Qv;function Qv(r,e){if(!r)throw new Error(e||"Assertion failed")}Qv.equal=function(e,t,i){if(e!=t)throw new Error(i||"Assertion failed: "+e+" != "+t)};var D0={};(function(r){var e=r;function t(a,f){if(Array.isArray(a))return a.slice();if(!a)return[];var u=[];if(typeof a!="string"){for(var b=0;b>8,A=p&255;y?u.push(y,A):u.push(A)}return u}e.toArray=t;function i(a){return a.length===1?"0"+a:a}e.zero2=i;function n(a){for(var f="",u=0;u(K>>1)-1?Q=(K>>1)-j:Q=j,W.isubn(Q)):Q=0,O[N]=Q,W.iushrn(1)}return O}e.getNAF=a;function f(y,A){var R=[[],[]];y=y.clone(),A=A.clone();for(var O=0,N=0,K;y.cmpn(-O)>0||A.cmpn(-N)>0;){var W=y.andln(3)+O&3,Q=A.andln(3)+N&3;W===3&&(W=-1),Q===3&&(Q=-1);var j;W&1?(K=y.andln(7)+O&7,(K===3||K===5)&&Q===2?j=-W:j=W):j=0,R[0].push(j);var Y;Q&1?(K=A.andln(7)+N&7,(K===3||K===5)&&W===2?Y=-Q:Y=Q):Y=0,R[1].push(Y),2*O===j+1&&(O=1-O),2*N===Y+1&&(N=1-N),y.iushrn(1),A.iushrn(1)}return R}e.getJSF=f;function u(y,A,R){var O="_"+A;y.prototype[A]=function(){return this[O]!==void 0?this[O]:this[O]=R.call(this)}}e.cachedProperty=u;function b(y){return typeof y=="string"?e.toArray(y,"hex"):y}e.parseBytes=b;function p(y){return new t(y,"hex","le")}e.intFromLE=p})(xi);var F0={exports:{}},fl;F0.exports=function(e){return fl||(fl=new Fs(null)),fl.generate(e)};function Fs(r){this.rand=r}F0.exports.Rand=Fs;Fs.prototype.generate=function(e){return this._rand(e)};Fs.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),i=0;i0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Nh=zs;zs.prototype.point=function(){throw new Error("Not implemented")};zs.prototype.validate=function(){throw new Error("Not implemented")};zs.prototype._fixedNafMul=function(e,t){fh(e.precomputed);var i=e._getDoubles(),n=ch(t,1,this._bitLength),a=(1<=u;p--)b=(b<<1)+n[p];f.push(b)}for(var y=this.jpoint(null,null,null),A=this.jpoint(null,null,null),R=a;R>0;R--){for(u=0;u=0;b--){for(var p=0;b>=0&&f[b]===0;b--)p++;if(b>=0&&p++,u=u.dblp(p),b<0)break;var y=f[b];fh(y!==0),e.type==="affine"?y>0?u=u.mixedAdd(a[y-1>>1]):u=u.mixedAdd(a[-y-1>>1].neg()):y>0?u=u.add(a[y-1>>1]):u=u.add(a[-y-1>>1].neg())}return e.type==="affine"?u.toP():u};zs.prototype._wnafMulAdd=function(e,t,i,n,a){var f=this._wnafT1,u=this._wnafT2,b=this._wnafT3,p=0,y,A,R;for(y=0;y=1;y-=2){var N=y-1,K=y;if(f[N]!==1||f[K]!==1){b[N]=ch(i[N],f[N],this._bitLength),b[K]=ch(i[K],f[K],this._bitLength),p=Math.max(b[N].length,p),p=Math.max(b[K].length,p);continue}var W=[t[N],null,null,t[K]];t[N].y.cmp(t[K].y)===0?(W[1]=t[N].add(t[K]),W[2]=t[N].toJ().mixedAdd(t[K].neg())):t[N].y.cmp(t[K].y.redNeg())===0?(W[1]=t[N].toJ().mixedAdd(t[K]),W[2]=t[N].add(t[K].neg())):(W[1]=t[N].toJ().mixedAdd(t[K]),W[2]=t[N].toJ().mixedAdd(t[K].neg()));var Q=[-3,-1,-5,-7,0,7,5,1,3],j=B_(i[N],i[K]);for(p=Math.max(j[0].length,p),b[N]=new Array(p),b[K]=new Array(p),A=0;A=0;y--){for(var x=0;y>=0;){var B=!0;for(A=0;A=0&&x++,k=k.dblp(x),y<0)break;for(A=0;A0?R=u[A][ae-1>>1]:ae<0&&(R=u[A][-ae-1>>1].neg()),R.type==="affine"?k=k.mixedAdd(R):k=k.add(R))}}for(y=0;y=Math.ceil((e.bitLength()+1)/t.step):!1};Ki.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var i=[this],n=this,a=0;a=0&&(O=p,N=y),A.negative&&(A=A.neg(),R=R.neg()),O.negative&&(O=O.neg(),N=N.neg()),[{a:A,b:R},{a:O,b:N}]};Vi.prototype._endoSplit=function(e){var t=this.endo.basis,i=t[0],n=t[1],a=n.b.mul(e).divRound(this.n),f=i.b.neg().mul(e).divRound(this.n),u=a.mul(i.a),b=f.mul(n.a),p=a.mul(i.b),y=f.mul(n.b),A=e.sub(u).sub(b),R=p.add(y).neg();return{k1:A,k2:R}};Vi.prototype.pointFromX=function(e,t){e=new nr(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=i.redSqrt();if(n.redSqr().redSub(i).cmp(this.zero)!==0)throw new Error("invalid point");var a=n.fromRed().isOdd();return(t&&!a||!t&&a)&&(n=n.redNeg()),this.point(e,n)};Vi.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,i=e.y,n=this.a.redMul(t),a=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return i.redSqr().redISub(a).cmpn(0)===0};Vi.prototype._endoWnafMulAdd=function(e,t,i){for(var n=this._endoWnafT1,a=this._endoWnafT2,f=0;f":""};Ir.prototype.isInfinity=function(){return this.inf};Ir.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(this.x.cmp(e.x)===0)return this.curve.point(null,null);var t=this.y.redSub(e.y);t.cmpn(0)!==0&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var i=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(i)).redISub(this.y);return this.curve.point(i,n)};Ir.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(e.cmpn(0)===0)return this.curve.point(null,null);var t=this.curve.a,i=this.x.redSqr(),n=e.redInvm(),a=i.redAdd(i).redIAdd(i).redIAdd(t).redMul(n),f=a.redSqr().redISub(this.x.redAdd(this.x)),u=a.redMul(this.x.redSub(f)).redISub(this.y);return this.curve.point(f,u)};Ir.prototype.getX=function(){return this.x.fromRed()};Ir.prototype.getY=function(){return this.y.fromRed()};Ir.prototype.mul=function(e){return e=new nr(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)};Ir.prototype.mulAdd=function(e,t,i){var n=[this,t],a=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,a):this.curve._wnafMulAdd(1,n,a,2)};Ir.prototype.jmulAdd=function(e,t,i){var n=[this,t],a=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,a,!0):this.curve._wnafMulAdd(1,n,a,2,!0)};Ir.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||this.x.cmp(e.x)===0&&this.y.cmp(e.y)===0)};Ir.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var i=this.precomputed,n=function(a){return a.neg()};t.precomputed={naf:i.naf&&{wnd:i.naf.wnd,points:i.naf.points.map(n)},doubles:i.doubles&&{step:i.doubles.step,points:i.doubles.points.map(n)}}}return t};Ir.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var e=this.curve.jpoint(this.x,this.y,this.curve.one);return e};function Rr(r,e,t,i){fo.BasePoint.call(this,r,"jacobian"),e===null&&t===null&&i===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new nr(0)):(this.x=new nr(e,16),this.y=new nr(t,16),this.z=new nr(i,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}q0(Rr,fo.BasePoint);Vi.prototype.jpoint=function(e,t,i){return new Rr(this,e,t,i)};Rr.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),i=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(i,n)};Rr.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)};Rr.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),i=this.z.redSqr(),n=this.x.redMul(t),a=e.x.redMul(i),f=this.y.redMul(t.redMul(e.z)),u=e.y.redMul(i.redMul(this.z)),b=n.redSub(a),p=f.redSub(u);if(b.cmpn(0)===0)return p.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var y=b.redSqr(),A=y.redMul(b),R=n.redMul(y),O=p.redSqr().redIAdd(A).redISub(R).redISub(R),N=p.redMul(R.redISub(O)).redISub(f.redMul(A)),K=this.z.redMul(e.z).redMul(b);return this.curve.jpoint(O,N,K)};Rr.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),i=this.x,n=e.x.redMul(t),a=this.y,f=e.y.redMul(t).redMul(this.z),u=i.redSub(n),b=a.redSub(f);if(u.cmpn(0)===0)return b.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var p=u.redSqr(),y=p.redMul(u),A=i.redMul(p),R=b.redSqr().redIAdd(y).redISub(A).redISub(A),O=b.redMul(A.redISub(R)).redISub(a.redMul(y)),N=this.z.redMul(u);return this.curve.jpoint(R,O,N)};Rr.prototype.dblp=function(e){if(e===0)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var i=this;for(t=0;t=0)return!1;if(i.redIAdd(a),this.x.cmp(i)===0)return!0}};Rr.prototype.inspect=function(){return this.isInfinity()?"":""};Rr.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var Xa=bs,Zv=xh,Ch=Nh,$_=xi;function ho(r){Ch.call(this,"mont",r),this.a=new Xa(r.a,16).toRed(this.red),this.b=new Xa(r.b,16).toRed(this.red),this.i4=new Xa(4).toRed(this.red).redInvm(),this.two=new Xa(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}Zv(ho,Ch);var z_=ho;ho.prototype.validate=function(e){var t=e.normalize().x,i=t.redSqr(),n=i.redMul(t).redAdd(i.redMul(this.a)).redAdd(t),a=n.redSqrt();return a.redSqr().cmp(n)===0};function Sr(r,e,t){Ch.BasePoint.call(this,r,"projective"),e===null&&t===null?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new Xa(e,16),this.z=new Xa(t,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}Zv(Sr,Ch.BasePoint);ho.prototype.decodePoint=function(e,t){return this.point($_.toArray(e,t),1)};ho.prototype.point=function(e,t){return new Sr(this,e,t)};ho.prototype.pointFromJSON=function(e){return Sr.fromJSON(this,e)};Sr.prototype.precompute=function(){};Sr.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())};Sr.fromJSON=function(e,t){return new Sr(e,t[0],t[1]||e.one)};Sr.prototype.inspect=function(){return this.isInfinity()?"":""};Sr.prototype.isInfinity=function(){return this.z.cmpn(0)===0};Sr.prototype.dbl=function(){var e=this.x.redAdd(this.z),t=e.redSqr(),i=this.x.redSub(this.z),n=i.redSqr(),a=t.redSub(n),f=t.redMul(n),u=a.redMul(n.redAdd(this.curve.a24.redMul(a)));return this.curve.point(f,u)};Sr.prototype.add=function(){throw new Error("Not supported on Montgomery curve")};Sr.prototype.diffAdd=function(e,t){var i=this.x.redAdd(this.z),n=this.x.redSub(this.z),a=e.x.redAdd(e.z),f=e.x.redSub(e.z),u=f.redMul(i),b=a.redMul(n),p=t.z.redMul(u.redAdd(b).redSqr()),y=t.x.redMul(u.redISub(b).redSqr());return this.curve.point(p,y)};Sr.prototype.mul=function(e){for(var t=e.clone(),i=this,n=this.curve.point(null,null),a=this,f=[];t.cmpn(0)!==0;t.iushrn(1))f.push(t.andln(1));for(var u=f.length-1;u>=0;u--)f[u]===0?(i=i.diffAdd(n,a),n=n.dbl()):(n=i.diffAdd(n,a),i=i.dbl());return n};Sr.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")};Sr.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")};Sr.prototype.eq=function(e){return this.getX().cmp(e.getX())===0};Sr.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this};Sr.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var j_=xi,ls=bs,eb=xh,Th=Nh,k_=j_.assert;function Hn(r){this.twisted=(r.a|0)!==1,this.mOneA=this.twisted&&(r.a|0)===-1,this.extended=this.mOneA,Th.call(this,"edwards",r),this.a=new ls(r.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new ls(r.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new ls(r.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),k_(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(r.c|0)===1}eb(Hn,Th);var H_=Hn;Hn.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)};Hn.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)};Hn.prototype.jpoint=function(e,t,i,n){return this.point(e,t,i,n)};Hn.prototype.pointFromX=function(e,t){e=new ls(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr(),n=this.c2.redSub(this.a.redMul(i)),a=this.one.redSub(this.c2.redMul(this.d).redMul(i)),f=n.redMul(a.redInvm()),u=f.redSqrt();if(u.redSqr().redSub(f).cmp(this.zero)!==0)throw new Error("invalid point");var b=u.fromRed().isOdd();return(t&&!b||!t&&b)&&(u=u.redNeg()),this.point(e,u)};Hn.prototype.pointFromY=function(e,t){e=new ls(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr(),n=i.redSub(this.c2),a=i.redMul(this.d).redMul(this.c2).redSub(this.a),f=n.redMul(a.redInvm());if(f.cmp(this.zero)===0){if(t)throw new Error("invalid point");return this.point(this.zero,e)}var u=f.redSqrt();if(u.redSqr().redSub(f).cmp(this.zero)!==0)throw new Error("invalid point");return u.fromRed().isOdd()!==t&&(u=u.redNeg()),this.point(u,e)};Hn.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),i=e.y.redSqr(),n=t.redMul(this.a).redAdd(i),a=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(i)));return n.cmp(a)===0};function Wt(r,e,t,i,n){Th.BasePoint.call(this,r,"projective"),e===null&&t===null&&i===null?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new ls(e,16),this.y=new ls(t,16),this.z=i?new ls(i,16):this.curve.one,this.t=n&&new ls(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}eb(Wt,Th.BasePoint);Hn.prototype.pointFromJSON=function(e){return Wt.fromJSON(this,e)};Hn.prototype.point=function(e,t,i,n){return new Wt(this,e,t,i,n)};Wt.fromJSON=function(e,t){return new Wt(e,t[0],t[1],t[2])};Wt.prototype.inspect=function(){return this.isInfinity()?"":""};Wt.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)};Wt.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),i=this.z.redSqr();i=i.redIAdd(i);var n=this.curve._mulA(e),a=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),f=n.redAdd(t),u=f.redSub(i),b=n.redSub(t),p=a.redMul(u),y=f.redMul(b),A=a.redMul(b),R=u.redMul(f);return this.curve.point(p,y,R,A)};Wt.prototype._projDbl=function(){var e=this.x.redAdd(this.y).redSqr(),t=this.x.redSqr(),i=this.y.redSqr(),n,a,f,u,b,p;if(this.curve.twisted){u=this.curve._mulA(t);var y=u.redAdd(i);this.zOne?(n=e.redSub(t).redSub(i).redMul(y.redSub(this.curve.two)),a=y.redMul(u.redSub(i)),f=y.redSqr().redSub(y).redSub(y)):(b=this.z.redSqr(),p=y.redSub(b).redISub(b),n=e.redSub(t).redISub(i).redMul(p),a=y.redMul(u.redSub(i)),f=y.redMul(p))}else u=t.redAdd(i),b=this.curve._mulC(this.z).redSqr(),p=u.redSub(b).redSub(b),n=this.curve._mulC(e.redISub(u)).redMul(p),a=this.curve._mulC(u).redMul(t.redISub(i)),f=u.redMul(p);return this.curve.point(n,a,f)};Wt.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()};Wt.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),i=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),a=this.z.redMul(e.z.redAdd(e.z)),f=i.redSub(t),u=a.redSub(n),b=a.redAdd(n),p=i.redAdd(t),y=f.redMul(u),A=b.redMul(p),R=f.redMul(p),O=u.redMul(b);return this.curve.point(y,A,O,R)};Wt.prototype._projAdd=function(e){var t=this.z.redMul(e.z),i=t.redSqr(),n=this.x.redMul(e.x),a=this.y.redMul(e.y),f=this.curve.d.redMul(n).redMul(a),u=i.redSub(f),b=i.redAdd(f),p=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(n).redISub(a),y=t.redMul(u).redMul(p),A,R;return this.curve.twisted?(A=t.redMul(b).redMul(a.redSub(this.curve._mulA(n))),R=u.redMul(b)):(A=t.redMul(b).redMul(a.redSub(n)),R=this.curve._mulC(u).redMul(b)),this.curve.point(y,A,R)};Wt.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)};Wt.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)};Wt.prototype.mulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!1)};Wt.prototype.jmulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!0)};Wt.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this};Wt.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())};Wt.prototype.getX=function(){return this.normalize(),this.x.fromRed()};Wt.prototype.getY=function(){return this.normalize(),this.y.fromRed()};Wt.prototype.eq=function(e){return this===e||this.getX().cmp(e.getX())===0&&this.getY().cmp(e.getY())===0};Wt.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(t)===0)return!0;for(var i=e.clone(),n=this.curve.redN.redMul(this.z);;){if(i.iadd(this.curve.n),i.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),this.x.cmp(t)===0)return!0}};Wt.prototype.toP=Wt.prototype.normalize;Wt.prototype.mixedAdd=Wt.prototype.add;(function(r){var e=r;e.base=Nh,e.short=U_,e.mont=z_,e.edwards=H_})(B0);var Dh={},Fh={},Ot={},K_=ya,V_=xh;Ot.inherits=V_;function G_(r,e){return(r.charCodeAt(e)&64512)!==55296||e<0||e+1>=r.length?!1:(r.charCodeAt(e+1)&64512)===56320}function W_(r,e){if(Array.isArray(r))return r.slice();if(!r)return[];var t=[];if(typeof r=="string")if(e){if(e==="hex")for(r=r.replace(/[^a-z0-9]+/ig,""),r.length%2!==0&&(r="0"+r),n=0;n>6|192,t[i++]=a&63|128):G_(r,n)?(a=65536+((a&1023)<<10)+(r.charCodeAt(++n)&1023),t[i++]=a>>18|240,t[i++]=a>>12&63|128,t[i++]=a>>6&63|128,t[i++]=a&63|128):(t[i++]=a>>12|224,t[i++]=a>>6&63|128,t[i++]=a&63|128)}else for(n=0;n>>24|r>>>8&65280|r<<8&16711680|(r&255)<<24;return e>>>0}Ot.htonl=tb;function Y_(r,e){for(var t="",i=0;i>>0}return a}Ot.join32=Q_;function X_(r,e){for(var t=new Array(r.length*4),i=0,n=0;i>>24,t[n+1]=a>>>16&255,t[n+2]=a>>>8&255,t[n+3]=a&255):(t[n+3]=a>>>24,t[n+2]=a>>>16&255,t[n+1]=a>>>8&255,t[n]=a&255)}return t}Ot.split32=X_;function Z_(r,e){return r>>>e|r<<32-e}Ot.rotr32=Z_;function e7(r,e){return r<>>32-e}Ot.rotl32=e7;function t7(r,e){return r+e>>>0}Ot.sum32=t7;function r7(r,e,t){return r+e+t>>>0}Ot.sum32_3=r7;function i7(r,e,t,i){return r+e+t+i>>>0}Ot.sum32_4=i7;function n7(r,e,t,i,n){return r+e+t+i+n>>>0}Ot.sum32_5=n7;function s7(r,e,t,i){var n=r[e],a=r[e+1],f=i+a>>>0,u=(f>>0,r[e+1]=f}Ot.sum64=s7;function a7(r,e,t,i){var n=e+i>>>0,a=(n>>0}Ot.sum64_hi=a7;function o7(r,e,t,i){var n=e+i;return n>>>0}Ot.sum64_lo=o7;function c7(r,e,t,i,n,a,f,u){var b=0,p=e;p=p+i>>>0,b+=p>>0,b+=p>>0,b+=p>>0}Ot.sum64_4_hi=c7;function f7(r,e,t,i,n,a,f,u){var b=e+i+a+u;return b>>>0}Ot.sum64_4_lo=f7;function h7(r,e,t,i,n,a,f,u,b,p){var y=0,A=e;A=A+i>>>0,y+=A>>0,y+=A>>0,y+=A>>0,y+=A>>0}Ot.sum64_5_hi=h7;function u7(r,e,t,i,n,a,f,u,b,p){var y=e+i+a+u+p;return y>>>0}Ot.sum64_5_lo=u7;function l7(r,e,t){var i=e<<32-t|r>>>t;return i>>>0}Ot.rotr64_hi=l7;function d7(r,e,t){var i=r<<32-t|e>>>t;return i>>>0}Ot.rotr64_lo=d7;function p7(r,e,t){return r>>>t}Ot.shr64_hi=p7;function g7(r,e,t){var i=r<<32-t|e>>>t;return i>>>0}Ot.shr64_lo=g7;var uo={},_1=Ot,v7=ya;function Bh(){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}uo.BlockHash=Bh;Bh.prototype.update=function(e,t){if(e=_1.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){e=this.pending;var i=e.length%this._delta8;this.pending=e.slice(e.length-i,e.length),this.pending.length===0&&(this.pending=null),e=_1.join32(e,0,e.length-i,this.endian);for(var n=0;n>>24&255,n[a++]=e>>>16&255,n[a++]=e>>>8&255,n[a++]=e&255}else for(n[a++]=e&255,n[a++]=e>>>8&255,n[a++]=e>>>16&255,n[a++]=e>>>24&255,n[a++]=0,n[a++]=0,n[a++]=0,n[a++]=0,f=8;f>>3}Kn.g0_256=_7;function A7(r){return Nn(r,17)^Nn(r,19)^r>>>10}Kn.g1_256=A7;var ro=Ot,E7=uo,x7=Kn,hl=ro.rotl32,Ko=ro.sum32,S7=ro.sum32_5,I7=x7.ft_1,ob=E7.BlockHash,M7=[1518500249,1859775393,2400959708,3395469782];function Un(){if(!(this instanceof Un))return new Un;ob.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}ro.inherits(Un,ob);var P7=Un;Un.blockSize=512;Un.outSize=160;Un.hmacStrength=80;Un.padLength=64;Un.prototype._update=function(e,t){for(var i=this.W,n=0;n<16;n++)i[n]=e[t+n];for(;nthis.blockSize&&(e=new this.Hash().update(e).digest()),g9(e.length<=this.blockSize);for(var t=e.length;t=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,t,i)}var y9=Ls;Ls.prototype._init=function(e,t,i){var n=e.concat(t).concat(i);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var a=0;a=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(i||[])),this._reseed=1};Ls.prototype.generate=function(e,t,i,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof t!="string"&&(n=i,i=t,t=null),i&&(i=ua.toArray(i,n||"hex"),this._update(i));for(var a=[];a.length"};var hh=bs,L0=xi,E9=L0.assert;function qh(r,e){if(r instanceof qh)return r;this._importDER(r,e)||(E9(r.r&&r.s,"Signature without r or s"),this.r=new hh(r.r,16),this.s=new hh(r.s,16),r.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=r.recoveryParam)}var x9=qh;function S9(){this.place=0}function pl(r,e){var t=r[e.place++];if(!(t&128))return t;var i=t&15;if(i===0||i>4||r[e.place]===0)return!1;for(var n=0,a=0,f=e.place;a>>=0;return n<=127?!1:(e.place=f,n)}function I1(r){for(var e=0,t=r.length-1;!r[e]&&!(r[e+1]&128)&&e>>3);for(r.push(t|128);--t;)r.push(e>>>(t<<3)&255);r.push(e)}qh.prototype.toDER=function(e){var t=this.r.toArray(),i=this.s.toArray();for(t[0]&128&&(t=[0].concat(t)),i[0]&128&&(i=[0].concat(i)),t=I1(t),i=I1(i);!i[0]&&!(i[1]&128);)i=i.slice(1);var n=[2];gl(n,t.length),n=n.concat(t),n.push(2),gl(n,i.length);var a=n.concat(i),f=[48];return gl(f,a.length),f=f.concat(a),L0.encode(f,e)};var la=bs,yb=y9,I9=xi,vl=Dh,M9=Xv,wb=I9.assert,U0=A9,Lh=x9;function ki(r){if(!(this instanceof ki))return new ki(r);typeof r=="string"&&(wb(Object.prototype.hasOwnProperty.call(vl,r),"Unknown curve "+r),r=vl[r]),r instanceof vl.PresetCurve&&(r={curve:r}),this.curve=r.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=r.curve.g,this.g.precompute(r.curve.n.bitLength()+1),this.hash=r.hash||r.curve.hash}var P9=ki;ki.prototype.keyPair=function(e){return new U0(this,e)};ki.prototype.keyFromPrivate=function(e,t){return U0.fromPrivate(this,e,t)};ki.prototype.keyFromPublic=function(e,t){return U0.fromPublic(this,e,t)};ki.prototype.genKeyPair=function(e){e||(e={});for(var t=new yb({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||M9(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),i=this.n.byteLength(),n=this.n.sub(new la(2));;){var a=new la(t.generate(i));if(!(a.cmp(n)>0))return a.iaddn(1),this.keyFromPrivate(a)}};ki.prototype._truncateToN=function(e,t){var i=e.byteLength()*8-this.n.bitLength();return i>0&&(e=e.ushrn(i)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e};ki.prototype.sign=function(e,t,i,n){typeof i=="object"&&(n=i,i=null),n||(n={}),t=this.keyFromPrivate(t,i),e=this._truncateToN(new la(e,16));for(var a=this.n.byteLength(),f=t.getPrivate().toArray("be",a),u=e.toArray("be",a),b=new yb({hash:this.hash,entropy:f,nonce:u,pers:n.pers,persEnc:n.persEnc||"utf8"}),p=this.n.sub(new la(1)),y=0;;y++){var A=n.k?n.k(y):new la(b.generate(this.n.byteLength()));if(A=this._truncateToN(A,!0),!(A.cmpn(1)<=0||A.cmp(p)>=0)){var R=this.g.mul(A);if(!R.isInfinity()){var O=R.getX(),N=O.umod(this.n);if(N.cmpn(0)!==0){var K=A.invm(this.n).mul(N.mul(t.getPrivate()).iadd(e));if(K=K.umod(this.n),K.cmpn(0)!==0){var W=(R.getY().isOdd()?1:0)|(O.cmp(N)!==0?2:0);return n.canonical&&K.cmp(this.nh)>0&&(K=this.n.sub(K),W^=1),new Lh({r:N,s:K,recoveryParam:W})}}}}}};ki.prototype.verify=function(e,t,i,n){e=this._truncateToN(new la(e,16)),i=this.keyFromPublic(i,n),t=new Lh(t,"hex");var a=t.r,f=t.s;if(a.cmpn(1)<0||a.cmp(this.n)>=0||f.cmpn(1)<0||f.cmp(this.n)>=0)return!1;var u=f.invm(this.n),b=u.mul(e).umod(this.n),p=u.mul(a).umod(this.n),y;return this.curve._maxwellTrick?(y=this.g.jmulAdd(b,i.getPublic(),p),y.isInfinity()?!1:y.eqXToP(a)):(y=this.g.mulAdd(b,i.getPublic(),p),y.isInfinity()?!1:y.getX().umod(this.n).cmp(a)===0)};ki.prototype.recoverPubKey=function(r,e,t,i){wb((3&t)===t,"The recovery param is more than two bits"),e=new Lh(e,i);var n=this.n,a=new la(r),f=e.r,u=e.s,b=t&1,p=t>>1;if(f.cmp(this.curve.p.umod(this.curve.n))>=0&&p)throw new Error("Unable to find sencond key candinate");p?f=this.curve.pointFromX(f.add(this.curve.n),b):f=this.curve.pointFromX(f,b);var y=e.r.invm(n),A=n.sub(a).mul(y).umod(n),R=u.mul(y).umod(n);return this.g.mulAdd(A,f,R)};ki.prototype.getKeyRecoveryParam=function(r,e,t,i){if(e=new Lh(e,i),e.recoveryParam!==null)return e.recoveryParam;for(var n=0;n<4;n++){var a;try{a=this.recoverPubKey(r,e,n)}catch{continue}if(a.eq(t))return n}throw new Error("Unable to find valid recovery factor")};var xc=xi,_b=xc.assert,M1=xc.parseBytes,go=xc.cachedProperty;function xr(r,e){this.eddsa=r,this._secret=M1(e.secret),r.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=M1(e.pub)}xr.fromPublic=function(e,t){return t instanceof xr?t:new xr(e,{pub:t})};xr.fromSecret=function(e,t){return t instanceof xr?t:new xr(e,{secret:t})};xr.prototype.secret=function(){return this._secret};go(xr,"pubBytes",function(){return this.eddsa.encodePoint(this.pub())});go(xr,"pub",function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())});go(xr,"privBytes",function(){var e=this.eddsa,t=this.hash(),i=e.encodingLength-1,n=t.slice(0,e.encodingLength);return n[0]&=248,n[i]&=127,n[i]|=64,n});go(xr,"priv",function(){return this.eddsa.decodeInt(this.privBytes())});go(xr,"hash",function(){return this.eddsa.hash().update(this.secret()).digest()});go(xr,"messagePrefix",function(){return this.hash().slice(this.eddsa.encodingLength)});xr.prototype.sign=function(e){return _b(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)};xr.prototype.verify=function(e,t){return this.eddsa.verify(e,t,this)};xr.prototype.getSecret=function(e){return _b(this._secret,"KeyPair is public only"),xc.encode(this.secret(),e)};xr.prototype.getPublic=function(e){return xc.encode(this.pubBytes(),e)};var O9=xr,R9=bs,Uh=xi,P1=Uh.assert,$h=Uh.cachedProperty,N9=Uh.parseBytes;function wa(r,e){this.eddsa=r,typeof e!="object"&&(e=N9(e)),Array.isArray(e)&&(P1(e.length===r.encodingLength*2,"Signature has invalid size"),e={R:e.slice(0,r.encodingLength),S:e.slice(r.encodingLength)}),P1(e.R&&e.S,"Signature without R or S"),r.isPoint(e.R)&&(this._R=e.R),e.S instanceof R9&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}$h(wa,"S",function(){return this.eddsa.decodeInt(this.Sencoded())});$h(wa,"R",function(){return this.eddsa.decodePoint(this.Rencoded())});$h(wa,"Rencoded",function(){return this.eddsa.encodePoint(this.R())});$h(wa,"Sencoded",function(){return this.eddsa.encodeInt(this.S())});wa.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())};wa.prototype.toHex=function(){return Uh.encode(this.toBytes(),"hex").toUpperCase()};var C9=wa,T9=Fh,D9=Dh,so=xi,F9=so.assert,Ab=so.parseBytes,Eb=O9,O1=C9;function ui(r){if(F9(r==="ed25519","only tested with ed25519 so far"),!(this instanceof ui))return new ui(r);r=D9[r].curve,this.curve=r,this.g=r.g,this.g.precompute(r.n.bitLength()+1),this.pointClass=r.point().constructor,this.encodingLength=Math.ceil(r.n.bitLength()/8),this.hash=T9.sha512}var B9=ui;ui.prototype.sign=function(e,t){e=Ab(e);var i=this.keyFromSecret(t),n=this.hashInt(i.messagePrefix(),e),a=this.g.mul(n),f=this.encodePoint(a),u=this.hashInt(f,i.pubBytes(),e).mul(i.priv()),b=n.add(u).umod(this.curve.n);return this.makeSignature({R:a,S:b,Rencoded:f})};ui.prototype.verify=function(e,t,i){if(e=Ab(e),t=this.makeSignature(t),t.S().gte(t.eddsa.curve.n)||t.S().isNeg())return!1;var n=this.keyFromPublic(i),a=this.hashInt(t.Rencoded(),n.pubBytes(),e),f=this.g.mul(t.S()),u=t.R().add(n.pub().mul(a));return u.eq(f)};ui.prototype.hashInt=function(){for(var e=this.hash(),t=0;t0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=b[y++],p--;this._bufferLength===this.blockSize&&(a(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(p>=this.blockSize&&(y=a(this._tempHi,this._tempLo,this._stateHi,this._stateLo,b,y,p),p%=this.blockSize);p>0;)this._buffer[this._bufferLength++]=b[y++],p--;return this},u.prototype.finish=function(b){if(!this._finished){var p=this._bytesHashed,y=this._bufferLength,A=p/536870912|0,R=p<<3,O=p%128<112?128:256;this._buffer[y]=128;for(var N=y+1;N0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},u.prototype.restoreState=function(b){return this._stateHi.set(b.stateHi),this._stateLo.set(b.stateLo),this._bufferLength=b.bufferLength,b.buffer&&this._buffer.set(b.buffer),this._bytesHashed=b.bytesHashed,this._finished=!1,this},u.prototype.cleanSavedState=function(b){t.wipe(b.stateHi),t.wipe(b.stateLo),b.buffer&&t.wipe(b.buffer),b.bufferLength=0,b.bytesHashed=0},u}();r.SHA512=i;var n=new Int32Array([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 a(u,b,p,y,A,R,O){for(var N=p[0],K=p[1],W=p[2],Q=p[3],j=p[4],Y=p[5],U=p[6],k=p[7],G=y[0],x=y[1],B=y[2],ae=y[3],le=y[4],F=y[5],m=y[6],c=y[7],h,v,_,I,M,S,d,g;O>=128;){for(var T=0;T<16;T++){var Z=8*T+R;u[T]=e.readUint32BE(A,Z),b[T]=e.readUint32BE(A,Z+4)}for(var T=0;T<80;T++){var se=N,P=K,ee=W,q=Q,z=j,H=Y,w=U,$=k,ne=G,ce=x,he=B,ye=ae,we=le,Ce=F,Qe=m,Oe=c;if(h=k,v=c,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=(j>>>14|le<<18)^(j>>>18|le<<14)^(le>>>9|j<<23),v=(le>>>14|j<<18)^(le>>>18|j<<14)^(j>>>9|le<<23),M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,h=j&Y^~j&U,v=le&F^~le&m,M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,h=n[T*2],v=n[T*2+1],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,h=u[T%16],v=b[T%16],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,_=d&65535|g<<16,I=M&65535|S<<16,h=_,v=I,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=(N>>>28|G<<4)^(G>>>2|N<<30)^(G>>>7|N<<25),v=(G>>>28|N<<4)^(N>>>2|G<<30)^(N>>>7|G<<25),M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,h=N&K^N&W^K&W,v=G&x^G&B^x&B,M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,$=d&65535|g<<16,Oe=M&65535|S<<16,h=q,v=ye,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=_,v=I,M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,q=d&65535|g<<16,ye=M&65535|S<<16,K=se,W=P,Q=ee,j=q,Y=z,U=H,k=w,N=$,x=ne,B=ce,ae=he,le=ye,F=we,m=Ce,c=Qe,G=Oe,T%16===15)for(var Z=0;Z<16;Z++)h=u[Z],v=b[Z],M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=u[(Z+9)%16],v=b[(Z+9)%16],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,_=u[(Z+1)%16],I=b[(Z+1)%16],h=(_>>>1|I<<31)^(_>>>8|I<<24)^_>>>7,v=(I>>>1|_<<31)^(I>>>8|_<<24)^(I>>>7|_<<25),M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,_=u[(Z+14)%16],I=b[(Z+14)%16],h=(_>>>19|I<<13)^(I>>>29|_<<3)^_>>>6,v=(I>>>19|_<<13)^(_>>>29|I<<3)^(I>>>6|_<<26),M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,u[Z]=d&65535|g<<16,b[Z]=M&65535|S<<16}h=N,v=G,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=p[0],v=y[0],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,p[0]=N=d&65535|g<<16,y[0]=G=M&65535|S<<16,h=K,v=x,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=p[1],v=y[1],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,p[1]=K=d&65535|g<<16,y[1]=x=M&65535|S<<16,h=W,v=B,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=p[2],v=y[2],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,p[2]=W=d&65535|g<<16,y[2]=B=M&65535|S<<16,h=Q,v=ae,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=p[3],v=y[3],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,p[3]=Q=d&65535|g<<16,y[3]=ae=M&65535|S<<16,h=j,v=le,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=p[4],v=y[4],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,p[4]=j=d&65535|g<<16,y[4]=le=M&65535|S<<16,h=Y,v=F,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=p[5],v=y[5],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,p[5]=Y=d&65535|g<<16,y[5]=F=M&65535|S<<16,h=U,v=m,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=p[6],v=y[6],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,p[6]=U=d&65535|g<<16,y[6]=m=M&65535|S<<16,h=k,v=c,M=v&65535,S=v>>>16,d=h&65535,g=h>>>16,h=p[7],v=y[7],M+=v&65535,S+=v>>>16,d+=h&65535,g+=h>>>16,S+=M>>>16,d+=S>>>16,g+=d>>>16,p[7]=k=d&65535|g<<16,y[7]=c=M&65535|S<<16,R+=128,O-=128}return R}function f(u){var b=new i;b.update(u);var p=b.digest();return b.clean(),p}r.hash=f})(xb);(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.convertSecretKeyToX25519=r.convertPublicKeyToX25519=r.verify=r.sign=r.extractPublicKeyFromSecretKey=r.generateKeyPair=r.generateKeyPairFromSeed=r.SEED_LENGTH=r.SECRET_KEY_LENGTH=r.PUBLIC_KEY_LENGTH=r.SIGNATURE_LENGTH=void 0;const e=$s,t=xb,i=Ei;r.SIGNATURE_LENGTH=64,r.PUBLIC_KEY_LENGTH=32,r.SECRET_KEY_LENGTH=64,r.SEED_LENGTH=32;function n(q){const z=new Float64Array(16);if(q)for(let H=0;H>16&1),H[ce-1]&=65535;H[15]=w[15]-32767-(H[14]>>16&1);const ne=H[15]>>16&1;H[14]&=65535,K(w,H,1-ne)}for(let $=0;$<16;$++)q[2*$]=w[$]&255,q[2*$+1]=w[$]>>8}function Q(q,z){let H=0;for(let w=0;w<32;w++)H|=q[w]^z[w];return(1&H-1>>>8)-1}function j(q,z){const H=new Uint8Array(32),w=new Uint8Array(32);return W(H,q),W(w,z),Q(H,w)}function Y(q){const z=new Uint8Array(32);return W(z,q),z[0]&1}function U(q,z){for(let H=0;H<16;H++)q[H]=z[2*H]+(z[2*H+1]<<8);q[15]&=32767}function k(q,z,H){for(let w=0;w<16;w++)q[w]=z[w]+H[w]}function G(q,z,H){for(let w=0;w<16;w++)q[w]=z[w]-H[w]}function x(q,z,H){let w,$,ne=0,ce=0,he=0,ye=0,we=0,Ce=0,Qe=0,Oe=0,Te=0,Ie=0,me=0,Re=0,De=0,ve=0,Ne=0,Se=0,be=0,Le=0,Me=0,_e=0,He=0,Ve=0,Ee=0,Ke=0,ut=0,Ge=0,_t=0,lt=0,Je=0,Et=0,It=0,Fe=H[0],Xe=H[1],tt=H[2],Be=H[3],et=H[4],Ze=H[5],$e=H[6],ft=H[7],rt=H[8],ze=H[9],it=H[10],st=H[11],qe=H[12],Ye=H[13],ht=H[14],je=H[15];w=z[0],ne+=w*Fe,ce+=w*Xe,he+=w*tt,ye+=w*Be,we+=w*et,Ce+=w*Ze,Qe+=w*$e,Oe+=w*ft,Te+=w*rt,Ie+=w*ze,me+=w*it,Re+=w*st,De+=w*qe,ve+=w*Ye,Ne+=w*ht,Se+=w*je,w=z[1],ce+=w*Fe,he+=w*Xe,ye+=w*tt,we+=w*Be,Ce+=w*et,Qe+=w*Ze,Oe+=w*$e,Te+=w*ft,Ie+=w*rt,me+=w*ze,Re+=w*it,De+=w*st,ve+=w*qe,Ne+=w*Ye,Se+=w*ht,be+=w*je,w=z[2],he+=w*Fe,ye+=w*Xe,we+=w*tt,Ce+=w*Be,Qe+=w*et,Oe+=w*Ze,Te+=w*$e,Ie+=w*ft,me+=w*rt,Re+=w*ze,De+=w*it,ve+=w*st,Ne+=w*qe,Se+=w*Ye,be+=w*ht,Le+=w*je,w=z[3],ye+=w*Fe,we+=w*Xe,Ce+=w*tt,Qe+=w*Be,Oe+=w*et,Te+=w*Ze,Ie+=w*$e,me+=w*ft,Re+=w*rt,De+=w*ze,ve+=w*it,Ne+=w*st,Se+=w*qe,be+=w*Ye,Le+=w*ht,Me+=w*je,w=z[4],we+=w*Fe,Ce+=w*Xe,Qe+=w*tt,Oe+=w*Be,Te+=w*et,Ie+=w*Ze,me+=w*$e,Re+=w*ft,De+=w*rt,ve+=w*ze,Ne+=w*it,Se+=w*st,be+=w*qe,Le+=w*Ye,Me+=w*ht,_e+=w*je,w=z[5],Ce+=w*Fe,Qe+=w*Xe,Oe+=w*tt,Te+=w*Be,Ie+=w*et,me+=w*Ze,Re+=w*$e,De+=w*ft,ve+=w*rt,Ne+=w*ze,Se+=w*it,be+=w*st,Le+=w*qe,Me+=w*Ye,_e+=w*ht,He+=w*je,w=z[6],Qe+=w*Fe,Oe+=w*Xe,Te+=w*tt,Ie+=w*Be,me+=w*et,Re+=w*Ze,De+=w*$e,ve+=w*ft,Ne+=w*rt,Se+=w*ze,be+=w*it,Le+=w*st,Me+=w*qe,_e+=w*Ye,He+=w*ht,Ve+=w*je,w=z[7],Oe+=w*Fe,Te+=w*Xe,Ie+=w*tt,me+=w*Be,Re+=w*et,De+=w*Ze,ve+=w*$e,Ne+=w*ft,Se+=w*rt,be+=w*ze,Le+=w*it,Me+=w*st,_e+=w*qe,He+=w*Ye,Ve+=w*ht,Ee+=w*je,w=z[8],Te+=w*Fe,Ie+=w*Xe,me+=w*tt,Re+=w*Be,De+=w*et,ve+=w*Ze,Ne+=w*$e,Se+=w*ft,be+=w*rt,Le+=w*ze,Me+=w*it,_e+=w*st,He+=w*qe,Ve+=w*Ye,Ee+=w*ht,Ke+=w*je,w=z[9],Ie+=w*Fe,me+=w*Xe,Re+=w*tt,De+=w*Be,ve+=w*et,Ne+=w*Ze,Se+=w*$e,be+=w*ft,Le+=w*rt,Me+=w*ze,_e+=w*it,He+=w*st,Ve+=w*qe,Ee+=w*Ye,Ke+=w*ht,ut+=w*je,w=z[10],me+=w*Fe,Re+=w*Xe,De+=w*tt,ve+=w*Be,Ne+=w*et,Se+=w*Ze,be+=w*$e,Le+=w*ft,Me+=w*rt,_e+=w*ze,He+=w*it,Ve+=w*st,Ee+=w*qe,Ke+=w*Ye,ut+=w*ht,Ge+=w*je,w=z[11],Re+=w*Fe,De+=w*Xe,ve+=w*tt,Ne+=w*Be,Se+=w*et,be+=w*Ze,Le+=w*$e,Me+=w*ft,_e+=w*rt,He+=w*ze,Ve+=w*it,Ee+=w*st,Ke+=w*qe,ut+=w*Ye,Ge+=w*ht,_t+=w*je,w=z[12],De+=w*Fe,ve+=w*Xe,Ne+=w*tt,Se+=w*Be,be+=w*et,Le+=w*Ze,Me+=w*$e,_e+=w*ft,He+=w*rt,Ve+=w*ze,Ee+=w*it,Ke+=w*st,ut+=w*qe,Ge+=w*Ye,_t+=w*ht,lt+=w*je,w=z[13],ve+=w*Fe,Ne+=w*Xe,Se+=w*tt,be+=w*Be,Le+=w*et,Me+=w*Ze,_e+=w*$e,He+=w*ft,Ve+=w*rt,Ee+=w*ze,Ke+=w*it,ut+=w*st,Ge+=w*qe,_t+=w*Ye,lt+=w*ht,Je+=w*je,w=z[14],Ne+=w*Fe,Se+=w*Xe,be+=w*tt,Le+=w*Be,Me+=w*et,_e+=w*Ze,He+=w*$e,Ve+=w*ft,Ee+=w*rt,Ke+=w*ze,ut+=w*it,Ge+=w*st,_t+=w*qe,lt+=w*Ye,Je+=w*ht,Et+=w*je,w=z[15],Se+=w*Fe,be+=w*Xe,Le+=w*tt,Me+=w*Be,_e+=w*et,He+=w*Ze,Ve+=w*$e,Ee+=w*ft,Ke+=w*rt,ut+=w*ze,Ge+=w*it,_t+=w*st,lt+=w*qe,Je+=w*Ye,Et+=w*ht,It+=w*je,ne+=38*be,ce+=38*Le,he+=38*Me,ye+=38*_e,we+=38*He,Ce+=38*Ve,Qe+=38*Ee,Oe+=38*Ke,Te+=38*ut,Ie+=38*Ge,me+=38*_t,Re+=38*lt,De+=38*Je,ve+=38*Et,Ne+=38*It,$=1,w=ne+$+65535,$=Math.floor(w/65536),ne=w-$*65536,w=ce+$+65535,$=Math.floor(w/65536),ce=w-$*65536,w=he+$+65535,$=Math.floor(w/65536),he=w-$*65536,w=ye+$+65535,$=Math.floor(w/65536),ye=w-$*65536,w=we+$+65535,$=Math.floor(w/65536),we=w-$*65536,w=Ce+$+65535,$=Math.floor(w/65536),Ce=w-$*65536,w=Qe+$+65535,$=Math.floor(w/65536),Qe=w-$*65536,w=Oe+$+65535,$=Math.floor(w/65536),Oe=w-$*65536,w=Te+$+65535,$=Math.floor(w/65536),Te=w-$*65536,w=Ie+$+65535,$=Math.floor(w/65536),Ie=w-$*65536,w=me+$+65535,$=Math.floor(w/65536),me=w-$*65536,w=Re+$+65535,$=Math.floor(w/65536),Re=w-$*65536,w=De+$+65535,$=Math.floor(w/65536),De=w-$*65536,w=ve+$+65535,$=Math.floor(w/65536),ve=w-$*65536,w=Ne+$+65535,$=Math.floor(w/65536),Ne=w-$*65536,w=Se+$+65535,$=Math.floor(w/65536),Se=w-$*65536,ne+=$-1+37*($-1),$=1,w=ne+$+65535,$=Math.floor(w/65536),ne=w-$*65536,w=ce+$+65535,$=Math.floor(w/65536),ce=w-$*65536,w=he+$+65535,$=Math.floor(w/65536),he=w-$*65536,w=ye+$+65535,$=Math.floor(w/65536),ye=w-$*65536,w=we+$+65535,$=Math.floor(w/65536),we=w-$*65536,w=Ce+$+65535,$=Math.floor(w/65536),Ce=w-$*65536,w=Qe+$+65535,$=Math.floor(w/65536),Qe=w-$*65536,w=Oe+$+65535,$=Math.floor(w/65536),Oe=w-$*65536,w=Te+$+65535,$=Math.floor(w/65536),Te=w-$*65536,w=Ie+$+65535,$=Math.floor(w/65536),Ie=w-$*65536,w=me+$+65535,$=Math.floor(w/65536),me=w-$*65536,w=Re+$+65535,$=Math.floor(w/65536),Re=w-$*65536,w=De+$+65535,$=Math.floor(w/65536),De=w-$*65536,w=ve+$+65535,$=Math.floor(w/65536),ve=w-$*65536,w=Ne+$+65535,$=Math.floor(w/65536),Ne=w-$*65536,w=Se+$+65535,$=Math.floor(w/65536),Se=w-$*65536,ne+=$-1+37*($-1),q[0]=ne,q[1]=ce,q[2]=he,q[3]=ye,q[4]=we,q[5]=Ce,q[6]=Qe,q[7]=Oe,q[8]=Te,q[9]=Ie,q[10]=me,q[11]=Re,q[12]=De,q[13]=ve,q[14]=Ne,q[15]=Se}function B(q,z){x(q,z,z)}function ae(q,z){const H=n();let w;for(w=0;w<16;w++)H[w]=z[w];for(w=253;w>=0;w--)B(H,H),w!==2&&w!==4&&x(H,H,z);for(w=0;w<16;w++)q[w]=H[w]}function le(q,z){const H=n();let w;for(w=0;w<16;w++)H[w]=z[w];for(w=250;w>=0;w--)B(H,H),w!==1&&x(H,H,z);for(w=0;w<16;w++)q[w]=H[w]}function F(q,z){const H=n(),w=n(),$=n(),ne=n(),ce=n(),he=n(),ye=n(),we=n(),Ce=n();G(H,q[1],q[0]),G(Ce,z[1],z[0]),x(H,H,Ce),k(w,q[0],q[1]),k(Ce,z[0],z[1]),x(w,w,Ce),x($,q[3],z[3]),x($,$,p),x(ne,q[2],z[2]),k(ne,ne,ne),G(ce,w,H),G(he,ne,$),k(ye,ne,$),k(we,w,H),x(q[0],ce,he),x(q[1],we,ye),x(q[2],ye,he),x(q[3],ce,we)}function m(q,z,H){for(let w=0;w<4;w++)K(q[w],z[w],H)}function c(q,z){const H=n(),w=n(),$=n();ae($,z[2]),x(H,z[0],$),x(w,z[1],$),W(q,w),q[31]^=Y(H)<<7}function h(q,z,H){O(q[0],f),O(q[1],u),O(q[2],u),O(q[3],f);for(let w=255;w>=0;--w){const $=H[w/8|0]>>(w&7)&1;m(q,z,$),F(z,q),F(q,q),m(q,z,$)}}function v(q,z){const H=[n(),n(),n(),n()];O(H[0],y),O(H[1],A),O(H[2],u),x(H[3],y,A),h(q,H,z)}function _(q){if(q.length!==r.SEED_LENGTH)throw new Error(`ed25519: seed must be ${r.SEED_LENGTH} bytes`);const z=(0,t.hash)(q);z[0]&=248,z[31]&=127,z[31]|=64;const H=new Uint8Array(32),w=[n(),n(),n(),n()];v(w,z),c(H,w);const $=new Uint8Array(64);return $.set(q),$.set(H,32),{publicKey:H,secretKey:$}}r.generateKeyPairFromSeed=_;function I(q){const z=(0,e.randomBytes)(32,q),H=_(z);return(0,i.wipe)(z),H}r.generateKeyPair=I;function M(q){if(q.length!==r.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${r.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(q.subarray(32))}r.extractPublicKeyFromSecretKey=M;const S=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function d(q,z){let H,w,$,ne;for(w=63;w>=32;--w){for(H=0,$=w-32,ne=w-12;$>4)*S[$],H=z[$]>>8,z[$]&=255;for($=0;$<32;$++)z[$]-=H*S[$];for(w=0;w<32;w++)z[w+1]+=z[w]>>8,q[w]=z[w]&255}function g(q){const z=new Float64Array(64);for(let H=0;H<64;H++)z[H]=q[H];for(let H=0;H<64;H++)q[H]=0;d(q,z)}function T(q,z){const H=new Float64Array(64),w=[n(),n(),n(),n()],$=(0,t.hash)(q.subarray(0,32));$[0]&=248,$[31]&=127,$[31]|=64;const ne=new Uint8Array(64);ne.set($.subarray(32),32);const ce=new t.SHA512;ce.update(ne.subarray(32)),ce.update(z);const he=ce.digest();ce.clean(),g(he),v(w,he),c(ne,w),ce.reset(),ce.update(ne.subarray(0,32)),ce.update(q.subarray(32)),ce.update(z);const ye=ce.digest();g(ye);for(let we=0;we<32;we++)H[we]=he[we];for(let we=0;we<32;we++)for(let Ce=0;Ce<32;Ce++)H[we+Ce]+=ye[we]*$[Ce];return d(ne.subarray(32),H),ne}r.sign=T;function Z(q,z){const H=n(),w=n(),$=n(),ne=n(),ce=n(),he=n(),ye=n();return O(q[2],u),U(q[1],z),B($,q[1]),x(ne,$,b),G($,$,q[2]),k(ne,q[2],ne),B(ce,ne),B(he,ce),x(ye,he,ce),x(H,ye,$),x(H,H,ne),le(H,H),x(H,H,$),x(H,H,ne),x(H,H,ne),x(q[0],H,ne),B(w,q[0]),x(w,w,ne),j(w,$)&&x(q[0],q[0],R),B(w,q[0]),x(w,w,ne),j(w,$)?-1:(Y(q[0])===z[31]>>7&&G(q[0],f,q[0]),x(q[3],q[0],q[1]),0)}function se(q,z,H){const w=new Uint8Array(32),$=[n(),n(),n(),n()],ne=[n(),n(),n(),n()];if(H.length!==r.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${r.SIGNATURE_LENGTH} bytes`);if(Z(ne,q))return!1;const ce=new t.SHA512;ce.update(H.subarray(0,32)),ce.update(q),ce.update(z);const he=ce.digest();return g(he),h($,ne,he),v(ne,H.subarray(32)),F($,ne),c(w,$),!Q(H,w)}r.verify=se;function P(q){let z=[n(),n(),n(),n()];if(Z(z,q))throw new Error("Ed25519: invalid public key");let H=n(),w=n(),$=z[1];k(H,u,$),G(w,u,$),ae(w,w),x(H,H,w);let ne=new Uint8Array(32);return W(ne,H),ne}r.convertPublicKeyToX25519=P;function ee(q){const z=(0,t.hash)(q.subarray(0,32));z[0]&=248,z[31]&=127,z[31]|=64;const H=new Uint8Array(z.subarray(0,32));return(0,i.wipe)(z),H}r.convertSecretKeyToX25519=ee})($0);const q9="EdDSA",L9="JWT",uh=".",zh="base64url",Sb="utf8",Ib="utf8",U9=":",$9="did",z9="key",R1="base58btc",j9="z",k9="K36",H9=32,K9=r=>JSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString()+"n":t),V9=r=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,t=r.replace(e,'$1"$2n"$3');return JSON.parse(t,(i,n)=>typeof n=="string"&&n.match(/^\d+n$/)?BigInt(n.substring(0,n.length-1)):n)};function ga(r){if(typeof r!="string")throw new Error(`Cannot safe json parse value of type ${typeof r}`);try{return V9(r)}catch{return r}}function vs(r){return typeof r=="string"?r:K9(r)||""}function N1(r){return ga(Er(Ar(r,zh),Sb))}function lh(r){return Er(Ar(vs(r),Sb),zh)}function Mb(r){const e=Ar(k9,R1),t=j9+Er(Yf([e,r]),R1);return[$9,z9,t].join(U9)}function G9(r){return Er(r,zh)}function W9(r){return Ar(r,zh)}function J9(r){return Ar([lh(r.header),lh(r.payload)].join(uh),Ib)}function Y9(r){return[lh(r.header),lh(r.payload),G9(r.signature)].join(uh)}function n0(r){const e=r.split(uh),t=N1(e[0]),i=N1(e[1]),n=W9(e[2]),a=Ar(e.slice(0,2).join(uh),Ib);return{header:t,payload:i,signature:n,data:a}}function C1(r=$s.randomBytes(H9)){return $0.generateKeyPairFromSeed(r)}async function Q9(r,e,t,i,n=xe.fromMiliseconds(Date.now())){const a={alg:q9,typ:L9},f=Mb(i.publicKey),u=n+t,b={iss:f,sub:r,aud:e,iat:n,exp:u},p=J9({header:a,payload:b}),y=$0.sign(i.secretKey,p);return Y9({header:a,payload:b,signature:y})}const X9={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}};var Z9={};const eA=":";function ac(r){const[e,t]=r.split(eA);return{namespace:e,reference:t}}function T1(r,e=[]){const t=[];return Object.keys(r).forEach(i=>{if(e.length&&!e.includes(i))return;const n=r[i];t.push(...n.accounts)}),t}function Pb(r,e){return r.includes(":")?[r]:e.chains||[]}var tA=Object.defineProperty,D1=Object.getOwnPropertySymbols,rA=Object.prototype.hasOwnProperty,iA=Object.prototype.propertyIsEnumerable,F1=(r,e,t)=>e in r?tA(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,B1=(r,e)=>{for(var t in e||(e={}))rA.call(e,t)&&F1(r,t,e[t]);if(D1)for(var t of D1(e))iA.call(e,t)&&F1(r,t,e[t]);return r};const nA="ReactNative",wi={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},sA="js";function dh(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function vo(){return!Ih()&&!!P0()&&navigator.product===nA}function Sc(){return!dh()&&!!P0()&&!!Ih()}function Ic(){return vo()?wi.reactNative:dh()?wi.node:Sc()?wi.browser:wi.unknown}function aA(){var r;try{return vo()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(r=global.Application)==null?void 0:r.applicationId:void 0}catch{return}}function oA(r,e){let t=dc.parse(r);return t=B1(B1({},t),e),r=dc.stringify(t),r}function Ob(){return qv()||{name:"",description:"",url:"",icons:[""]}}function cA(){if(Ic()===wi.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:t,Version:i}=global.Platform;return[t,i].join("-")}const r=z4();if(r===null)return"unknown";const e=r.os?r.os.replace(" ","").toLowerCase():"unknown";return r.type==="browser"?[e,r.name,r.version].join("-"):[e,r.version].join("-")}function fA(){var r;const e=Ic();return e===wi.browser?[e,((r=Bv())==null?void 0:r.host)||"unknown"].join(":"):e}function Rb(r,e,t){const i=cA(),n=fA();return[[r,e].join("-"),[sA,t].join("-"),i,n].join("/")}function hA({protocol:r,version:e,relayUrl:t,sdkVersion:i,auth:n,projectId:a,useOnCloseEvent:f,bundleId:u}){const b=t.split("?"),p=Rb(r,e,i),y={auth:n,ua:p,projectId:a,useOnCloseEvent:f||void 0,origin:u||void 0},A=oA(b[1]||"",y);return b[0]+"?"+A}function fa(r,e){return r.filter(t=>e.includes(t)).length===r.length}function Nb(r){return Object.fromEntries(r.entries())}function Cb(r){return new Map(Object.entries(r))}function oa(r=xe.FIVE_MINUTES,e){const t=xe.toMiliseconds(r||xe.FIVE_MINUTES);let i,n,a;return{resolve:f=>{a&&i&&(clearTimeout(a),i(f))},reject:f=>{a&&n&&(clearTimeout(a),n(f))},done:()=>new Promise((f,u)=>{a=setTimeout(()=>{u(new Error(e))},t),i=f,n=u})}}function Za(r,e,t){return new Promise(async(i,n)=>{const a=setTimeout(()=>n(new Error(t)),e);try{const f=await r;i(f)}catch(f){n(f)}clearTimeout(a)})}function Tb(r,e){if(typeof e=="string"&&e.startsWith(`${r}:`))return e;if(r.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(r.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${r}`)}function uA(r){return Tb("topic",r)}function lA(r){return Tb("id",r)}function Db(r){const[e,t]=r.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function vr(r,e){return xe.fromMiliseconds(Date.now()+xe.toMiliseconds(r))}function Rs(r){return Date.now()>=xe.toMiliseconds(r)}function St(r,e){return`${r}${e?`:${e}`:""}`}function Qf(r=[],e=[]){return[...new Set([...r,...e])]}async function dA({id:r,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const n=typeof t=="string"?JSON.parse(t):t,a=n==null?void 0:n.href;if(typeof a!="string")return;const f=pA(a,r,e),u=Ic();if(u===wi.browser){if(!((i=Ih())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}f.startsWith("https://")||f.startsWith("http://")?window.open(f,"_blank","noreferrer noopener"):window.open(f,vA()?"_blank":"_self","noreferrer noopener")}else u===wi.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(f)}catch(n){console.error(n)}}function pA(r,e,t){const i=`requestId=${e}&sessionTopic=${t}`;r.endsWith("/")&&(r=r.slice(0,-1));let n=`${r}`;if(r.startsWith("https://t.me")){const a=r.includes("?")?"&startapp=":"?startapp=";n=`${n}${a}${bA(i,!0)}`}else n=`${n}/wc?${i}`;return n}async function gA(r,e){let t="";try{if(Sc()&&(t=localStorage.getItem(e),t))return t;t=await r.getItem(e)}catch(i){console.error(i)}return t}function q1(r,e){if(!r.includes(e))return null;const t=r.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function L1(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function z0(){return typeof process<"u"&&Z9.IS_VITEST==="true"}function vA(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function bA(r,e=!1){const t=Buffer.from(r).toString("base64");return e?t.replace(/[=]/g,""):t}function Fb(r){return Buffer.from(r,"base64").toString("utf-8")}var Bb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function mA(r){var e=r.default;if(typeof e=="function"){var t=function(){return e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(i){var n=Object.getOwnPropertyDescriptor(r,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return r[i]}})}),t}var qb={exports:{}};/** +* [js-sha3]{@link https://github.com/emn178/js-sha3} +* +* @version 0.8.0 +* @author Chen, Yi-Cyuan [emn178@gmail.com] +* @copyright Chen, Yi-Cyuan 2015-2018 +* @license MIT +*/(function(r){(function(){var e="input is invalid type",t="finalize already called",i=typeof window=="object",n=i?window:{};n.JS_SHA3_NO_WINDOW&&(i=!1);var a=!i&&typeof self=="object",f=!n.JS_SHA3_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;f?n=Bb:a&&(n=self);var u=!n.JS_SHA3_NO_COMMON_JS&&!0&&r.exports,b=!n.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",p="0123456789abcdef".split(""),y=[31,7936,2031616,520093696],A=[4,1024,262144,67108864],R=[1,256,65536,16777216],O=[6,1536,393216,100663296],N=[0,8,16,24],K=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],W=[224,256,384,512],Q=[128,256],j=["hex","buffer","arrayBuffer","array","digest"],Y={128:168,256:136};(n.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(P){return Object.prototype.toString.call(P)==="[object Array]"}),b&&(n.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(P){return typeof P=="object"&&P.buffer&&P.buffer.constructor===ArrayBuffer});for(var U=function(P,ee,q){return function(z){return new T(P,ee,P).update(z)[q]()}},k=function(P,ee,q){return function(z,H){return new T(P,ee,H).update(z)[q]()}},G=function(P,ee,q){return function(z,H,w,$){return h["cshake"+P].update(z,H,w,$)[q]()}},x=function(P,ee,q){return function(z,H,w,$){return h["kmac"+P].update(z,H,w,$)[q]()}},B=function(P,ee,q,z){for(var H=0;H>5,this.byteCount=this.blockCount<<2,this.outputBlocks=q>>5,this.extraBytes=(q&31)>>3;for(var z=0;z<50;++z)this.s[z]=0}T.prototype.update=function(P){if(this.finalized)throw new Error(t);var ee,q=typeof P;if(q!=="string"){if(q==="object"){if(P===null)throw new Error(e);if(b&&P.constructor===ArrayBuffer)P=new Uint8Array(P);else if(!Array.isArray(P)&&(!b||!ArrayBuffer.isView(P)))throw new Error(e)}else throw new Error(e);ee=!0}for(var z=this.blocks,H=this.byteCount,w=P.length,$=this.blockCount,ne=0,ce=this.s,he,ye;ne>2]|=P[ne]<>2]|=ye<>2]|=(192|ye>>6)<>2]|=(128|ye&63)<=57344?(z[he>>2]|=(224|ye>>12)<>2]|=(128|ye>>6&63)<>2]|=(128|ye&63)<>2]|=(240|ye>>18)<>2]|=(128|ye>>12&63)<>2]|=(128|ye>>6&63)<>2]|=(128|ye&63)<=H){for(this.start=he-H,this.block=z[$],he=0;he<$;++he)ce[he]^=z[he];se(ce),this.reset=!0}else this.start=he}return this},T.prototype.encode=function(P,ee){var q=P&255,z=1,H=[q];for(P=P>>8,q=P&255;q>0;)H.unshift(q),P=P>>8,q=P&255,++z;return ee?H.push(z):H.unshift(z),this.update(H),H.length},T.prototype.encodeString=function(P){var ee,q=typeof P;if(q!=="string"){if(q==="object"){if(P===null)throw new Error(e);if(b&&P.constructor===ArrayBuffer)P=new Uint8Array(P);else if(!Array.isArray(P)&&(!b||!ArrayBuffer.isView(P)))throw new Error(e)}else throw new Error(e);ee=!0}var z=0,H=P.length;if(ee)z=H;else for(var w=0;w=57344?z+=3:($=65536+(($&1023)<<10|P.charCodeAt(++w)&1023),z+=4)}return z+=this.encode(z*8),this.update(P),z},T.prototype.bytepad=function(P,ee){for(var q=this.encode(ee),z=0;z>2]|=this.padding[ee&3],this.lastByteIndex===this.byteCount)for(P[0]=P[q],ee=1;ee>4&15]+p[ne&15]+p[ne>>12&15]+p[ne>>8&15]+p[ne>>20&15]+p[ne>>16&15]+p[ne>>28&15]+p[ne>>24&15];w%P===0&&(se(ee),H=0)}return z&&(ne=ee[H],$+=p[ne>>4&15]+p[ne&15],z>1&&($+=p[ne>>12&15]+p[ne>>8&15]),z>2&&($+=p[ne>>20&15]+p[ne>>16&15])),$},T.prototype.arrayBuffer=function(){this.finalize();var P=this.blockCount,ee=this.s,q=this.outputBlocks,z=this.extraBytes,H=0,w=0,$=this.outputBits>>3,ne;z?ne=new ArrayBuffer(q+1<<2):ne=new ArrayBuffer($);for(var ce=new Uint32Array(ne);w>8&255,$[ne+2]=ce>>16&255,$[ne+3]=ce>>24&255;w%P===0&&se(ee)}return z&&(ne=w<<2,ce=ee[H],$[ne]=ce&255,z>1&&($[ne+1]=ce>>8&255),z>2&&($[ne+2]=ce>>16&255)),$};function Z(P,ee,q){T.call(this,P,ee,q)}Z.prototype=new T,Z.prototype.finalize=function(){return this.encode(this.outputBits,!0),T.prototype.finalize.call(this)};var se=function(P){var ee,q,z,H,w,$,ne,ce,he,ye,we,Ce,Qe,Oe,Te,Ie,me,Re,De,ve,Ne,Se,be,Le,Me,_e,He,Ve,Ee,Ke,ut,Ge,_t,lt,Je,Et,It,Fe,Xe,tt,Be,et,Ze,$e,ft,rt,ze,it,st,qe,Ye,ht,je,Tt,Dt,at,bt,Cr,Tr,Dr,Fr,Br,er;for(z=0;z<48;z+=2)H=P[0]^P[10]^P[20]^P[30]^P[40],w=P[1]^P[11]^P[21]^P[31]^P[41],$=P[2]^P[12]^P[22]^P[32]^P[42],ne=P[3]^P[13]^P[23]^P[33]^P[43],ce=P[4]^P[14]^P[24]^P[34]^P[44],he=P[5]^P[15]^P[25]^P[35]^P[45],ye=P[6]^P[16]^P[26]^P[36]^P[46],we=P[7]^P[17]^P[27]^P[37]^P[47],Ce=P[8]^P[18]^P[28]^P[38]^P[48],Qe=P[9]^P[19]^P[29]^P[39]^P[49],ee=Ce^($<<1|ne>>>31),q=Qe^(ne<<1|$>>>31),P[0]^=ee,P[1]^=q,P[10]^=ee,P[11]^=q,P[20]^=ee,P[21]^=q,P[30]^=ee,P[31]^=q,P[40]^=ee,P[41]^=q,ee=H^(ce<<1|he>>>31),q=w^(he<<1|ce>>>31),P[2]^=ee,P[3]^=q,P[12]^=ee,P[13]^=q,P[22]^=ee,P[23]^=q,P[32]^=ee,P[33]^=q,P[42]^=ee,P[43]^=q,ee=$^(ye<<1|we>>>31),q=ne^(we<<1|ye>>>31),P[4]^=ee,P[5]^=q,P[14]^=ee,P[15]^=q,P[24]^=ee,P[25]^=q,P[34]^=ee,P[35]^=q,P[44]^=ee,P[45]^=q,ee=ce^(Ce<<1|Qe>>>31),q=he^(Qe<<1|Ce>>>31),P[6]^=ee,P[7]^=q,P[16]^=ee,P[17]^=q,P[26]^=ee,P[27]^=q,P[36]^=ee,P[37]^=q,P[46]^=ee,P[47]^=q,ee=ye^(H<<1|w>>>31),q=we^(w<<1|H>>>31),P[8]^=ee,P[9]^=q,P[18]^=ee,P[19]^=q,P[28]^=ee,P[29]^=q,P[38]^=ee,P[39]^=q,P[48]^=ee,P[49]^=q,Oe=P[0],Te=P[1],rt=P[11]<<4|P[10]>>>28,ze=P[10]<<4|P[11]>>>28,Ve=P[20]<<3|P[21]>>>29,Ee=P[21]<<3|P[20]>>>29,Dr=P[31]<<9|P[30]>>>23,Fr=P[30]<<9|P[31]>>>23,et=P[40]<<18|P[41]>>>14,Ze=P[41]<<18|P[40]>>>14,lt=P[2]<<1|P[3]>>>31,Je=P[3]<<1|P[2]>>>31,Ie=P[13]<<12|P[12]>>>20,me=P[12]<<12|P[13]>>>20,it=P[22]<<10|P[23]>>>22,st=P[23]<<10|P[22]>>>22,Ke=P[33]<<13|P[32]>>>19,ut=P[32]<<13|P[33]>>>19,Br=P[42]<<2|P[43]>>>30,er=P[43]<<2|P[42]>>>30,Tt=P[5]<<30|P[4]>>>2,Dt=P[4]<<30|P[5]>>>2,Et=P[14]<<6|P[15]>>>26,It=P[15]<<6|P[14]>>>26,Re=P[25]<<11|P[24]>>>21,De=P[24]<<11|P[25]>>>21,qe=P[34]<<15|P[35]>>>17,Ye=P[35]<<15|P[34]>>>17,Ge=P[45]<<29|P[44]>>>3,_t=P[44]<<29|P[45]>>>3,Le=P[6]<<28|P[7]>>>4,Me=P[7]<<28|P[6]>>>4,at=P[17]<<23|P[16]>>>9,bt=P[16]<<23|P[17]>>>9,Fe=P[26]<<25|P[27]>>>7,Xe=P[27]<<25|P[26]>>>7,ve=P[36]<<21|P[37]>>>11,Ne=P[37]<<21|P[36]>>>11,ht=P[47]<<24|P[46]>>>8,je=P[46]<<24|P[47]>>>8,$e=P[8]<<27|P[9]>>>5,ft=P[9]<<27|P[8]>>>5,_e=P[18]<<20|P[19]>>>12,He=P[19]<<20|P[18]>>>12,Cr=P[29]<<7|P[28]>>>25,Tr=P[28]<<7|P[29]>>>25,tt=P[38]<<8|P[39]>>>24,Be=P[39]<<8|P[38]>>>24,Se=P[48]<<14|P[49]>>>18,be=P[49]<<14|P[48]>>>18,P[0]=Oe^~Ie&Re,P[1]=Te^~me&De,P[10]=Le^~_e&Ve,P[11]=Me^~He&Ee,P[20]=lt^~Et&Fe,P[21]=Je^~It&Xe,P[30]=$e^~rt&it,P[31]=ft^~ze&st,P[40]=Tt^~at&Cr,P[41]=Dt^~bt&Tr,P[2]=Ie^~Re&ve,P[3]=me^~De&Ne,P[12]=_e^~Ve&Ke,P[13]=He^~Ee&ut,P[22]=Et^~Fe&tt,P[23]=It^~Xe&Be,P[32]=rt^~it&qe,P[33]=ze^~st&Ye,P[42]=at^~Cr&Dr,P[43]=bt^~Tr&Fr,P[4]=Re^~ve&Se,P[5]=De^~Ne&be,P[14]=Ve^~Ke&Ge,P[15]=Ee^~ut&_t,P[24]=Fe^~tt&et,P[25]=Xe^~Be&Ze,P[34]=it^~qe&ht,P[35]=st^~Ye&je,P[44]=Cr^~Dr&Br,P[45]=Tr^~Fr&er,P[6]=ve^~Se&Oe,P[7]=Ne^~be&Te,P[16]=Ke^~Ge&Le,P[17]=ut^~_t&Me,P[26]=tt^~et<,P[27]=Be^~Ze&Je,P[36]=qe^~ht&$e,P[37]=Ye^~je&ft,P[46]=Dr^~Br&Tt,P[47]=Fr^~er&Dt,P[8]=Se^~Oe&Ie,P[9]=be^~Te&me,P[18]=Ge^~Le&_e,P[19]=_t^~Me&He,P[28]=et^~lt&Et,P[29]=Ze^~Je&It,P[38]=ht^~$e&rt,P[39]=je^~ft&ze,P[48]=Br^~Tt&at,P[49]=er^~Dt&bt,P[0]^=K[z],P[1]^=K[z+1]};if(u)r.exports=h;else for(_=0;_{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{r.push(e)}}),r.length)throw new Error("missing "+r.join(", "));if("é".normalize("NFD")!=="é")throw new Error("broken implementation")}catch(r){return r.message}return null}const j1=_A();var s0;(function(r){r.DEBUG="DEBUG",r.INFO="INFO",r.WARNING="WARNING",r.ERROR="ERROR",r.OFF="OFF"})(s0||(s0={}));var hn;(function(r){r.UNKNOWN_ERROR="UNKNOWN_ERROR",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",r.NETWORK_ERROR="NETWORK_ERROR",r.SERVER_ERROR="SERVER_ERROR",r.TIMEOUT="TIMEOUT",r.BUFFER_OVERRUN="BUFFER_OVERRUN",r.NUMERIC_FAULT="NUMERIC_FAULT",r.MISSING_NEW="MISSING_NEW",r.INVALID_ARGUMENT="INVALID_ARGUMENT",r.MISSING_ARGUMENT="MISSING_ARGUMENT",r.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",r.CALL_EXCEPTION="CALL_EXCEPTION",r.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",r.NONCE_EXPIRED="NONCE_EXPIRED",r.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",r.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",r.TRANSACTION_REPLACED="TRANSACTION_REPLACED",r.ACTION_REJECTED="ACTION_REJECTED"})(hn||(hn={}));const k1="0123456789abcdef";let Or=class gr{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const i=e.toLowerCase();Xf[i]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(z1>Xf[i])&&console.log.apply(console,t)}debug(...e){this._log(gr.levels.DEBUG,e)}info(...e){this._log(gr.levels.INFO,e)}warn(...e){this._log(gr.levels.WARNING,e)}makeError(e,t,i){if($1)return this.makeError("censored error",t,{});t||(t=gr.errors.UNKNOWN_ERROR),i||(i={});const n=[];Object.keys(i).forEach(b=>{const p=i[b];try{if(p instanceof Uint8Array){let y="";for(let A=0;A>4],y+=k1[p[A]&15];n.push(b+"=Uint8Array(0x"+y+")")}else n.push(b+"="+JSON.stringify(p))}catch{n.push(b+"="+JSON.stringify(i[b].toString()))}}),n.push(`code=${t}`),n.push(`version=${this.version}`);const a=e;let f="";switch(t){case hn.NUMERIC_FAULT:{f="NUMERIC_FAULT";const b=e;switch(b){case"overflow":case"underflow":case"division-by-zero":f+="-"+b;break;case"negative-power":case"negative-width":f+="-unsupported";break;case"unbound-bitwise-result":f+="-unbound-result";break}break}case hn.CALL_EXCEPTION:case hn.INSUFFICIENT_FUNDS:case hn.MISSING_NEW:case hn.NONCE_EXPIRED:case hn.REPLACEMENT_UNDERPRICED:case hn.TRANSACTION_REPLACED:case hn.UNPREDICTABLE_GAS_LIMIT:f=t;break}f&&(e+=" [ See: https://links.ethers.org/v5-errors-"+f+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const u=new Error(e);return u.reason=a,u.code=t,Object.keys(i).forEach(function(b){u[b]=i[b]}),u}throwError(e,t,i){throw this.makeError(e,t,i)}throwArgumentError(e,t,i){return this.throwError(e,gr.errors.INVALID_ARGUMENT,{argument:t,value:i})}assert(e,t,i,n){e||this.throwError(t,i,n)}assertArgument(e,t,i,n){e||this.throwArgumentError(t,i,n)}checkNormalize(e){j1&&this.throwError("platform missing String.prototype.normalize",gr.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:j1})}checkSafeUint53(e,t){typeof e=="number"&&(t==null&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,gr.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,gr.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,i){i?i=": "+i:i="",et&&this.throwError("too many arguments"+i,gr.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){(e===Object||e==null)&&this.throwError("missing new",gr.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",gr.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",gr.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return bl||(bl=new gr(wA)),bl}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",gr.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),U1){if(!e)return;this.globalLogger().throwError("error censorship permanent",gr.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}$1=!!e,U1=!!t}static setLogLevel(e){const t=Xf[e.toLowerCase()];if(t==null){gr.globalLogger().warn("invalid log level - "+e);return}z1=t}static from(e){return new gr(e)}};Or.errors=hn,Or.levels=s0;const AA="bytes/5.7.0",cr=new Or(AA);function Lb(r){return!!r.toHexString}function eo(r){return r.slice||(r.slice=function(){const e=Array.prototype.slice.call(arguments);return eo(new Uint8Array(Array.prototype.slice.apply(r,e)))}),r}function EA(r){return _i(r)&&!(r.length%2)||bo(r)}function H1(r){return typeof r=="number"&&r==r&&r%1===0}function bo(r){if(r==null)return!1;if(r.constructor===Uint8Array)return!0;if(typeof r=="string"||!H1(r.length)||r.length<0)return!1;for(let e=0;e=256)return!1}return!0}function ir(r,e){if(e||(e={}),typeof r=="number"){cr.checkSafeUint53(r,"invalid arrayify value");const t=[];for(;r;)t.unshift(r&255),r=parseInt(String(r/256));return t.length===0&&t.push(0),eo(new Uint8Array(t))}if(e.allowMissingPrefix&&typeof r=="string"&&r.substring(0,2)!=="0x"&&(r="0x"+r),Lb(r)&&(r=r.toHexString()),_i(r)){let t=r.substring(2);t.length%2&&(e.hexPad==="left"?t="0"+t:e.hexPad==="right"?t+="0":cr.throwArgumentError("hex data is odd-length","value",r));const i=[];for(let n=0;nir(n)),t=e.reduce((n,a)=>n+a.length,0),i=new Uint8Array(t);return e.reduce((n,a)=>(i.set(a,n),n+a.length),0),eo(i)}function SA(r,e){r=ir(r),r.length>e&&cr.throwArgumentError("value out of range","value",arguments[0]);const t=new Uint8Array(e);return t.set(r,e-r.length),eo(t)}function _i(r,e){return!(typeof r!="string"||!r.match(/^0x[0-9A-Fa-f]*$/)||e&&r.length!==2+2*e)}const ml="0123456789abcdef";function ci(r,e){if(e||(e={}),typeof r=="number"){cr.checkSafeUint53(r,"invalid hexlify value");let t="";for(;r;)t=ml[r&15]+t,r=Math.floor(r/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if(typeof r=="bigint")return r=r.toString(16),r.length%2?"0x0"+r:"0x"+r;if(e.allowMissingPrefix&&typeof r=="string"&&r.substring(0,2)!=="0x"&&(r="0x"+r),Lb(r))return r.toHexString();if(_i(r))return r.length%2&&(e.hexPad==="left"?r="0x0"+r.substring(2):e.hexPad==="right"?r+="0":cr.throwArgumentError("hex data is odd-length","value",r)),r.toLowerCase();if(bo(r)){let t="0x";for(let i=0;i>4]+ml[n&15]}return t}return cr.throwArgumentError("invalid hexlify value","value",r)}function IA(r){if(typeof r!="string")r=ci(r);else if(!_i(r)||r.length%2)return null;return(r.length-2)/2}function K1(r,e,t){return typeof r!="string"?r=ci(r):(!_i(r)||r.length%2)&&cr.throwArgumentError("invalid hexData","value",r),e=2+2*e,t!=null?"0x"+r.substring(e,2+2*t):"0x"+r.substring(e)}function Dn(r,e){for(typeof r!="string"?r=ci(r):_i(r)||cr.throwArgumentError("invalid hex string","value",r),r.length>2*e+2&&cr.throwArgumentError("value out of range","value",arguments[1]);r.length<2*e+2;)r="0x0"+r.substring(2);return r}function Ub(r){const e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(EA(r)){let t=ir(r);t.length===64?(e.v=27+(t[32]>>7),t[32]&=127,e.r=ci(t.slice(0,32)),e.s=ci(t.slice(32,64))):t.length===65?(e.r=ci(t.slice(0,32)),e.s=ci(t.slice(32,64)),e.v=t[64]):cr.throwArgumentError("invalid signature string","signature",r),e.v<27&&(e.v===0||e.v===1?e.v+=27:cr.throwArgumentError("signature invalid v byte","signature",r)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(t[32]|=128),e._vs=ci(t.slice(32,64))}else{if(e.r=r.r,e.s=r.s,e.v=r.v,e.recoveryParam=r.recoveryParam,e._vs=r._vs,e._vs!=null){const n=SA(ir(e._vs),32);e._vs=ci(n);const a=n[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=a:e.recoveryParam!==a&&cr.throwArgumentError("signature recoveryParam mismatch _vs","signature",r),n[0]&=127;const f=ci(n);e.s==null?e.s=f:e.s!==f&&cr.throwArgumentError("signature v mismatch _vs","signature",r)}if(e.recoveryParam==null)e.v==null?cr.throwArgumentError("signature missing v and recoveryParam","signature",r):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{const n=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==n&&cr.throwArgumentError("signature recoveryParam mismatch v","signature",r)}e.r==null||!_i(e.r)?cr.throwArgumentError("signature missing or invalid r","signature",r):e.r=Dn(e.r,32),e.s==null||!_i(e.s)?cr.throwArgumentError("signature missing or invalid s","signature",r):e.s=Dn(e.s,32);const t=ir(e.s);t[0]>=128&&cr.throwArgumentError("signature s out of range","signature",r),e.recoveryParam&&(t[0]|=128);const i=ci(t);e._vs&&(_i(e._vs)||cr.throwArgumentError("signature invalid _vs","signature",r),e._vs=Dn(e._vs,32)),e._vs==null?e._vs=i:e._vs!==i&&cr.throwArgumentError("signature _vs mismatch v and s","signature",r)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function j0(r){return"0x"+yA.keccak_256(ir(r))}var $b={exports:{}},MA={},PA=Object.freeze({__proto__:null,default:MA}),OA=mA(PA);(function(r){(function(e,t){function i(c,h){if(!c)throw new Error(h||"Assertion failed")}function n(c,h){c.super_=h;var v=function(){};v.prototype=h.prototype,c.prototype=new v,c.prototype.constructor=c}function a(c,h,v){if(a.isBN(c))return c;this.negative=0,this.words=null,this.length=0,this.red=null,c!==null&&((h==="le"||h==="be")&&(v=h,h=10),this._init(c||0,h||10,v||"be"))}typeof e=="object"?e.exports=a:t.BN=a,a.BN=a,a.wordSize=26;var f;try{typeof window<"u"&&typeof window.Buffer<"u"?f=window.Buffer:f=OA.Buffer}catch{}a.isBN=function(c){return c instanceof a?!0:c!==null&&typeof c=="object"&&c.constructor.wordSize===a.wordSize&&Array.isArray(c.words)},a.max=function(c,h){return c.cmp(h)>0?c:h},a.min=function(c,h){return c.cmp(h)<0?c:h},a.prototype._init=function(c,h,v){if(typeof c=="number")return this._initNumber(c,h,v);if(typeof c=="object")return this._initArray(c,h,v);h==="hex"&&(h=16),i(h===(h|0)&&h>=2&&h<=36),c=c.toString().replace(/\s+/g,"");var _=0;c[0]==="-"&&(_++,this.negative=1),_=0;_-=3)M=c[_]|c[_-1]<<8|c[_-2]<<16,this.words[I]|=M<>>26-S&67108863,S+=24,S>=26&&(S-=26,I++);else if(v==="le")for(_=0,I=0;_>>26-S&67108863,S+=24,S>=26&&(S-=26,I++);return this._strip()};function u(c,h){var v=c.charCodeAt(h);if(v>=48&&v<=57)return v-48;if(v>=65&&v<=70)return v-55;if(v>=97&&v<=102)return v-87;i(!1,"Invalid character in "+c)}function b(c,h,v){var _=u(c,v);return v-1>=h&&(_|=u(c,v-1)<<4),_}a.prototype._parseHex=function(c,h,v){this.length=Math.ceil((c.length-h)/6),this.words=new Array(this.length);for(var _=0;_=h;_-=2)S=b(c,h,_)<=18?(I-=18,M+=1,this.words[M]|=S>>>26):I+=8;else{var d=c.length-h;for(_=d%2===0?h+1:h;_=18?(I-=18,M+=1,this.words[M]|=S>>>26):I+=8}this._strip()};function p(c,h,v,_){for(var I=0,M=0,S=Math.min(c.length,v),d=h;d=49?M=g-49+10:g>=17?M=g-17+10:M=g,i(g>=0&&M<_,"Invalid character"),I+=M}return I}a.prototype._parseBase=function(c,h,v){this.words=[0],this.length=1;for(var _=0,I=1;I<=67108863;I*=h)_++;_--,I=I/h|0;for(var M=c.length-v,S=M%_,d=Math.min(M,M-S)+v,g=0,T=v;T1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},a.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{a.prototype[Symbol.for("nodejs.util.inspect.custom")]=A}catch{a.prototype.inspect=A}else a.prototype.inspect=A;function A(){return(this.red?""}var R=["","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"],O=[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],N=[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];a.prototype.toString=function(c,h){c=c||10,h=h|0||1;var v;if(c===16||c==="hex"){v="";for(var _=0,I=0,M=0;M>>24-_&16777215,_+=2,_>=26&&(_-=26,M--),I!==0||M!==this.length-1?v=R[6-d.length]+d+v:v=d+v}for(I!==0&&(v=I.toString(16)+v);v.length%h!==0;)v="0"+v;return this.negative!==0&&(v="-"+v),v}if(c===(c|0)&&c>=2&&c<=36){var g=O[c],T=N[c];v="";var Z=this.clone();for(Z.negative=0;!Z.isZero();){var se=Z.modrn(T).toString(c);Z=Z.idivn(T),Z.isZero()?v=se+v:v=R[g-se.length]+se+v}for(this.isZero()&&(v="0"+v);v.length%h!==0;)v="0"+v;return this.negative!==0&&(v="-"+v),v}i(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var c=this.words[0];return this.length===2?c+=this.words[1]*67108864:this.length===3&&this.words[2]===1?c+=4503599627370496+this.words[1]*67108864:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-c:c},a.prototype.toJSON=function(){return this.toString(16,2)},f&&(a.prototype.toBuffer=function(c,h){return this.toArrayLike(f,c,h)}),a.prototype.toArray=function(c,h){return this.toArrayLike(Array,c,h)};var K=function(c,h){return c.allocUnsafe?c.allocUnsafe(h):new c(h)};a.prototype.toArrayLike=function(c,h,v){this._strip();var _=this.byteLength(),I=v||Math.max(1,_);i(_<=I,"byte array longer than desired length"),i(I>0,"Requested array length <= 0");var M=K(c,I),S=h==="le"?"LE":"BE";return this["_toArrayLike"+S](M,_),M},a.prototype._toArrayLikeLE=function(c,h){for(var v=0,_=0,I=0,M=0;I>8&255),v>16&255),M===6?(v>24&255),_=0,M=0):(_=S>>>24,M+=2)}if(v=0&&(c[v--]=S>>8&255),v>=0&&(c[v--]=S>>16&255),M===6?(v>=0&&(c[v--]=S>>24&255),_=0,M=0):(_=S>>>24,M+=2)}if(v>=0)for(c[v--]=_;v>=0;)c[v--]=0},Math.clz32?a.prototype._countBits=function(c){return 32-Math.clz32(c)}:a.prototype._countBits=function(c){var h=c,v=0;return h>=4096&&(v+=13,h>>>=13),h>=64&&(v+=7,h>>>=7),h>=8&&(v+=4,h>>>=4),h>=2&&(v+=2,h>>>=2),v+h},a.prototype._zeroBits=function(c){if(c===0)return 26;var h=c,v=0;return h&8191||(v+=13,h>>>=13),h&127||(v+=7,h>>>=7),h&15||(v+=4,h>>>=4),h&3||(v+=2,h>>>=2),h&1||v++,v},a.prototype.bitLength=function(){var c=this.words[this.length-1],h=this._countBits(c);return(this.length-1)*26+h};function W(c){for(var h=new Array(c.bitLength()),v=0;v>>I&1}return h}a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var c=0,h=0;hc.length?this.clone().ior(c):c.clone().ior(this)},a.prototype.uor=function(c){return this.length>c.length?this.clone().iuor(c):c.clone().iuor(this)},a.prototype.iuand=function(c){var h;this.length>c.length?h=c:h=this;for(var v=0;vc.length?this.clone().iand(c):c.clone().iand(this)},a.prototype.uand=function(c){return this.length>c.length?this.clone().iuand(c):c.clone().iuand(this)},a.prototype.iuxor=function(c){var h,v;this.length>c.length?(h=this,v=c):(h=c,v=this);for(var _=0;_c.length?this.clone().ixor(c):c.clone().ixor(this)},a.prototype.uxor=function(c){return this.length>c.length?this.clone().iuxor(c):c.clone().iuxor(this)},a.prototype.inotn=function(c){i(typeof c=="number"&&c>=0);var h=Math.ceil(c/26)|0,v=c%26;this._expand(h),v>0&&h--;for(var _=0;_0&&(this.words[_]=~this.words[_]&67108863>>26-v),this._strip()},a.prototype.notn=function(c){return this.clone().inotn(c)},a.prototype.setn=function(c,h){i(typeof c=="number"&&c>=0);var v=c/26|0,_=c%26;return this._expand(v+1),h?this.words[v]=this.words[v]|1<<_:this.words[v]=this.words[v]&~(1<<_),this._strip()},a.prototype.iadd=function(c){var h;if(this.negative!==0&&c.negative===0)return this.negative=0,h=this.isub(c),this.negative^=1,this._normSign();if(this.negative===0&&c.negative!==0)return c.negative=0,h=this.isub(c),c.negative=1,h._normSign();var v,_;this.length>c.length?(v=this,_=c):(v=c,_=this);for(var I=0,M=0;M<_.length;M++)h=(v.words[M]|0)+(_.words[M]|0)+I,this.words[M]=h&67108863,I=h>>>26;for(;I!==0&&M>>26;if(this.length=v.length,I!==0)this.words[this.length]=I,this.length++;else if(v!==this)for(;Mc.length?this.clone().iadd(c):c.clone().iadd(this)},a.prototype.isub=function(c){if(c.negative!==0){c.negative=0;var h=this.iadd(c);return c.negative=1,h._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(c),this.negative=1,this._normSign();var v=this.cmp(c);if(v===0)return this.negative=0,this.length=1,this.words[0]=0,this;var _,I;v>0?(_=this,I=c):(_=c,I=this);for(var M=0,S=0;S>26,this.words[S]=h&67108863;for(;M!==0&&S<_.length;S++)h=(_.words[S]|0)+M,M=h>>26,this.words[S]=h&67108863;if(M===0&&S<_.length&&_!==this)for(;S<_.length;S++)this.words[S]=_.words[S];return this.length=Math.max(this.length,S),_!==this&&(this.negative=1),this._strip()},a.prototype.sub=function(c){return this.clone().isub(c)};function Q(c,h,v){v.negative=h.negative^c.negative;var _=c.length+h.length|0;v.length=_,_=_-1|0;var I=c.words[0]|0,M=h.words[0]|0,S=I*M,d=S&67108863,g=S/67108864|0;v.words[0]=d;for(var T=1;T<_;T++){for(var Z=g>>>26,se=g&67108863,P=Math.min(T,h.length-1),ee=Math.max(0,T-c.length+1);ee<=P;ee++){var q=T-ee|0;I=c.words[q]|0,M=h.words[ee]|0,S=I*M+se,Z+=S/67108864|0,se=S&67108863}v.words[T]=se|0,g=Z|0}return g!==0?v.words[T]=g|0:v.length--,v._strip()}var j=function(c,h,v){var _=c.words,I=h.words,M=v.words,S=0,d,g,T,Z=_[0]|0,se=Z&8191,P=Z>>>13,ee=_[1]|0,q=ee&8191,z=ee>>>13,H=_[2]|0,w=H&8191,$=H>>>13,ne=_[3]|0,ce=ne&8191,he=ne>>>13,ye=_[4]|0,we=ye&8191,Ce=ye>>>13,Qe=_[5]|0,Oe=Qe&8191,Te=Qe>>>13,Ie=_[6]|0,me=Ie&8191,Re=Ie>>>13,De=_[7]|0,ve=De&8191,Ne=De>>>13,Se=_[8]|0,be=Se&8191,Le=Se>>>13,Me=_[9]|0,_e=Me&8191,He=Me>>>13,Ve=I[0]|0,Ee=Ve&8191,Ke=Ve>>>13,ut=I[1]|0,Ge=ut&8191,_t=ut>>>13,lt=I[2]|0,Je=lt&8191,Et=lt>>>13,It=I[3]|0,Fe=It&8191,Xe=It>>>13,tt=I[4]|0,Be=tt&8191,et=tt>>>13,Ze=I[5]|0,$e=Ze&8191,ft=Ze>>>13,rt=I[6]|0,ze=rt&8191,it=rt>>>13,st=I[7]|0,qe=st&8191,Ye=st>>>13,ht=I[8]|0,je=ht&8191,Tt=ht>>>13,Dt=I[9]|0,at=Dt&8191,bt=Dt>>>13;v.negative=c.negative^h.negative,v.length=19,d=Math.imul(se,Ee),g=Math.imul(se,Ke),g=g+Math.imul(P,Ee)|0,T=Math.imul(P,Ke);var Cr=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Cr>>>26)|0,Cr&=67108863,d=Math.imul(q,Ee),g=Math.imul(q,Ke),g=g+Math.imul(z,Ee)|0,T=Math.imul(z,Ke),d=d+Math.imul(se,Ge)|0,g=g+Math.imul(se,_t)|0,g=g+Math.imul(P,Ge)|0,T=T+Math.imul(P,_t)|0;var Tr=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Tr>>>26)|0,Tr&=67108863,d=Math.imul(w,Ee),g=Math.imul(w,Ke),g=g+Math.imul($,Ee)|0,T=Math.imul($,Ke),d=d+Math.imul(q,Ge)|0,g=g+Math.imul(q,_t)|0,g=g+Math.imul(z,Ge)|0,T=T+Math.imul(z,_t)|0,d=d+Math.imul(se,Je)|0,g=g+Math.imul(se,Et)|0,g=g+Math.imul(P,Je)|0,T=T+Math.imul(P,Et)|0;var Dr=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Dr>>>26)|0,Dr&=67108863,d=Math.imul(ce,Ee),g=Math.imul(ce,Ke),g=g+Math.imul(he,Ee)|0,T=Math.imul(he,Ke),d=d+Math.imul(w,Ge)|0,g=g+Math.imul(w,_t)|0,g=g+Math.imul($,Ge)|0,T=T+Math.imul($,_t)|0,d=d+Math.imul(q,Je)|0,g=g+Math.imul(q,Et)|0,g=g+Math.imul(z,Je)|0,T=T+Math.imul(z,Et)|0,d=d+Math.imul(se,Fe)|0,g=g+Math.imul(se,Xe)|0,g=g+Math.imul(P,Fe)|0,T=T+Math.imul(P,Xe)|0;var Fr=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Fr>>>26)|0,Fr&=67108863,d=Math.imul(we,Ee),g=Math.imul(we,Ke),g=g+Math.imul(Ce,Ee)|0,T=Math.imul(Ce,Ke),d=d+Math.imul(ce,Ge)|0,g=g+Math.imul(ce,_t)|0,g=g+Math.imul(he,Ge)|0,T=T+Math.imul(he,_t)|0,d=d+Math.imul(w,Je)|0,g=g+Math.imul(w,Et)|0,g=g+Math.imul($,Je)|0,T=T+Math.imul($,Et)|0,d=d+Math.imul(q,Fe)|0,g=g+Math.imul(q,Xe)|0,g=g+Math.imul(z,Fe)|0,T=T+Math.imul(z,Xe)|0,d=d+Math.imul(se,Be)|0,g=g+Math.imul(se,et)|0,g=g+Math.imul(P,Be)|0,T=T+Math.imul(P,et)|0;var Br=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Br>>>26)|0,Br&=67108863,d=Math.imul(Oe,Ee),g=Math.imul(Oe,Ke),g=g+Math.imul(Te,Ee)|0,T=Math.imul(Te,Ke),d=d+Math.imul(we,Ge)|0,g=g+Math.imul(we,_t)|0,g=g+Math.imul(Ce,Ge)|0,T=T+Math.imul(Ce,_t)|0,d=d+Math.imul(ce,Je)|0,g=g+Math.imul(ce,Et)|0,g=g+Math.imul(he,Je)|0,T=T+Math.imul(he,Et)|0,d=d+Math.imul(w,Fe)|0,g=g+Math.imul(w,Xe)|0,g=g+Math.imul($,Fe)|0,T=T+Math.imul($,Xe)|0,d=d+Math.imul(q,Be)|0,g=g+Math.imul(q,et)|0,g=g+Math.imul(z,Be)|0,T=T+Math.imul(z,et)|0,d=d+Math.imul(se,$e)|0,g=g+Math.imul(se,ft)|0,g=g+Math.imul(P,$e)|0,T=T+Math.imul(P,ft)|0;var er=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(er>>>26)|0,er&=67108863,d=Math.imul(me,Ee),g=Math.imul(me,Ke),g=g+Math.imul(Re,Ee)|0,T=Math.imul(Re,Ke),d=d+Math.imul(Oe,Ge)|0,g=g+Math.imul(Oe,_t)|0,g=g+Math.imul(Te,Ge)|0,T=T+Math.imul(Te,_t)|0,d=d+Math.imul(we,Je)|0,g=g+Math.imul(we,Et)|0,g=g+Math.imul(Ce,Je)|0,T=T+Math.imul(Ce,Et)|0,d=d+Math.imul(ce,Fe)|0,g=g+Math.imul(ce,Xe)|0,g=g+Math.imul(he,Fe)|0,T=T+Math.imul(he,Xe)|0,d=d+Math.imul(w,Be)|0,g=g+Math.imul(w,et)|0,g=g+Math.imul($,Be)|0,T=T+Math.imul($,et)|0,d=d+Math.imul(q,$e)|0,g=g+Math.imul(q,ft)|0,g=g+Math.imul(z,$e)|0,T=T+Math.imul(z,ft)|0,d=d+Math.imul(se,ze)|0,g=g+Math.imul(se,it)|0,g=g+Math.imul(P,ze)|0,T=T+Math.imul(P,it)|0;var Qr=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Qr>>>26)|0,Qr&=67108863,d=Math.imul(ve,Ee),g=Math.imul(ve,Ke),g=g+Math.imul(Ne,Ee)|0,T=Math.imul(Ne,Ke),d=d+Math.imul(me,Ge)|0,g=g+Math.imul(me,_t)|0,g=g+Math.imul(Re,Ge)|0,T=T+Math.imul(Re,_t)|0,d=d+Math.imul(Oe,Je)|0,g=g+Math.imul(Oe,Et)|0,g=g+Math.imul(Te,Je)|0,T=T+Math.imul(Te,Et)|0,d=d+Math.imul(we,Fe)|0,g=g+Math.imul(we,Xe)|0,g=g+Math.imul(Ce,Fe)|0,T=T+Math.imul(Ce,Xe)|0,d=d+Math.imul(ce,Be)|0,g=g+Math.imul(ce,et)|0,g=g+Math.imul(he,Be)|0,T=T+Math.imul(he,et)|0,d=d+Math.imul(w,$e)|0,g=g+Math.imul(w,ft)|0,g=g+Math.imul($,$e)|0,T=T+Math.imul($,ft)|0,d=d+Math.imul(q,ze)|0,g=g+Math.imul(q,it)|0,g=g+Math.imul(z,ze)|0,T=T+Math.imul(z,it)|0,d=d+Math.imul(se,qe)|0,g=g+Math.imul(se,Ye)|0,g=g+Math.imul(P,qe)|0,T=T+Math.imul(P,Ye)|0;var Gi=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Gi>>>26)|0,Gi&=67108863,d=Math.imul(be,Ee),g=Math.imul(be,Ke),g=g+Math.imul(Le,Ee)|0,T=Math.imul(Le,Ke),d=d+Math.imul(ve,Ge)|0,g=g+Math.imul(ve,_t)|0,g=g+Math.imul(Ne,Ge)|0,T=T+Math.imul(Ne,_t)|0,d=d+Math.imul(me,Je)|0,g=g+Math.imul(me,Et)|0,g=g+Math.imul(Re,Je)|0,T=T+Math.imul(Re,Et)|0,d=d+Math.imul(Oe,Fe)|0,g=g+Math.imul(Oe,Xe)|0,g=g+Math.imul(Te,Fe)|0,T=T+Math.imul(Te,Xe)|0,d=d+Math.imul(we,Be)|0,g=g+Math.imul(we,et)|0,g=g+Math.imul(Ce,Be)|0,T=T+Math.imul(Ce,et)|0,d=d+Math.imul(ce,$e)|0,g=g+Math.imul(ce,ft)|0,g=g+Math.imul(he,$e)|0,T=T+Math.imul(he,ft)|0,d=d+Math.imul(w,ze)|0,g=g+Math.imul(w,it)|0,g=g+Math.imul($,ze)|0,T=T+Math.imul($,it)|0,d=d+Math.imul(q,qe)|0,g=g+Math.imul(q,Ye)|0,g=g+Math.imul(z,qe)|0,T=T+Math.imul(z,Ye)|0,d=d+Math.imul(se,je)|0,g=g+Math.imul(se,Tt)|0,g=g+Math.imul(P,je)|0,T=T+Math.imul(P,Tt)|0;var Xr=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,d=Math.imul(_e,Ee),g=Math.imul(_e,Ke),g=g+Math.imul(He,Ee)|0,T=Math.imul(He,Ke),d=d+Math.imul(be,Ge)|0,g=g+Math.imul(be,_t)|0,g=g+Math.imul(Le,Ge)|0,T=T+Math.imul(Le,_t)|0,d=d+Math.imul(ve,Je)|0,g=g+Math.imul(ve,Et)|0,g=g+Math.imul(Ne,Je)|0,T=T+Math.imul(Ne,Et)|0,d=d+Math.imul(me,Fe)|0,g=g+Math.imul(me,Xe)|0,g=g+Math.imul(Re,Fe)|0,T=T+Math.imul(Re,Xe)|0,d=d+Math.imul(Oe,Be)|0,g=g+Math.imul(Oe,et)|0,g=g+Math.imul(Te,Be)|0,T=T+Math.imul(Te,et)|0,d=d+Math.imul(we,$e)|0,g=g+Math.imul(we,ft)|0,g=g+Math.imul(Ce,$e)|0,T=T+Math.imul(Ce,ft)|0,d=d+Math.imul(ce,ze)|0,g=g+Math.imul(ce,it)|0,g=g+Math.imul(he,ze)|0,T=T+Math.imul(he,it)|0,d=d+Math.imul(w,qe)|0,g=g+Math.imul(w,Ye)|0,g=g+Math.imul($,qe)|0,T=T+Math.imul($,Ye)|0,d=d+Math.imul(q,je)|0,g=g+Math.imul(q,Tt)|0,g=g+Math.imul(z,je)|0,T=T+Math.imul(z,Tt)|0,d=d+Math.imul(se,at)|0,g=g+Math.imul(se,bt)|0,g=g+Math.imul(P,at)|0,T=T+Math.imul(P,bt)|0;var Wi=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Wi>>>26)|0,Wi&=67108863,d=Math.imul(_e,Ge),g=Math.imul(_e,_t),g=g+Math.imul(He,Ge)|0,T=Math.imul(He,_t),d=d+Math.imul(be,Je)|0,g=g+Math.imul(be,Et)|0,g=g+Math.imul(Le,Je)|0,T=T+Math.imul(Le,Et)|0,d=d+Math.imul(ve,Fe)|0,g=g+Math.imul(ve,Xe)|0,g=g+Math.imul(Ne,Fe)|0,T=T+Math.imul(Ne,Xe)|0,d=d+Math.imul(me,Be)|0,g=g+Math.imul(me,et)|0,g=g+Math.imul(Re,Be)|0,T=T+Math.imul(Re,et)|0,d=d+Math.imul(Oe,$e)|0,g=g+Math.imul(Oe,ft)|0,g=g+Math.imul(Te,$e)|0,T=T+Math.imul(Te,ft)|0,d=d+Math.imul(we,ze)|0,g=g+Math.imul(we,it)|0,g=g+Math.imul(Ce,ze)|0,T=T+Math.imul(Ce,it)|0,d=d+Math.imul(ce,qe)|0,g=g+Math.imul(ce,Ye)|0,g=g+Math.imul(he,qe)|0,T=T+Math.imul(he,Ye)|0,d=d+Math.imul(w,je)|0,g=g+Math.imul(w,Tt)|0,g=g+Math.imul($,je)|0,T=T+Math.imul($,Tt)|0,d=d+Math.imul(q,at)|0,g=g+Math.imul(q,bt)|0,g=g+Math.imul(z,at)|0,T=T+Math.imul(z,bt)|0;var Ji=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Ji>>>26)|0,Ji&=67108863,d=Math.imul(_e,Je),g=Math.imul(_e,Et),g=g+Math.imul(He,Je)|0,T=Math.imul(He,Et),d=d+Math.imul(be,Fe)|0,g=g+Math.imul(be,Xe)|0,g=g+Math.imul(Le,Fe)|0,T=T+Math.imul(Le,Xe)|0,d=d+Math.imul(ve,Be)|0,g=g+Math.imul(ve,et)|0,g=g+Math.imul(Ne,Be)|0,T=T+Math.imul(Ne,et)|0,d=d+Math.imul(me,$e)|0,g=g+Math.imul(me,ft)|0,g=g+Math.imul(Re,$e)|0,T=T+Math.imul(Re,ft)|0,d=d+Math.imul(Oe,ze)|0,g=g+Math.imul(Oe,it)|0,g=g+Math.imul(Te,ze)|0,T=T+Math.imul(Te,it)|0,d=d+Math.imul(we,qe)|0,g=g+Math.imul(we,Ye)|0,g=g+Math.imul(Ce,qe)|0,T=T+Math.imul(Ce,Ye)|0,d=d+Math.imul(ce,je)|0,g=g+Math.imul(ce,Tt)|0,g=g+Math.imul(he,je)|0,T=T+Math.imul(he,Tt)|0,d=d+Math.imul(w,at)|0,g=g+Math.imul(w,bt)|0,g=g+Math.imul($,at)|0,T=T+Math.imul($,bt)|0;var Zr=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Zr>>>26)|0,Zr&=67108863,d=Math.imul(_e,Fe),g=Math.imul(_e,Xe),g=g+Math.imul(He,Fe)|0,T=Math.imul(He,Xe),d=d+Math.imul(be,Be)|0,g=g+Math.imul(be,et)|0,g=g+Math.imul(Le,Be)|0,T=T+Math.imul(Le,et)|0,d=d+Math.imul(ve,$e)|0,g=g+Math.imul(ve,ft)|0,g=g+Math.imul(Ne,$e)|0,T=T+Math.imul(Ne,ft)|0,d=d+Math.imul(me,ze)|0,g=g+Math.imul(me,it)|0,g=g+Math.imul(Re,ze)|0,T=T+Math.imul(Re,it)|0,d=d+Math.imul(Oe,qe)|0,g=g+Math.imul(Oe,Ye)|0,g=g+Math.imul(Te,qe)|0,T=T+Math.imul(Te,Ye)|0,d=d+Math.imul(we,je)|0,g=g+Math.imul(we,Tt)|0,g=g+Math.imul(Ce,je)|0,T=T+Math.imul(Ce,Tt)|0,d=d+Math.imul(ce,at)|0,g=g+Math.imul(ce,bt)|0,g=g+Math.imul(he,at)|0,T=T+Math.imul(he,bt)|0;var Si=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Si>>>26)|0,Si&=67108863,d=Math.imul(_e,Be),g=Math.imul(_e,et),g=g+Math.imul(He,Be)|0,T=Math.imul(He,et),d=d+Math.imul(be,$e)|0,g=g+Math.imul(be,ft)|0,g=g+Math.imul(Le,$e)|0,T=T+Math.imul(Le,ft)|0,d=d+Math.imul(ve,ze)|0,g=g+Math.imul(ve,it)|0,g=g+Math.imul(Ne,ze)|0,T=T+Math.imul(Ne,it)|0,d=d+Math.imul(me,qe)|0,g=g+Math.imul(me,Ye)|0,g=g+Math.imul(Re,qe)|0,T=T+Math.imul(Re,Ye)|0,d=d+Math.imul(Oe,je)|0,g=g+Math.imul(Oe,Tt)|0,g=g+Math.imul(Te,je)|0,T=T+Math.imul(Te,Tt)|0,d=d+Math.imul(we,at)|0,g=g+Math.imul(we,bt)|0,g=g+Math.imul(Ce,at)|0,T=T+Math.imul(Ce,bt)|0;var Ii=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Ii>>>26)|0,Ii&=67108863,d=Math.imul(_e,$e),g=Math.imul(_e,ft),g=g+Math.imul(He,$e)|0,T=Math.imul(He,ft),d=d+Math.imul(be,ze)|0,g=g+Math.imul(be,it)|0,g=g+Math.imul(Le,ze)|0,T=T+Math.imul(Le,it)|0,d=d+Math.imul(ve,qe)|0,g=g+Math.imul(ve,Ye)|0,g=g+Math.imul(Ne,qe)|0,T=T+Math.imul(Ne,Ye)|0,d=d+Math.imul(me,je)|0,g=g+Math.imul(me,Tt)|0,g=g+Math.imul(Re,je)|0,T=T+Math.imul(Re,Tt)|0,d=d+Math.imul(Oe,at)|0,g=g+Math.imul(Oe,bt)|0,g=g+Math.imul(Te,at)|0,T=T+Math.imul(Te,bt)|0;var lr=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(lr>>>26)|0,lr&=67108863,d=Math.imul(_e,ze),g=Math.imul(_e,it),g=g+Math.imul(He,ze)|0,T=Math.imul(He,it),d=d+Math.imul(be,qe)|0,g=g+Math.imul(be,Ye)|0,g=g+Math.imul(Le,qe)|0,T=T+Math.imul(Le,Ye)|0,d=d+Math.imul(ve,je)|0,g=g+Math.imul(ve,Tt)|0,g=g+Math.imul(Ne,je)|0,T=T+Math.imul(Ne,Tt)|0,d=d+Math.imul(me,at)|0,g=g+Math.imul(me,bt)|0,g=g+Math.imul(Re,at)|0,T=T+Math.imul(Re,bt)|0;var Yi=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Yi>>>26)|0,Yi&=67108863,d=Math.imul(_e,qe),g=Math.imul(_e,Ye),g=g+Math.imul(He,qe)|0,T=Math.imul(He,Ye),d=d+Math.imul(be,je)|0,g=g+Math.imul(be,Tt)|0,g=g+Math.imul(Le,je)|0,T=T+Math.imul(Le,Tt)|0,d=d+Math.imul(ve,at)|0,g=g+Math.imul(ve,bt)|0,g=g+Math.imul(Ne,at)|0,T=T+Math.imul(Ne,bt)|0;var Qi=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Qi>>>26)|0,Qi&=67108863,d=Math.imul(_e,je),g=Math.imul(_e,Tt),g=g+Math.imul(He,je)|0,T=Math.imul(He,Tt),d=d+Math.imul(be,at)|0,g=g+Math.imul(be,bt)|0,g=g+Math.imul(Le,at)|0,T=T+Math.imul(Le,bt)|0;var Xi=(S+d|0)+((g&8191)<<13)|0;S=(T+(g>>>13)|0)+(Xi>>>26)|0,Xi&=67108863,d=Math.imul(_e,at),g=Math.imul(_e,bt),g=g+Math.imul(He,at)|0,T=Math.imul(He,bt);var js=(S+d|0)+((g&8191)<<13)|0;return S=(T+(g>>>13)|0)+(js>>>26)|0,js&=67108863,M[0]=Cr,M[1]=Tr,M[2]=Dr,M[3]=Fr,M[4]=Br,M[5]=er,M[6]=Qr,M[7]=Gi,M[8]=Xr,M[9]=Wi,M[10]=Ji,M[11]=Zr,M[12]=Si,M[13]=Ii,M[14]=lr,M[15]=Yi,M[16]=Qi,M[17]=Xi,M[18]=js,S!==0&&(M[19]=S,v.length++),v};Math.imul||(j=Q);function Y(c,h,v){v.negative=h.negative^c.negative,v.length=c.length+h.length;for(var _=0,I=0,M=0;M>>26)|0,I+=S>>>26,S&=67108863}v.words[M]=d,_=S,S=I}return _!==0?v.words[M]=_:v.length--,v._strip()}function U(c,h,v){return Y(c,h,v)}a.prototype.mulTo=function(c,h){var v,_=this.length+c.length;return this.length===10&&c.length===10?v=j(this,c,h):_<63?v=Q(this,c,h):_<1024?v=Y(this,c,h):v=U(this,c,h),v},a.prototype.mul=function(c){var h=new a(null);return h.words=new Array(this.length+c.length),this.mulTo(c,h)},a.prototype.mulf=function(c){var h=new a(null);return h.words=new Array(this.length+c.length),U(this,c,h)},a.prototype.imul=function(c){return this.clone().mulTo(c,this)},a.prototype.imuln=function(c){var h=c<0;h&&(c=-c),i(typeof c=="number"),i(c<67108864);for(var v=0,_=0;_>=26,v+=I/67108864|0,v+=M>>>26,this.words[_]=M&67108863}return v!==0&&(this.words[_]=v,this.length++),h?this.ineg():this},a.prototype.muln=function(c){return this.clone().imuln(c)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(c){var h=W(c);if(h.length===0)return new a(1);for(var v=this,_=0;_=0);var h=c%26,v=(c-h)/26,_=67108863>>>26-h<<26-h,I;if(h!==0){var M=0;for(I=0;I>>26-h}M&&(this.words[I]=M,this.length++)}if(v!==0){for(I=this.length-1;I>=0;I--)this.words[I+v]=this.words[I];for(I=0;I=0);var _;h?_=(h-h%26)/26:_=0;var I=c%26,M=Math.min((c-I)/26,this.length),S=67108863^67108863>>>I<M)for(this.length-=M,g=0;g=0&&(T!==0||g>=_);g--){var Z=this.words[g]|0;this.words[g]=T<<26-I|Z>>>I,T=Z&S}return d&&T!==0&&(d.words[d.length++]=T),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},a.prototype.ishrn=function(c,h,v){return i(this.negative===0),this.iushrn(c,h,v)},a.prototype.shln=function(c){return this.clone().ishln(c)},a.prototype.ushln=function(c){return this.clone().iushln(c)},a.prototype.shrn=function(c){return this.clone().ishrn(c)},a.prototype.ushrn=function(c){return this.clone().iushrn(c)},a.prototype.testn=function(c){i(typeof c=="number"&&c>=0);var h=c%26,v=(c-h)/26,_=1<=0);var h=c%26,v=(c-h)/26;if(i(this.negative===0,"imaskn works only with positive numbers"),this.length<=v)return this;if(h!==0&&v++,this.length=Math.min(v,this.length),h!==0){var _=67108863^67108863>>>h<=67108864;h++)this.words[h]-=67108864,h===this.length-1?this.words[h+1]=1:this.words[h+1]++;return this.length=Math.max(this.length,h+1),this},a.prototype.isubn=function(c){if(i(typeof c=="number"),i(c<67108864),c<0)return this.iaddn(-c);if(this.negative!==0)return this.negative=0,this.iaddn(c),this.negative=1,this;if(this.words[0]-=c,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var h=0;h>26)-(d/67108864|0),this.words[I+v]=M&67108863}for(;I>26,this.words[I+v]=M&67108863;if(S===0)return this._strip();for(i(S===-1),S=0,I=0;I>26,this.words[I]=M&67108863;return this.negative=1,this._strip()},a.prototype._wordDiv=function(c,h){var v=this.length-c.length,_=this.clone(),I=c,M=I.words[I.length-1]|0,S=this._countBits(M);v=26-S,v!==0&&(I=I.ushln(v),_.iushln(v),M=I.words[I.length-1]|0);var d=_.length-I.length,g;if(h!=="mod"){g=new a(null),g.length=d+1,g.words=new Array(g.length);for(var T=0;T=0;se--){var P=(_.words[I.length+se]|0)*67108864+(_.words[I.length+se-1]|0);for(P=Math.min(P/M|0,67108863),_._ishlnsubmul(I,P,se);_.negative!==0;)P--,_.negative=0,_._ishlnsubmul(I,1,se),_.isZero()||(_.negative^=1);g&&(g.words[se]=P)}return g&&g._strip(),_._strip(),h!=="div"&&v!==0&&_.iushrn(v),{div:g||null,mod:_}},a.prototype.divmod=function(c,h,v){if(i(!c.isZero()),this.isZero())return{div:new a(0),mod:new a(0)};var _,I,M;return this.negative!==0&&c.negative===0?(M=this.neg().divmod(c,h),h!=="mod"&&(_=M.div.neg()),h!=="div"&&(I=M.mod.neg(),v&&I.negative!==0&&I.iadd(c)),{div:_,mod:I}):this.negative===0&&c.negative!==0?(M=this.divmod(c.neg(),h),h!=="mod"&&(_=M.div.neg()),{div:_,mod:M.mod}):this.negative&c.negative?(M=this.neg().divmod(c.neg(),h),h!=="div"&&(I=M.mod.neg(),v&&I.negative!==0&&I.isub(c)),{div:M.div,mod:I}):c.length>this.length||this.cmp(c)<0?{div:new a(0),mod:this}:c.length===1?h==="div"?{div:this.divn(c.words[0]),mod:null}:h==="mod"?{div:null,mod:new a(this.modrn(c.words[0]))}:{div:this.divn(c.words[0]),mod:new a(this.modrn(c.words[0]))}:this._wordDiv(c,h)},a.prototype.div=function(c){return this.divmod(c,"div",!1).div},a.prototype.mod=function(c){return this.divmod(c,"mod",!1).mod},a.prototype.umod=function(c){return this.divmod(c,"mod",!0).mod},a.prototype.divRound=function(c){var h=this.divmod(c);if(h.mod.isZero())return h.div;var v=h.div.negative!==0?h.mod.isub(c):h.mod,_=c.ushrn(1),I=c.andln(1),M=v.cmp(_);return M<0||I===1&&M===0?h.div:h.div.negative!==0?h.div.isubn(1):h.div.iaddn(1)},a.prototype.modrn=function(c){var h=c<0;h&&(c=-c),i(c<=67108863);for(var v=(1<<26)%c,_=0,I=this.length-1;I>=0;I--)_=(v*_+(this.words[I]|0))%c;return h?-_:_},a.prototype.modn=function(c){return this.modrn(c)},a.prototype.idivn=function(c){var h=c<0;h&&(c=-c),i(c<=67108863);for(var v=0,_=this.length-1;_>=0;_--){var I=(this.words[_]|0)+v*67108864;this.words[_]=I/c|0,v=I%c}return this._strip(),h?this.ineg():this},a.prototype.divn=function(c){return this.clone().idivn(c)},a.prototype.egcd=function(c){i(c.negative===0),i(!c.isZero());var h=this,v=c.clone();h.negative!==0?h=h.umod(c):h=h.clone();for(var _=new a(1),I=new a(0),M=new a(0),S=new a(1),d=0;h.isEven()&&v.isEven();)h.iushrn(1),v.iushrn(1),++d;for(var g=v.clone(),T=h.clone();!h.isZero();){for(var Z=0,se=1;!(h.words[0]&se)&&Z<26;++Z,se<<=1);if(Z>0)for(h.iushrn(Z);Z-- >0;)(_.isOdd()||I.isOdd())&&(_.iadd(g),I.isub(T)),_.iushrn(1),I.iushrn(1);for(var P=0,ee=1;!(v.words[0]&ee)&&P<26;++P,ee<<=1);if(P>0)for(v.iushrn(P);P-- >0;)(M.isOdd()||S.isOdd())&&(M.iadd(g),S.isub(T)),M.iushrn(1),S.iushrn(1);h.cmp(v)>=0?(h.isub(v),_.isub(M),I.isub(S)):(v.isub(h),M.isub(_),S.isub(I))}return{a:M,b:S,gcd:v.iushln(d)}},a.prototype._invmp=function(c){i(c.negative===0),i(!c.isZero());var h=this,v=c.clone();h.negative!==0?h=h.umod(c):h=h.clone();for(var _=new a(1),I=new a(0),M=v.clone();h.cmpn(1)>0&&v.cmpn(1)>0;){for(var S=0,d=1;!(h.words[0]&d)&&S<26;++S,d<<=1);if(S>0)for(h.iushrn(S);S-- >0;)_.isOdd()&&_.iadd(M),_.iushrn(1);for(var g=0,T=1;!(v.words[0]&T)&&g<26;++g,T<<=1);if(g>0)for(v.iushrn(g);g-- >0;)I.isOdd()&&I.iadd(M),I.iushrn(1);h.cmp(v)>=0?(h.isub(v),_.isub(I)):(v.isub(h),I.isub(_))}var Z;return h.cmpn(1)===0?Z=_:Z=I,Z.cmpn(0)<0&&Z.iadd(c),Z},a.prototype.gcd=function(c){if(this.isZero())return c.abs();if(c.isZero())return this.abs();var h=this.clone(),v=c.clone();h.negative=0,v.negative=0;for(var _=0;h.isEven()&&v.isEven();_++)h.iushrn(1),v.iushrn(1);do{for(;h.isEven();)h.iushrn(1);for(;v.isEven();)v.iushrn(1);var I=h.cmp(v);if(I<0){var M=h;h=v,v=M}else if(I===0||v.cmpn(1)===0)break;h.isub(v)}while(!0);return v.iushln(_)},a.prototype.invm=function(c){return this.egcd(c).a.umod(c)},a.prototype.isEven=function(){return(this.words[0]&1)===0},a.prototype.isOdd=function(){return(this.words[0]&1)===1},a.prototype.andln=function(c){return this.words[0]&c},a.prototype.bincn=function(c){i(typeof c=="number");var h=c%26,v=(c-h)/26,_=1<>>26,S&=67108863,this.words[M]=S}return I!==0&&(this.words[M]=I,this.length++),this},a.prototype.isZero=function(){return this.length===1&&this.words[0]===0},a.prototype.cmpn=function(c){var h=c<0;if(this.negative!==0&&!h)return-1;if(this.negative===0&&h)return 1;this._strip();var v;if(this.length>1)v=1;else{h&&(c=-c),i(c<=67108863,"Number is too big");var _=this.words[0]|0;v=_===c?0:_c.length)return 1;if(this.length=0;v--){var _=this.words[v]|0,I=c.words[v]|0;if(_!==I){_I&&(h=1);break}}return h},a.prototype.gtn=function(c){return this.cmpn(c)===1},a.prototype.gt=function(c){return this.cmp(c)===1},a.prototype.gten=function(c){return this.cmpn(c)>=0},a.prototype.gte=function(c){return this.cmp(c)>=0},a.prototype.ltn=function(c){return this.cmpn(c)===-1},a.prototype.lt=function(c){return this.cmp(c)===-1},a.prototype.lten=function(c){return this.cmpn(c)<=0},a.prototype.lte=function(c){return this.cmp(c)<=0},a.prototype.eqn=function(c){return this.cmpn(c)===0},a.prototype.eq=function(c){return this.cmp(c)===0},a.red=function(c){return new F(c)},a.prototype.toRed=function(c){return i(!this.red,"Already a number in reduction context"),i(this.negative===0,"red works only with positives"),c.convertTo(this)._forceRed(c)},a.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(c){return this.red=c,this},a.prototype.forceRed=function(c){return i(!this.red,"Already a number in reduction context"),this._forceRed(c)},a.prototype.redAdd=function(c){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,c)},a.prototype.redIAdd=function(c){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,c)},a.prototype.redSub=function(c){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,c)},a.prototype.redISub=function(c){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,c)},a.prototype.redShl=function(c){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,c)},a.prototype.redMul=function(c){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,c),this.red.mul(this,c)},a.prototype.redIMul=function(c){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,c),this.red.imul(this,c)},a.prototype.redSqr=function(){return i(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return i(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return i(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return i(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return i(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(c){return i(this.red&&!c.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,c)};var k={k256:null,p224:null,p192:null,p25519:null};function G(c,h){this.name=c,this.p=new a(h,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}G.prototype._tmp=function(){var c=new a(null);return c.words=new Array(Math.ceil(this.n/13)),c},G.prototype.ireduce=function(c){var h=c,v;do this.split(h,this.tmp),h=this.imulK(h),h=h.iadd(this.tmp),v=h.bitLength();while(v>this.n);var _=v0?h.isub(this.p):h.strip!==void 0?h.strip():h._strip(),h},G.prototype.split=function(c,h){c.iushrn(this.n,0,h)},G.prototype.imulK=function(c){return c.imul(this.k)};function x(){G.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(x,G),x.prototype.split=function(c,h){for(var v=4194303,_=Math.min(c.length,9),I=0;I<_;I++)h.words[I]=c.words[I];if(h.length=_,c.length<=9){c.words[0]=0,c.length=1;return}var M=c.words[9];for(h.words[h.length++]=M&v,I=10;I>>22,M=S}M>>>=22,c.words[I-10]=M,M===0&&c.length>10?c.length-=10:c.length-=9},x.prototype.imulK=function(c){c.words[c.length]=0,c.words[c.length+1]=0,c.length+=2;for(var h=0,v=0;v>>=26,c.words[v]=I,h=_}return h!==0&&(c.words[c.length++]=h),c},a._prime=function(c){if(k[c])return k[c];var h;if(c==="k256")h=new x;else if(c==="p224")h=new B;else if(c==="p192")h=new ae;else if(c==="p25519")h=new le;else throw new Error("Unknown prime "+c);return k[c]=h,h};function F(c){if(typeof c=="string"){var h=a._prime(c);this.m=h.p,this.prime=h}else i(c.gtn(1),"modulus must be greater than 1"),this.m=c,this.prime=null}F.prototype._verify1=function(c){i(c.negative===0,"red works only with positives"),i(c.red,"red works only with red numbers")},F.prototype._verify2=function(c,h){i((c.negative|h.negative)===0,"red works only with positives"),i(c.red&&c.red===h.red,"red works only with red numbers")},F.prototype.imod=function(c){return this.prime?this.prime.ireduce(c)._forceRed(this):(y(c,c.umod(this.m)._forceRed(this)),c)},F.prototype.neg=function(c){return c.isZero()?c.clone():this.m.sub(c)._forceRed(this)},F.prototype.add=function(c,h){this._verify2(c,h);var v=c.add(h);return v.cmp(this.m)>=0&&v.isub(this.m),v._forceRed(this)},F.prototype.iadd=function(c,h){this._verify2(c,h);var v=c.iadd(h);return v.cmp(this.m)>=0&&v.isub(this.m),v},F.prototype.sub=function(c,h){this._verify2(c,h);var v=c.sub(h);return v.cmpn(0)<0&&v.iadd(this.m),v._forceRed(this)},F.prototype.isub=function(c,h){this._verify2(c,h);var v=c.isub(h);return v.cmpn(0)<0&&v.iadd(this.m),v},F.prototype.shl=function(c,h){return this._verify1(c),this.imod(c.ushln(h))},F.prototype.imul=function(c,h){return this._verify2(c,h),this.imod(c.imul(h))},F.prototype.mul=function(c,h){return this._verify2(c,h),this.imod(c.mul(h))},F.prototype.isqr=function(c){return this.imul(c,c.clone())},F.prototype.sqr=function(c){return this.mul(c,c)},F.prototype.sqrt=function(c){if(c.isZero())return c.clone();var h=this.m.andln(3);if(i(h%2===1),h===3){var v=this.m.add(new a(1)).iushrn(2);return this.pow(c,v)}for(var _=this.m.subn(1),I=0;!_.isZero()&&_.andln(1)===0;)I++,_.iushrn(1);i(!_.isZero());var M=new a(1).toRed(this),S=M.redNeg(),d=this.m.subn(1).iushrn(1),g=this.m.bitLength();for(g=new a(2*g*g).toRed(this);this.pow(g,d).cmp(S)!==0;)g.redIAdd(S);for(var T=this.pow(g,_),Z=this.pow(c,_.addn(1).iushrn(1)),se=this.pow(c,_),P=I;se.cmp(M)!==0;){for(var ee=se,q=0;ee.cmp(M)!==0;q++)ee=ee.redSqr();i(q=0;I--){for(var T=h.words[I],Z=g-1;Z>=0;Z--){var se=T>>Z&1;if(M!==_[0]&&(M=this.sqr(M)),se===0&&S===0){d=0;continue}S<<=1,S|=se,d++,!(d!==v&&(I!==0||Z!==0))&&(M=this.mul(M,_[S]),d=0,S=0)}g=26}return M},F.prototype.convertTo=function(c){var h=c.umod(this.m);return h===c?h.clone():h},F.prototype.convertFrom=function(c){var h=c.clone();return h.red=null,h},a.mont=function(c){return new m(c)};function m(c){F.call(this,c),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new a(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)}n(m,F),m.prototype.convertTo=function(c){return this.imod(c.ushln(this.shift))},m.prototype.convertFrom=function(c){var h=this.imod(c.mul(this.rinv));return h.red=null,h},m.prototype.imul=function(c,h){if(c.isZero()||h.isZero())return c.words[0]=0,c.length=1,c;var v=c.imul(h),_=v.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=v.isub(_).iushrn(this.shift),M=I;return I.cmp(this.m)>=0?M=I.isub(this.m):I.cmpn(0)<0&&(M=I.iadd(this.m)),M._forceRed(this)},m.prototype.mul=function(c,h){if(c.isZero()||h.isZero())return new a(0)._forceRed(this);var v=c.mul(h),_=v.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=v.isub(_).iushrn(this.shift),M=I;return I.cmp(this.m)>=0?M=I.isub(this.m):I.cmpn(0)<0&&(M=I.iadd(this.m)),M._forceRed(this)},m.prototype.invm=function(c){var h=this.imod(c._invmp(this.m).mul(this.r2));return h._forceRed(this)}})(r,Bb)})($b);var vt=$b.exports;const zb="bignumber/5.7.0";var ph=vt.BN;const cs=new Or(zb),yl={},V1=9007199254740991;function RA(r){return r!=null&&(Gt.isBigNumber(r)||typeof r=="number"&&r%1===0||typeof r=="string"&&!!r.match(/^-?[0-9]+$/)||_i(r)||typeof r=="bigint"||bo(r))}let G1=!1;class Gt{constructor(e,t){e!==yl&&cs.throwError("cannot call constructor directly; use BigNumber.from",Or.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=t,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return si(Pt(this).fromTwos(e))}toTwos(e){return si(Pt(this).toTwos(e))}abs(){return this._hex[0]==="-"?Gt.from(this._hex.substring(1)):this}add(e){return si(Pt(this).add(Pt(e)))}sub(e){return si(Pt(this).sub(Pt(e)))}div(e){return Gt.from(e).isZero()&&Fi("division-by-zero","div"),si(Pt(this).div(Pt(e)))}mul(e){return si(Pt(this).mul(Pt(e)))}mod(e){const t=Pt(e);return t.isNeg()&&Fi("division-by-zero","mod"),si(Pt(this).umod(t))}pow(e){const t=Pt(e);return t.isNeg()&&Fi("negative-power","pow"),si(Pt(this).pow(t))}and(e){const t=Pt(e);return(this.isNegative()||t.isNeg())&&Fi("unbound-bitwise-result","and"),si(Pt(this).and(t))}or(e){const t=Pt(e);return(this.isNegative()||t.isNeg())&&Fi("unbound-bitwise-result","or"),si(Pt(this).or(t))}xor(e){const t=Pt(e);return(this.isNegative()||t.isNeg())&&Fi("unbound-bitwise-result","xor"),si(Pt(this).xor(t))}mask(e){return(this.isNegative()||e<0)&&Fi("negative-width","mask"),si(Pt(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Fi("negative-width","shl"),si(Pt(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Fi("negative-width","shr"),si(Pt(this).shrn(e))}eq(e){return Pt(this).eq(Pt(e))}lt(e){return Pt(this).lt(Pt(e))}lte(e){return Pt(this).lte(Pt(e))}gt(e){return Pt(this).gt(Pt(e))}gte(e){return Pt(this).gte(Pt(e))}isNegative(){return this._hex[0]==="-"}isZero(){return Pt(this).isZero()}toNumber(){try{return Pt(this).toNumber()}catch{Fi("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return cs.throwError("this platform does not support BigInt",Or.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?G1||(G1=!0,cs.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?cs.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",Or.errors.UNEXPECTED_ARGUMENT,{}):cs.throwError("BigNumber.toString does not accept parameters",Or.errors.UNEXPECTED_ARGUMENT,{})),Pt(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof Gt)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new Gt(yl,pc(e)):e.match(/^-?[0-9]+$/)?new Gt(yl,pc(new ph(e))):cs.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Fi("underflow","BigNumber.from",e),(e>=V1||e<=-V1)&&Fi("overflow","BigNumber.from",e),Gt.from(String(e));const t=e;if(typeof t=="bigint")return Gt.from(t.toString());if(bo(t))return Gt.from(ci(t));if(t)if(t.toHexString){const i=t.toHexString();if(typeof i=="string")return Gt.from(i)}else{let i=t._hex;if(i==null&&t.type==="BigNumber"&&(i=t.hex),typeof i=="string"&&(_i(i)||i[0]==="-"&&_i(i.substring(1))))return Gt.from(i)}return cs.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}}function pc(r){if(typeof r!="string")return pc(r.toString(16));if(r[0]==="-")return r=r.substring(1),r[0]==="-"&&cs.throwArgumentError("invalid hex","value",r),r=pc(r),r==="0x00"?r:"-"+r;if(r.substring(0,2)!=="0x"&&(r="0x"+r),r==="0x")return"0x00";for(r.length%2&&(r="0x0"+r.substring(2));r.length>4&&r.substring(0,4)==="0x00";)r="0x"+r.substring(4);return r}function si(r){return Gt.from(pc(r))}function Pt(r){const e=Gt.from(r).toHexString();return e[0]==="-"?new ph("-"+e.substring(3),16):new ph(e.substring(2),16)}function Fi(r,e,t){const i={fault:r,operation:e};return t!=null&&(i.value=t),cs.throwError(r,Or.errors.NUMERIC_FAULT,i)}function NA(r){return new ph(r,36).toString(16)}const Wr=new Or(zb),oc={},jb=Gt.from(0),kb=Gt.from(-1);function Hb(r,e,t,i){const n={fault:e,operation:t};return i!==void 0&&(n.value=i),Wr.throwError(r,Or.errors.NUMERIC_FAULT,n)}let cc="0";for(;cc.length<256;)cc+=cc;function k0(r){if(typeof r!="number")try{r=Gt.from(r).toNumber()}catch{}return typeof r=="number"&&r>=0&&r<=256&&!(r%1)?"1"+cc.substring(0,r):Wr.throwArgumentError("invalid decimal size","decimals",r)}function wl(r,e){e==null&&(e=0);const t=k0(e);r=Gt.from(r);const i=r.lt(jb);i&&(r=r.mul(kb));let n=r.mod(t).toString();for(;n.length2&&Wr.throwArgumentError("too many decimal points","value",r);let a=n[0],f=n[1];for(a||(a="0"),f||(f="0");f[f.length-1]==="0";)f=f.substring(0,f.length-1);for(f.length>t.length-1&&Hb("fractional component exceeds decimals","underflow","parseFixed"),f===""&&(f="0");f.lengthe[f]==null?b:(typeof e[f]!==u&&Wr.throwArgumentError("invalid fixed format ("+f+" not "+u+")","format."+f,e[f]),e[f]);t=a("signed","boolean",t),i=a("width","number",i),n=a("decimals","number",n)}return i%8&&Wr.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",i),n>80&&Wr.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",n),new a0(oc,t,i,n)}},Kb=class Vr{constructor(e,t,i,n){e!==oc&&Wr.throwError("cannot use FixedNumber constructor; use FixedNumber.from",Or.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=n,this._hex=t,this._value=i,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&Wr.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);const t=ns(this._value,this.format.decimals),i=ns(e._value,e.format.decimals);return Vr.fromValue(t.add(i),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);const t=ns(this._value,this.format.decimals),i=ns(e._value,e.format.decimals);return Vr.fromValue(t.sub(i),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);const t=ns(this._value,this.format.decimals),i=ns(e._value,e.format.decimals);return Vr.fromValue(t.mul(i).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);const t=ns(this._value,this.format.decimals),i=ns(e._value,e.format.decimals);return Vr.fromValue(t.mul(this.format._multiplier).div(i),this.format.decimals,this.format)}floor(){const e=this.toString().split(".");e.length===1&&e.push("0");let t=Vr.from(e[0],this.format);const i=!e[1].match(/^(0*)$/);return this.isNegative()&&i&&(t=t.subUnsafe(W1.toFormat(t.format))),t}ceiling(){const e=this.toString().split(".");e.length===1&&e.push("0");let t=Vr.from(e[0],this.format);const i=!e[1].match(/^(0*)$/);return!this.isNegative()&&i&&(t=t.addUnsafe(W1.toFormat(t.format))),t}round(e){e==null&&(e=0);const t=this.toString().split(".");if(t.length===1&&t.push("0"),(e<0||e>80||e%1)&&Wr.throwArgumentError("invalid decimal count","decimals",e),t[1].length<=e)return this;const i=Vr.from("1"+cc.substring(0,e),this.format),n=CA.toFormat(this.format);return this.mulUnsafe(i).addUnsafe(n).floor().divUnsafe(i)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&Wr.throwArgumentError("invalid byte width","width",e);const t=Gt.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return Dn(t,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return Vr.fromString(this._value,e)}static fromValue(e,t,i){return i==null&&t!=null&&!RA(t)&&(i=t,t=null),t==null&&(t=0),i==null&&(i="fixed"),Vr.fromString(wl(e,t),_l.from(i))}static fromString(e,t){t==null&&(t="fixed");const i=_l.from(t),n=ns(e,i.decimals);!i.signed&&n.lt(jb)&&Hb("unsigned value cannot be negative","overflow","value",e);let a=null;i.signed?a=n.toTwos(i.width).toHexString():(a=n.toHexString(),a=Dn(a,i.width/8));const f=wl(n,i.decimals);return new Vr(oc,a,f,i)}static fromBytes(e,t){t==null&&(t="fixed");const i=_l.from(t);if(ir(e).length>i.width/8)throw new Error("overflow");let n=Gt.from(e);i.signed&&(n=n.fromTwos(i.width));const a=n.toTwos((i.signed?0:1)+i.width).toHexString(),f=wl(n,i.decimals);return new Vr(oc,a,f,i)}static from(e,t){if(typeof e=="string")return Vr.fromString(e,t);if(bo(e))return Vr.fromBytes(e,t);try{return Vr.fromValue(e,0,t)}catch(i){if(i.code!==Or.errors.INVALID_ARGUMENT)throw i}return Wr.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}};const W1=Kb.from(1),CA=Kb.from("0.5"),TA="strings/5.7.0",DA=new Or(TA);var gh;(function(r){r.current="",r.NFC="NFC",r.NFD="NFD",r.NFKC="NFKC",r.NFKD="NFKD"})(gh||(gh={}));var J1;(function(r){r.UNEXPECTED_CONTINUE="unexpected continuation byte",r.BAD_PREFIX="bad codepoint prefix",r.OVERRUN="string overrun",r.MISSING_CONTINUE="missing continuation byte",r.OUT_OF_RANGE="out of UTF-8 range",r.UTF16_SURROGATE="UTF-16 surrogate",r.OVERLONG="overlong representation"})(J1||(J1={}));function Al(r,e=gh.current){e!=gh.current&&(DA.checkNormalize(),r=r.normalize(e));let t=[];for(let i=0;i>6|192),t.push(n&63|128);else if((n&64512)==55296){i++;const a=r.charCodeAt(i);if(i>=r.length||(a&64512)!==56320)throw new Error("invalid utf-8 string");const f=65536+((n&1023)<<10)+(a&1023);t.push(f>>18|240),t.push(f>>12&63|128),t.push(f>>6&63|128),t.push(f&63|128)}else t.push(n>>12|224),t.push(n>>6&63|128),t.push(n&63|128)}return ir(t)}function FA(r){if(r.length%4!==0)throw new Error("bad data");let e=[];for(let t=0;t{let a=n.split(":");t+=parseInt(a[0],16),i[t]=e(a[1])}),i}function Y1(r){let e=0;return r.split(",").map(t=>{let i=t.split("-");i.length===1?i[1]="0":i[1]===""&&(i[1]="1");let n=e+parseInt(i[0],16);return e=parseInt(i[1],16),{l:n,h:e}})}Y1("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(r=>parseInt(r,16)),El("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),El("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),El("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",FA),Y1("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");function BA(r){r=atob(r);const e=[];for(let t=0;t0&&Array.isArray(u)?n(u,f-1):t.push(u)})};return n(r,e),t}function qA(r){const e={};for(let t=0;t>--b&1}const A=31,R=Math.pow(2,A),O=R>>>1,N=O>>1,K=R-1;let W=0;for(let k=0;k1;){let le=G+x>>>1;k>>1|y(),B=B<<1^O,ae=(ae^O)<<1|O|1;j=B,Y=1+ae-B}let U=i-4;return Q.map(k=>{switch(k-U){case 3:return U+65792+(r[u++]<<16|r[u++]<<8|r[u++]);case 2:return U+256+(r[u++]<<8|r[u++]);case 1:return U+r[u++];default:return k-1}})}function UA(r){let e=0;return()=>r[e++]}function $A(r){return UA(LA(r))}function zA(r){return r&1?~r>>1:r>>1}function jA(r,e){let t=Array(r);for(let i=0;ie[f]):t}function HA(r){let e=[];for(;;){let t=r();if(t==0)break;e.push(VA(t,r))}for(;;){let t=r()-1;if(t<0)break;e.push(GA(t,r))}return qA(Vb(e))}function KA(r){let e=[];for(;;){let t=r();if(t==0)break;e.push(t)}return e}function Gb(r,e,t){let i=Array(r).fill(void 0).map(()=>[]);for(let n=0;ni[f].push(a));return i}function VA(r,e){let t=1+e(),i=e(),n=KA(e),a=Gb(n.length,1+r,e);return Vb(a.map((f,u)=>{const b=f[0],p=f.slice(1);return Array(n[u]).fill(void 0).map((y,A)=>{let R=A*i;return[b+A*t,p.map(O=>O+R)]})}))}function GA(r,e){let t=1+e();return Gb(t,1+r,e).map(i=>[i[0],i.slice(1)])}function WA(r){let e=vh(r).sort((i,n)=>i-n);return t();function t(){let i=[];for(;;){let p=vh(r,e);if(p.length==0)break;i.push({set:new Set(p),node:t()})}i.sort((p,y)=>y.set.size-p.set.size);let n=r(),a=n%3;n=n/3|0;let f=!!(n&1);n>>=1;let u=n==1,b=n==2;return{branches:i,valid:a,fe0f:f,save:u,check:b}}}function JA(){return $A(BA("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}const Lf=JA();new Set(vh(Lf)),new Set(vh(Lf)),HA(Lf),WA(Lf);const YA=new Uint8Array(32);YA.fill(0);const QA=`Ethereum Signed Message: +`;function Wb(r){return typeof r=="string"&&(r=Al(r)),j0(xA([Al(QA),Al(String(r.length)),r]))}const XA="address/5.7.0",ic=new Or(XA);function X1(r){_i(r,20)||ic.throwArgumentError("invalid address","address",r),r=r.toLowerCase();const e=r.substring(2).split(""),t=new Uint8Array(40);for(let n=0;n<40;n++)t[n]=e[n].charCodeAt(0);const i=ir(j0(t));for(let n=0;n<40;n+=2)i[n>>1]>>4>=8&&(e[n]=e[n].toUpperCase()),(i[n>>1]&15)>=8&&(e[n+1]=e[n+1].toUpperCase());return"0x"+e.join("")}const ZA=9007199254740991;function eE(r){return Math.log10?Math.log10(r):Math.log(r)/Math.LN10}const H0={};for(let r=0;r<10;r++)H0[String(r)]=String(r);for(let r=0;r<26;r++)H0[String.fromCharCode(65+r)]=String(10+r);const Z1=Math.floor(eE(ZA));function tE(r){r=r.toUpperCase(),r=r.substring(4)+r.substring(0,2)+"00";let e=r.split("").map(i=>H0[i]).join("");for(;e.length>=Z1;){let i=e.substring(0,Z1);e=parseInt(i,10)%97+e.substring(i.length)}let t=String(98-parseInt(e,10)%97);for(;t.length<2;)t="0"+t;return t}function rE(r){let e=null;if(typeof r!="string"&&ic.throwArgumentError("invalid address","address",r),r.match(/^(0x)?[0-9a-fA-F]{40}$/))r.substring(0,2)!=="0x"&&(r="0x"+r),e=X1(r),r.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==r&&ic.throwArgumentError("bad address checksum","address",r);else if(r.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(r.substring(2,4)!==tE(r)&&ic.throwArgumentError("bad icap checksum","address",r),e=NA(r.substring(4));e.length<40;)e="0"+e;e=X1("0x"+e)}else ic.throwArgumentError("invalid address","address",r);return e}function Go(r,e,t){Object.defineProperty(r,e,{enumerable:!0,value:t,writable:!1})}const iE=new Uint8Array(32);iE.fill(0),Gt.from(-1);const nE=Gt.from(0),sE=Gt.from(1);Gt.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Dn(sE.toHexString(),32),Dn(nE.toHexString(),32);var Sn={},Rt={},Mc=Jb;function Jb(r,e){if(!r)throw new Error(e||"Assertion failed")}Jb.equal=function(r,e,t){if(r!=e)throw new Error(t||"Assertion failed: "+r+" != "+e)};var o0={exports:{}};typeof Object.create=="function"?o0.exports=function(r,e){e&&(r.super_=e,r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}))}:o0.exports=function(r,e){if(e){r.super_=e;var t=function(){};t.prototype=e.prototype,r.prototype=new t,r.prototype.constructor=r}};var aE=Mc,oE=o0.exports;Rt.inherits=oE;function cE(r,e){return(r.charCodeAt(e)&64512)!==55296||e<0||e+1>=r.length?!1:(r.charCodeAt(e+1)&64512)===56320}function fE(r,e){if(Array.isArray(r))return r.slice();if(!r)return[];var t=[];if(typeof r=="string")if(e){if(e==="hex")for(r=r.replace(/[^a-z0-9]+/ig,""),r.length%2!==0&&(r="0"+r),n=0;n>6|192,t[i++]=a&63|128):cE(r,n)?(a=65536+((a&1023)<<10)+(r.charCodeAt(++n)&1023),t[i++]=a>>18|240,t[i++]=a>>12&63|128,t[i++]=a>>6&63|128,t[i++]=a&63|128):(t[i++]=a>>12|224,t[i++]=a>>6&63|128,t[i++]=a&63|128)}else for(n=0;n>>24|r>>>8&65280|r<<8&16711680|(r&255)<<24;return e>>>0}Rt.htonl=Yb;function uE(r,e){for(var t="",i=0;i>>0}return a}Rt.join32=lE;function dE(r,e){for(var t=new Array(r.length*4),i=0,n=0;i>>24,t[n+1]=a>>>16&255,t[n+2]=a>>>8&255,t[n+3]=a&255):(t[n+3]=a>>>24,t[n+2]=a>>>16&255,t[n+1]=a>>>8&255,t[n]=a&255)}return t}Rt.split32=dE;function pE(r,e){return r>>>e|r<<32-e}Rt.rotr32=pE;function gE(r,e){return r<>>32-e}Rt.rotl32=gE;function vE(r,e){return r+e>>>0}Rt.sum32=vE;function bE(r,e,t){return r+e+t>>>0}Rt.sum32_3=bE;function mE(r,e,t,i){return r+e+t+i>>>0}Rt.sum32_4=mE;function yE(r,e,t,i,n){return r+e+t+i+n>>>0}Rt.sum32_5=yE;function wE(r,e,t,i){var n=r[e],a=r[e+1],f=i+a>>>0,u=(f>>0,r[e+1]=f}Rt.sum64=wE;function _E(r,e,t,i){var n=e+i>>>0,a=(n>>0}Rt.sum64_hi=_E;function AE(r,e,t,i){var n=e+i;return n>>>0}Rt.sum64_lo=AE;function EE(r,e,t,i,n,a,f,u){var b=0,p=e;p=p+i>>>0,b+=p>>0,b+=p>>0,b+=p>>0}Rt.sum64_4_hi=EE;function xE(r,e,t,i,n,a,f,u){var b=e+i+a+u;return b>>>0}Rt.sum64_4_lo=xE;function SE(r,e,t,i,n,a,f,u,b,p){var y=0,A=e;A=A+i>>>0,y+=A>>0,y+=A>>0,y+=A>>0,y+=A>>0}Rt.sum64_5_hi=SE;function IE(r,e,t,i,n,a,f,u,b,p){var y=e+i+a+u+p;return y>>>0}Rt.sum64_5_lo=IE;function ME(r,e,t){var i=e<<32-t|r>>>t;return i>>>0}Rt.rotr64_hi=ME;function PE(r,e,t){var i=r<<32-t|e>>>t;return i>>>0}Rt.rotr64_lo=PE;function OE(r,e,t){return r>>>t}Rt.shr64_hi=OE;function RE(r,e,t){var i=r<<32-t|e>>>t;return i>>>0}Rt.shr64_lo=RE;var mo={},eg=Rt,NE=Mc;function Uf(){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}mo.BlockHash=Uf,Uf.prototype.update=function(r,e){if(r=eg.toArray(r,e),this.pending?this.pending=this.pending.concat(r):this.pending=r,this.pendingTotal+=r.length,this.pending.length>=this._delta8){r=this.pending;var t=r.length%this._delta8;this.pending=r.slice(r.length-t,r.length),this.pending.length===0&&(this.pending=null),r=eg.join32(r,0,r.length-t,this.endian);for(var i=0;i>>24&255,i[n++]=r>>>16&255,i[n++]=r>>>8&255,i[n++]=r&255}else for(i[n++]=r&255,i[n++]=r>>>8&255,i[n++]=r>>>16&255,i[n++]=r>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,a=8;a>>3}Vn.g0_256=BE;function qE(r){return Fn(r,17)^Fn(r,19)^r>>>10}Vn.g1_256=qE;var ao=Rt,LE=mo,UE=Vn,xl=ao.rotl32,Wo=ao.sum32,$E=ao.sum32_5,zE=UE.ft_1,r2=LE.BlockHash,jE=[1518500249,1859775393,2400959708,3395469782];function On(){if(!(this instanceof On))return new On;r2.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}ao.inherits(On,r2);var kE=On;On.blockSize=512,On.outSize=160,On.hmacStrength=80,On.padLength=64,On.prototype._update=function(r,e){for(var t=this.W,i=0;i<16;i++)t[i]=r[e+i];for(;ithis.blockSize&&(r=new this.Hash().update(r).digest()),Rx(r.length<=this.blockSize);for(var e=r.length;e>8,R=y&255;A?b.push(A,R):b.push(R)}return b}t.toArray=i;function n(f){return f.length===1?"0"+f:f}t.zero2=n;function a(f){for(var u="",b=0;b(R>>1)-1?K=(R>>1)-W:K=W,O.isubn(K)):K=0,A[N]=K,O.iushrn(1)}return A}t.getNAF=i;function n(b,p){var y=[[],[]];b=b.clone(),p=p.clone();for(var A=0,R=0,O;b.cmpn(-A)>0||p.cmpn(-R)>0;){var N=b.andln(3)+A&3,K=p.andln(3)+R&3;N===3&&(N=-1),K===3&&(K=-1);var W;N&1?(O=b.andln(7)+A&7,(O===3||O===5)&&K===2?W=-N:W=N):W=0,y[0].push(W);var Q;K&1?(O=p.andln(7)+R&7,(O===3||O===5)&&N===2?Q=-K:Q=K):Q=0,y[1].push(Q),2*A===W+1&&(A=1-A),2*R===Q+1&&(R=1-R),b.iushrn(1),p.iushrn(1)}return y}t.getJSF=n;function a(b,p,y){var A="_"+p;b.prototype[p]=function(){return this[A]!==void 0?this[A]:this[A]=y.call(this)}}t.cachedProperty=a;function f(b){return typeof b=="string"?t.toArray(b,"hex"):b}t.parseBytes=f;function u(b){return new vt(b,"hex","le")}t.intFromLE=u}),zf=Ai.getNAF,Tx=Ai.getJSF,bh=Ai.assert;function Ts(r,e){this.type=r,this.p=new vt(e.p,16),this.red=e.prime?vt.red(e.prime):vt.mont(this.p),this.zero=new vt(0).toRed(this.red),this.one=new vt(1).toRed(this.red),this.two=new vt(2).toRed(this.red),this.n=e.n&&new vt(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var t=this.n&&this.p.div(this.n);!t||t.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var _a=Ts;Ts.prototype.point=function(){throw new Error("Not implemented")},Ts.prototype.validate=function(){throw new Error("Not implemented")},Ts.prototype._fixedNafMul=function(r,e){bh(r.precomputed);var t=r._getDoubles(),i=zf(e,1,this._bitLength),n=(1<=f;b--)u=(u<<1)+i[b];a.push(u)}for(var p=this.jpoint(null,null,null),y=this.jpoint(null,null,null),A=n;A>0;A--){for(f=0;f=0;u--){for(var b=0;u>=0&&a[u]===0;u--)b++;if(u>=0&&b++,f=f.dblp(b),u<0)break;var p=a[u];bh(p!==0),r.type==="affine"?p>0?f=f.mixedAdd(n[p-1>>1]):f=f.mixedAdd(n[-p-1>>1].neg()):p>0?f=f.add(n[p-1>>1]):f=f.add(n[-p-1>>1].neg())}return r.type==="affine"?f.toP():f},Ts.prototype._wnafMulAdd=function(r,e,t,i,n){var a=this._wnafT1,f=this._wnafT2,u=this._wnafT3,b=0,p,y,A;for(p=0;p=1;p-=2){var O=p-1,N=p;if(a[O]!==1||a[N]!==1){u[O]=zf(t[O],a[O],this._bitLength),u[N]=zf(t[N],a[N],this._bitLength),b=Math.max(u[O].length,b),b=Math.max(u[N].length,b);continue}var K=[e[O],null,null,e[N]];e[O].y.cmp(e[N].y)===0?(K[1]=e[O].add(e[N]),K[2]=e[O].toJ().mixedAdd(e[N].neg())):e[O].y.cmp(e[N].y.redNeg())===0?(K[1]=e[O].toJ().mixedAdd(e[N]),K[2]=e[O].add(e[N].neg())):(K[1]=e[O].toJ().mixedAdd(e[N]),K[2]=e[O].toJ().mixedAdd(e[N].neg()));var W=[-3,-1,-5,-7,0,7,5,1,3],Q=Tx(t[O],t[N]);for(b=Math.max(Q[0].length,b),u[O]=new Array(b),u[N]=new Array(b),y=0;y=0;p--){for(var G=0;p>=0;){var x=!0;for(y=0;y=0&&G++,U=U.dblp(G),p<0)break;for(y=0;y0?A=f[y][B-1>>1]:B<0&&(A=f[y][-B-1>>1].neg()),A.type==="affine"?U=U.mixedAdd(A):U=U.add(A))}}for(p=0;p=Math.ceil((r.bitLength()+1)/e.step):!1},Bi.prototype._getDoubles=function(r,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var t=[this],i=this,n=0;n=0&&(R=b,O=p),y.negative&&(y=y.neg(),A=A.neg()),R.negative&&(R=R.neg(),O=O.neg()),[{a:y,b:A},{a:R,b:O}]},zi.prototype._endoSplit=function(r){var e=this.endo.basis,t=e[0],i=e[1],n=i.b.mul(r).divRound(this.n),a=t.b.neg().mul(r).divRound(this.n),f=n.mul(t.a),u=a.mul(i.a),b=n.mul(t.b),p=a.mul(i.b),y=r.sub(f).sub(u),A=b.add(p).neg();return{k1:y,k2:A}},zi.prototype.pointFromX=function(r,e){r=new vt(r,16),r.red||(r=r.toRed(this.red));var t=r.redSqr().redMul(r).redIAdd(r.redMul(this.a)).redIAdd(this.b),i=t.redSqrt();if(i.redSqr().redSub(t).cmp(this.zero)!==0)throw new Error("invalid point");var n=i.fromRed().isOdd();return(e&&!n||!e&&n)&&(i=i.redNeg()),this.point(r,i)},zi.prototype.validate=function(r){if(r.inf)return!0;var e=r.x,t=r.y,i=this.a.redMul(e),n=e.redSqr().redMul(e).redIAdd(i).redIAdd(this.b);return t.redSqr().redISub(n).cmpn(0)===0},zi.prototype._endoWnafMulAdd=function(r,e,t){for(var i=this._endoWnafT1,n=this._endoWnafT2,a=0;a":""},yr.prototype.isInfinity=function(){return this.inf},yr.prototype.add=function(r){if(this.inf)return r;if(r.inf)return this;if(this.eq(r))return this.dbl();if(this.neg().eq(r))return this.curve.point(null,null);if(this.x.cmp(r.x)===0)return this.curve.point(null,null);var e=this.y.redSub(r.y);e.cmpn(0)!==0&&(e=e.redMul(this.x.redSub(r.x).redInvm()));var t=e.redSqr().redISub(this.x).redISub(r.x),i=e.redMul(this.x.redSub(t)).redISub(this.y);return this.curve.point(t,i)},yr.prototype.dbl=function(){if(this.inf)return this;var r=this.y.redAdd(this.y);if(r.cmpn(0)===0)return this.curve.point(null,null);var e=this.curve.a,t=this.x.redSqr(),i=r.redInvm(),n=t.redAdd(t).redIAdd(t).redIAdd(e).redMul(i),a=n.redSqr().redISub(this.x.redAdd(this.x)),f=n.redMul(this.x.redSub(a)).redISub(this.y);return this.curve.point(a,f)},yr.prototype.getX=function(){return this.x.fromRed()},yr.prototype.getY=function(){return this.y.fromRed()},yr.prototype.mul=function(r){return r=new vt(r,16),this.isInfinity()?this:this._hasDoubles(r)?this.curve._fixedNafMul(this,r):this.curve.endo?this.curve._endoWnafMulAdd([this],[r]):this.curve._wnafMul(this,r)},yr.prototype.mulAdd=function(r,e,t){var i=[this,e],n=[r,t];return this.curve.endo?this.curve._endoWnafMulAdd(i,n):this.curve._wnafMulAdd(1,i,n,2)},yr.prototype.jmulAdd=function(r,e,t){var i=[this,e],n=[r,t];return this.curve.endo?this.curve._endoWnafMulAdd(i,n,!0):this.curve._wnafMulAdd(1,i,n,2,!0)},yr.prototype.eq=function(r){return this===r||this.inf===r.inf&&(this.inf||this.x.cmp(r.x)===0&&this.y.cmp(r.y)===0)},yr.prototype.neg=function(r){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(r&&this.precomputed){var t=this.precomputed,i=function(n){return n.neg()};e.precomputed={naf:t.naf&&{wnd:t.naf.wnd,points:t.naf.points.map(i)},doubles:t.doubles&&{step:t.doubles.step,points:t.doubles.points.map(i)}}}return e},yr.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var r=this.curve.jpoint(this.x,this.y,this.curve.one);return r};function Pr(r,e,t,i){_a.BasePoint.call(this,r,"jacobian"),e===null&&t===null&&i===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new vt(0)):(this.x=new vt(e,16),this.y=new vt(t,16),this.z=new vt(i,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}V0(Pr,_a.BasePoint),zi.prototype.jpoint=function(r,e,t){return new Pr(this,r,e,t)},Pr.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var r=this.z.redInvm(),e=r.redSqr(),t=this.x.redMul(e),i=this.y.redMul(e).redMul(r);return this.curve.point(t,i)},Pr.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Pr.prototype.add=function(r){if(this.isInfinity())return r;if(r.isInfinity())return this;var e=r.z.redSqr(),t=this.z.redSqr(),i=this.x.redMul(e),n=r.x.redMul(t),a=this.y.redMul(e.redMul(r.z)),f=r.y.redMul(t.redMul(this.z)),u=i.redSub(n),b=a.redSub(f);if(u.cmpn(0)===0)return b.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var p=u.redSqr(),y=p.redMul(u),A=i.redMul(p),R=b.redSqr().redIAdd(y).redISub(A).redISub(A),O=b.redMul(A.redISub(R)).redISub(a.redMul(y)),N=this.z.redMul(r.z).redMul(u);return this.curve.jpoint(R,O,N)},Pr.prototype.mixedAdd=function(r){if(this.isInfinity())return r.toJ();if(r.isInfinity())return this;var e=this.z.redSqr(),t=this.x,i=r.x.redMul(e),n=this.y,a=r.y.redMul(e).redMul(this.z),f=t.redSub(i),u=n.redSub(a);if(f.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var b=f.redSqr(),p=b.redMul(f),y=t.redMul(b),A=u.redSqr().redIAdd(p).redISub(y).redISub(y),R=u.redMul(y.redISub(A)).redISub(n.redMul(p)),O=this.z.redMul(f);return this.curve.jpoint(A,R,O)},Pr.prototype.dblp=function(r){if(r===0)return this;if(this.isInfinity())return this;if(!r)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var t=this;for(e=0;e=0)return!1;if(t.redIAdd(n),this.x.cmp(t)===0)return!0}},Pr.prototype.inspect=function(){return this.isInfinity()?"":""},Pr.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var Zf=wo(function(r,e){var t=e;t.base=_a,t.short=Fx,t.mont=null,t.edwards=null}),eh=wo(function(r,e){var t=e,i=Ai.assert;function n(u){u.type==="short"?this.curve=new Zf.short(u):u.type==="edwards"?this.curve=new Zf.edwards(u):this.curve=new Zf.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,i(this.g.validate(),"Invalid curve"),i(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}t.PresetCurve=n;function a(u,b){Object.defineProperty(t,u,{configurable:!0,enumerable:!0,get:function(){var p=new n(b);return Object.defineProperty(t,u,{configurable:!0,enumerable:!0,value:p}),p}})}a("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:Sn.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),a("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:Sn.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),a("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:Sn.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),a("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:Sn.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),a("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:Sn.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),a("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Sn.sha256,gRed:!1,g:["9"]}),a("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Sn.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var f;try{f=null.crash()}catch{f=void 0}a("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:Sn.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",f]})});function Ds(r){if(!(this instanceof Ds))return new Ds(r);this.hash=r.hash,this.predResist=!!r.predResist,this.outLen=this.hash.outSize,this.minEntropy=r.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=ln.toArray(r.entropy,r.entropyEnc||"hex"),t=ln.toArray(r.nonce,r.nonceEnc||"hex"),i=ln.toArray(r.pers,r.persEnc||"hex");K0(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,t,i)}var ng=Ds;Ds.prototype._init=function(r,e,t){var i=r.concat(e).concat(t);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var n=0;n=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(r.concat(t||[])),this._reseed=1},Ds.prototype.generate=function(r,e,t,i){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof e!="string"&&(i=t,t=e,e=null),t&&(t=ln.toArray(t,i||"hex"),this._update(t));for(var n=[];n.length"};var Bx=Ai.assert;function jh(r,e){if(r instanceof jh)return r;this._importDER(r,e)||(Bx(r.r&&r.s,"Signature without r or s"),this.r=new vt(r.r,16),this.s=new vt(r.s,16),r.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=r.recoveryParam)}var jf=jh;function qx(){this.place=0}function Ol(r,e){var t=r[e.place++];if(!(t&128))return t;var i=t&15;if(i===0||i>4)return!1;for(var n=0,a=0,f=e.place;a>>=0;return n<=127?!1:(e.place=f,n)}function sg(r){for(var e=0,t=r.length-1;!r[e]&&!(r[e+1]&128)&&e>>3);for(r.push(t|128);--t;)r.push(e>>>(t<<3)&255);r.push(e)}jh.prototype.toDER=function(r){var e=this.r.toArray(),t=this.s.toArray();for(e[0]&128&&(e=[0].concat(e)),t[0]&128&&(t=[0].concat(t)),e=sg(e),t=sg(t);!t[0]&&!(t[1]&128);)t=t.slice(1);var i=[2];Rl(i,e.length),i=i.concat(e),i.push(2),Rl(i,t.length);var n=i.concat(t),a=[48];return Rl(a,n.length),a=a.concat(n),Ai.encode(a,r)};var Lx=function(){throw new Error("unsupported")},p2=Ai.assert;function Ui(r){if(!(this instanceof Ui))return new Ui(r);typeof r=="string"&&(p2(Object.prototype.hasOwnProperty.call(eh,r),"Unknown curve "+r),r=eh[r]),r instanceof eh.PresetCurve&&(r={curve:r}),this.curve=r.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=r.curve.g,this.g.precompute(r.curve.n.bitLength()+1),this.hash=r.hash||r.curve.hash}var Ux=Ui;Ui.prototype.keyPair=function(r){return new Pl(this,r)},Ui.prototype.keyFromPrivate=function(r,e){return Pl.fromPrivate(this,r,e)},Ui.prototype.keyFromPublic=function(r,e){return Pl.fromPublic(this,r,e)},Ui.prototype.genKeyPair=function(r){r||(r={});for(var e=new ng({hash:this.hash,pers:r.pers,persEnc:r.persEnc||"utf8",entropy:r.entropy||Lx(this.hash.hmacStrength),entropyEnc:r.entropy&&r.entropyEnc||"utf8",nonce:this.n.toArray()}),t=this.n.byteLength(),i=this.n.sub(new vt(2));;){var n=new vt(e.generate(t));if(!(n.cmp(i)>0))return n.iaddn(1),this.keyFromPrivate(n)}},Ui.prototype._truncateToN=function(r,e){var t=r.byteLength()*8-this.n.bitLength();return t>0&&(r=r.ushrn(t)),!e&&r.cmp(this.n)>=0?r.sub(this.n):r},Ui.prototype.sign=function(r,e,t,i){typeof t=="object"&&(i=t,t=null),i||(i={}),e=this.keyFromPrivate(e,t),r=this._truncateToN(new vt(r,16));for(var n=this.n.byteLength(),a=e.getPrivate().toArray("be",n),f=r.toArray("be",n),u=new ng({hash:this.hash,entropy:a,nonce:f,pers:i.pers,persEnc:i.persEnc||"utf8"}),b=this.n.sub(new vt(1)),p=0;;p++){var y=i.k?i.k(p):new vt(u.generate(this.n.byteLength()));if(y=this._truncateToN(y,!0),!(y.cmpn(1)<=0||y.cmp(b)>=0)){var A=this.g.mul(y);if(!A.isInfinity()){var R=A.getX(),O=R.umod(this.n);if(O.cmpn(0)!==0){var N=y.invm(this.n).mul(O.mul(e.getPrivate()).iadd(r));if(N=N.umod(this.n),N.cmpn(0)!==0){var K=(A.getY().isOdd()?1:0)|(R.cmp(O)!==0?2:0);return i.canonical&&N.cmp(this.nh)>0&&(N=this.n.sub(N),K^=1),new jf({r:O,s:N,recoveryParam:K})}}}}}},Ui.prototype.verify=function(r,e,t,i){r=this._truncateToN(new vt(r,16)),t=this.keyFromPublic(t,i),e=new jf(e,"hex");var n=e.r,a=e.s;if(n.cmpn(1)<0||n.cmp(this.n)>=0||a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var f=a.invm(this.n),u=f.mul(r).umod(this.n),b=f.mul(n).umod(this.n),p;return this.curve._maxwellTrick?(p=this.g.jmulAdd(u,t.getPublic(),b),p.isInfinity()?!1:p.eqXToP(n)):(p=this.g.mulAdd(u,t.getPublic(),b),p.isInfinity()?!1:p.getX().umod(this.n).cmp(n)===0)},Ui.prototype.recoverPubKey=function(r,e,t,i){p2((3&t)===t,"The recovery param is more than two bits"),e=new jf(e,i);var n=this.n,a=new vt(r),f=e.r,u=e.s,b=t&1,p=t>>1;if(f.cmp(this.curve.p.umod(this.curve.n))>=0&&p)throw new Error("Unable to find sencond key candinate");p?f=this.curve.pointFromX(f.add(this.curve.n),b):f=this.curve.pointFromX(f,b);var y=e.r.invm(n),A=n.sub(a).mul(y).umod(n),R=u.mul(y).umod(n);return this.g.mulAdd(A,f,R)},Ui.prototype.getKeyRecoveryParam=function(r,e,t,i){if(e=new jf(e,i),e.recoveryParam!==null)return e.recoveryParam;for(var n=0;n<4;n++){var a;try{a=this.recoverPubKey(r,e,n)}catch{continue}if(a.eq(t))return n}throw new Error("Unable to find valid recovery factor")};var $x=wo(function(r,e){var t=e;t.version="6.5.4",t.utils=Ai,t.rand=function(){throw new Error("unsupported")},t.curve=Zf,t.curves=eh,t.ec=Ux,t.eddsa=null}),zx=$x.ec;const jx="signing-key/5.7.0",h0=new Or(jx);let Nl=null;function Ns(){return Nl||(Nl=new zx("secp256k1")),Nl}class kx{constructor(e){Go(this,"curve","secp256k1"),Go(this,"privateKey",ci(e)),IA(this.privateKey)!==32&&h0.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");const t=Ns().keyFromPrivate(ir(this.privateKey));Go(this,"publicKey","0x"+t.getPublic(!1,"hex")),Go(this,"compressedPublicKey","0x"+t.getPublic(!0,"hex")),Go(this,"_isSigningKey",!0)}_addPoint(e){const t=Ns().keyFromPublic(ir(this.publicKey)),i=Ns().keyFromPublic(ir(e));return"0x"+t.pub.add(i.pub).encodeCompressed("hex")}signDigest(e){const t=Ns().keyFromPrivate(ir(this.privateKey)),i=ir(e);i.length!==32&&h0.throwArgumentError("bad digest length","digest",e);const n=t.sign(i,{canonical:!0});return Ub({recoveryParam:n.recoveryParam,r:Dn("0x"+n.r.toString(16),32),s:Dn("0x"+n.s.toString(16),32)})}computeSharedSecret(e){const t=Ns().keyFromPrivate(ir(this.privateKey)),i=Ns().keyFromPublic(ir(g2(e)));return Dn("0x"+t.derive(i.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}}function Hx(r,e){const t=Ub(e),i={r:ir(t.r),s:ir(t.s)};return"0x"+Ns().recoverPubKey(ir(r),i,t.recoveryParam).encode("hex",!1)}function g2(r,e){const t=ir(r);return t.length===32?new kx(t).publicKey:t.length===33?"0x"+Ns().keyFromPublic(t).getPublic(!1,"hex"):t.length===65?ci(t):h0.throwArgumentError("invalid public or private key","key","[REDACTED]")}var ag;(function(r){r[r.legacy=0]="legacy",r[r.eip2930=1]="eip2930",r[r.eip1559=2]="eip1559"})(ag||(ag={}));function Kx(r){const e=g2(r);return rE(K1(j0(K1(e,1)),12))}function Vx(r,e){return Kx(Hx(ir(r),e))}const Gx="https://rpc.walletconnect.org/v1";async function Wx(r,e,t,i,n,a){switch(t.t){case"eip191":return Jx(r,e,t.s);case"eip1271":return await Yx(r,e,t.s,i,n,a);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}function Jx(r,e,t){return Vx(Wb(e),t).toLowerCase()===r.toLowerCase()}async function Yx(r,e,t,i,n,a){try{const f="0x1626ba7e",u="0000000000000000000000000000000000000000000000000000000000000040",b="0000000000000000000000000000000000000000000000000000000000000041",p=t.substring(2),y=Wb(e).substring(2),A=f+y+u+b+p,R=await fetch(`${a||Gx}/?chainId=${i}&projectId=${n}`,{method:"POST",body:JSON.stringify({id:Qx(),jsonrpc:"2.0",method:"eth_call",params:[{to:r,data:A},"latest"]})}),{result:O}=await R.json();return O?O.slice(0,f.length).toLowerCase()===f.toLowerCase():!1}catch(f){return console.error("isValidEip1271Signature: ",f),!1}}function Qx(){return Date.now()+Math.floor(Math.random()*1e3)}var Xx=Object.defineProperty,Zx=Object.defineProperties,eS=Object.getOwnPropertyDescriptors,og=Object.getOwnPropertySymbols,tS=Object.prototype.hasOwnProperty,rS=Object.prototype.propertyIsEnumerable,cg=(r,e,t)=>e in r?Xx(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,iS=(r,e)=>{for(var t in e||(e={}))tS.call(e,t)&&cg(r,t,e[t]);if(og)for(var t of og(e))rS.call(e,t)&&cg(r,t,e[t]);return r},nS=(r,e)=>Zx(r,eS(e));const sS="did:pkh:",G0=r=>r==null?void 0:r.split(":"),v2=r=>{const e=r&&G0(r);if(e)return r.includes(sS)?e[3]:e[1]},fg=r=>{const e=r&&G0(r);if(e)return e[2]+":"+e[3]},mh=r=>{const e=r&&G0(r);if(e)return e.pop()};async function hg(r){const{cacao:e,projectId:t}=r,{s:i,p:n}=e,a=b2(n,n.iss),f=mh(n.iss);return await Wx(f,a,i,v2(n.iss),t)}const b2=(r,e)=>{const t=`${r.domain} wants you to sign in with your Ethereum account:`,i=mh(e);if(!r.aud&&!r.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let n=r.statement||void 0;const a=`URI: ${r.aud||r.uri}`,f=`Version: ${r.version}`,u=`Chain ID: ${v2(e)}`,b=`Nonce: ${r.nonce}`,p=`Issued At: ${r.iat}`,y=r.exp?`Expiration Time: ${r.exp}`:void 0,A=r.nbf?`Not Before: ${r.nbf}`:void 0,R=r.requestId?`Request ID: ${r.requestId}`:void 0,O=r.resources?`Resources:${r.resources.map(K=>` +- ${K}`).join("")}`:void 0,N=th(r.resources);if(N){const K=gc(N);n=pS(n,K)}return[t,i,"",n,"",a,f,u,b,p,y,A,R,O].filter(K=>K!=null).join(` +`)};function aS(r){return Buffer.from(JSON.stringify(r)).toString("base64")}function oS(r){return JSON.parse(Buffer.from(r,"base64").toString("utf-8"))}function va(r){if(!r)throw new Error("No recap provided, value is undefined");if(!r.att)throw new Error("No `att` property found");const e=Object.keys(r.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=r.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(n=>{const a=i[n];if(!Array.isArray(a))throw new Error(`Ability limits ${n} must be an array of objects, found: ${a}`);if(!a.length)throw new Error(`Value of ${n} is empty array, must be an array with objects`);a.forEach(f=>{if(typeof f!="object")throw new Error(`Ability limits (${n}) must be an array of objects, found: ${f}`)})})})}function cS(r,e,t,i={}){return t==null||t.sort((n,a)=>n.localeCompare(a)),{att:{[r]:fS(e,t,i)}}}function fS(r,e,t={}){e=e==null?void 0:e.sort((n,a)=>n.localeCompare(a));const i=e.map(n=>({[`${r}/${n}`]:[t]}));return Object.assign({},...i)}function m2(r){return va(r),`urn:recap:${aS(r).replace(/=/g,"")}`}function gc(r){const e=oS(r.replace("urn:recap:",""));return va(e),e}function hS(r,e,t){const i=cS(r,e,t);return m2(i)}function uS(r){return r&&r.includes("urn:recap:")}function lS(r,e){const t=gc(r),i=gc(e),n=dS(t,i);return m2(n)}function dS(r,e){va(r),va(e);const t=Object.keys(r.att).concat(Object.keys(e.att)).sort((n,a)=>n.localeCompare(a)),i={att:{}};return t.forEach(n=>{var a,f;Object.keys(((a=r.att)==null?void 0:a[n])||{}).concat(Object.keys(((f=e.att)==null?void 0:f[n])||{})).sort((u,b)=>u.localeCompare(b)).forEach(u=>{var b,p;i.att[n]=nS(iS({},i.att[n]),{[u]:((b=r.att[n])==null?void 0:b[u])||((p=e.att[n])==null?void 0:p[u])})})}),i}function pS(r="",e){va(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(r.includes(t))return r;const i=[];let n=0;Object.keys(e.att).forEach(u=>{const b=Object.keys(e.att[u]).map(A=>({ability:A.split("/")[0],action:A.split("/")[1]}));b.sort((A,R)=>A.action.localeCompare(R.action));const p={};b.forEach(A=>{p[A.ability]||(p[A.ability]=[]),p[A.ability].push(A.action)});const y=Object.keys(p).map(A=>(n++,`(${n}) '${A}': '${p[A].join("', '")}' for '${u}'.`));i.push(y.join(", ").replace(".,","."))});const a=i.join(" "),f=`${t}${a}`;return`${r?r+" ":""}${f}`}function ug(r){var e;const t=gc(r);va(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(n=>n.split("/")[1]):[]}function lg(r){const e=gc(r);va(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(n=>{var a;(a=n==null?void 0:n[0])!=null&&a.chains&&t.push(n[0].chains)})}),[...new Set(t.flat())]}function th(r){if(!r)return;const e=r==null?void 0:r[r.length-1];return uS(e)?e:void 0}const y2="base10",Jr="base16",Bs="base64pad",Yo="base64url",Pc="utf8",w2=0,ds=1,Oc=2,gS=0,dg=1,fc=12,W0=32;function vS(){const r=C0.generateKeyPair();return{privateKey:Er(r.secretKey,Jr),publicKey:Er(r.publicKey,Jr)}}function u0(){const r=$s.randomBytes(W0);return Er(r,Jr)}function bS(r,e){const t=C0.sharedKey(Ar(r,Jr),Ar(e,Jr),!0),i=new d_(Ac.SHA256,t).expand(W0);return Er(i,Jr)}function rh(r){const e=Ac.hash(Ar(r,Jr));return Er(e,Jr)}function fs(r){const e=Ac.hash(Ar(r,Pc));return Er(e,Jr)}function _2(r){return Ar(`${r}`,y2)}function ba(r){return Number(Er(r,y2))}function mS(r){const e=_2(typeof r.type<"u"?r.type:w2);if(ba(e)===ds&&typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof r.senderPublicKey<"u"?Ar(r.senderPublicKey,Jr):void 0,i=typeof r.iv<"u"?Ar(r.iv,Jr):$s.randomBytes(fc),n=new R0.ChaCha20Poly1305(Ar(r.symKey,Jr)).seal(i,Ar(r.message,Pc));return A2({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:r.encoding})}function yS(r,e){const t=_2(Oc),i=$s.randomBytes(fc),n=Ar(r,Pc);return A2({type:t,sealed:n,iv:i,encoding:e})}function wS(r){const e=new R0.ChaCha20Poly1305(Ar(r.symKey,Jr)),{sealed:t,iv:i}=vc({encoded:r.encoded,encoding:r==null?void 0:r.encoding}),n=e.open(i,t);if(n===null)throw new Error("Failed to decrypt");return Er(n,Pc)}function _S(r,e){const{sealed:t}=vc({encoded:r,encoding:e});return Er(t,Pc)}function A2(r){const{encoding:e=Bs}=r;if(ba(r.type)===Oc)return Er(Yf([r.type,r.sealed]),e);if(ba(r.type)===ds){if(typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Er(Yf([r.type,r.senderPublicKey,r.iv,r.sealed]),e)}return Er(Yf([r.type,r.iv,r.sealed]),e)}function vc(r){const{encoded:e,encoding:t=Bs}=r,i=Ar(e,t),n=i.slice(gS,dg),a=dg;if(ba(n)===ds){const p=a+W0,y=p+fc,A=i.slice(a,p),R=i.slice(p,y),O=i.slice(y);return{type:n,sealed:O,iv:R,senderPublicKey:A}}if(ba(n)===Oc){const p=i.slice(a),y=$s.randomBytes(fc);return{type:n,sealed:p,iv:y}}const f=a+fc,u=i.slice(a,f),b=i.slice(f);return{type:n,sealed:b,iv:u}}function AS(r,e){const t=vc({encoded:r,encoding:e==null?void 0:e.encoding});return E2({type:ba(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Er(t.senderPublicKey,Jr):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function E2(r){const e=(r==null?void 0:r.type)||w2;if(e===ds){if(typeof(r==null?void 0:r.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(r==null?void 0:r.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:r==null?void 0:r.senderPublicKey,receiverPublicKey:r==null?void 0:r.receiverPublicKey}}function pg(r){return r.type===ds&&typeof r.senderPublicKey=="string"&&typeof r.receiverPublicKey=="string"}function gg(r){return r.type===Oc}function ES(r){return new Yv.ec("p256").keyFromPublic({x:Buffer.from(r.x,"base64").toString("hex"),y:Buffer.from(r.y,"base64").toString("hex")},"hex")}function xS(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function SS(r){return Buffer.from(xS(r),"base64")}function IS(r,e){const[t,i,n]=r.split("."),a=SS(n);if(a.length!==64)throw new Error("Invalid signature length");const f=a.slice(0,32).toString("hex"),u=a.slice(32,64).toString("hex"),b=`${t}.${i}`,p=new Ac.SHA256().update(Buffer.from(b)).digest(),y=ES(e),A=Buffer.from(p).toString("hex");if(!y.verify(A,{r:f,s:u}))throw new Error("Invalid signature");return n0(r).payload}const MS="irn";function l0(r){return(r==null?void 0:r.relay)||{protocol:MS}}function nc(r){const e=X9[r];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${r}`);return e}var PS=Object.defineProperty,OS=Object.defineProperties,RS=Object.getOwnPropertyDescriptors,vg=Object.getOwnPropertySymbols,NS=Object.prototype.hasOwnProperty,CS=Object.prototype.propertyIsEnumerable,bg=(r,e,t)=>e in r?PS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,mg=(r,e)=>{for(var t in e||(e={}))NS.call(e,t)&&bg(r,t,e[t]);if(vg)for(var t of vg(e))CS.call(e,t)&&bg(r,t,e[t]);return r},TS=(r,e)=>OS(r,RS(e));function DS(r,e="-"){const t={},i="relay"+e;return Object.keys(r).forEach(n=>{if(n.startsWith(i)){const a=n.replace(i,""),f=r[n];t[a]=f}}),t}function yg(r){if(!r.includes("wc:")){const b=Fb(r);b!=null&&b.includes("wc:")&&(r=b)}r=r.includes("wc://")?r.replace("wc://",""):r,r=r.includes("wc:")?r.replace("wc:",""):r;const e=r.indexOf(":"),t=r.indexOf("?")!==-1?r.indexOf("?"):void 0,i=r.substring(0,e),n=r.substring(e+1,t).split("@"),a=typeof t<"u"?r.substring(t):"",f=dc.parse(a),u=typeof f.methods=="string"?f.methods.split(","):void 0;return{protocol:i,topic:FS(n[0]),version:parseInt(n[1],10),symKey:f.symKey,relay:DS(f),methods:u,expiryTimestamp:f.expiryTimestamp?parseInt(f.expiryTimestamp,10):void 0}}function FS(r){return r.startsWith("//")?r.substring(2):r}function BS(r,e="-"){const t="relay",i={};return Object.keys(r).forEach(n=>{const a=t+e+n;r[n]&&(i[a]=r[n])}),i}function wg(r){return`${r.protocol}:${r.topic}@${r.version}?`+dc.stringify(mg(TS(mg({symKey:r.symKey},BS(r.relay)),{expiryTimestamp:r.expiryTimestamp}),r.methods?{methods:r.methods.join(",")}:{}))}function kf(r,e,t){return`${r}?wc_ev=${t}&topic=${e}`}function _o(r){const e=[];return r.forEach(t=>{const[i,n]=t.split(":");e.push(`${i}:${n}`)}),e}function qS(r){const e=[];return Object.values(r).forEach(t=>{e.push(..._o(t.accounts))}),e}function LS(r,e){const t=[];return Object.values(r).forEach(i=>{_o(i.accounts).includes(e)&&t.push(...i.methods)}),t}function US(r,e){const t=[];return Object.values(r).forEach(i=>{_o(i.accounts).includes(e)&&t.push(...i.events)}),t}function J0(r){return r.includes(":")}function sc(r){return J0(r)?r.split(":")[0]:r}function $S(r){const e={};return r==null||r.forEach(t=>{const[i,n]=t.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[]}),e[i].accounts.push(t),e[i].chains.push(`${i}:${n}`)}),e}function _g(r,e){e=e.map(i=>i.replace("did:pkh:",""));const t=$S(e);for(const[i,n]of Object.entries(t))n.methods?n.methods=Qf(n.methods,r):n.methods=r,n.events=["chainChanged","accountsChanged"];return t}const zS={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},jS={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Ae(r,e){const{message:t,code:i}=jS[r];return{message:e?`${t} ${e}`:t,code:i}}function Ut(r,e){const{message:t,code:i}=zS[r];return{message:e?`${t} ${e}`:t,code:i}}function jn(r,e){return!!Array.isArray(r)}function bc(r){return Object.getPrototypeOf(r)===Object.prototype&&Object.keys(r).length}function fi(r){return typeof r>"u"}function fr(r,e){return e&&fi(r)?!0:typeof r=="string"&&!!r.trim().length}function Y0(r,e){return typeof r=="number"&&!isNaN(r)}function kS(r,e){const{requiredNamespaces:t}=e,i=Object.keys(r.namespaces),n=Object.keys(t);let a=!0;return fa(n,i)?(i.forEach(f=>{const{accounts:u,methods:b,events:p}=r.namespaces[f],y=_o(u),A=t[f];(!fa(Pb(f,A),y)||!fa(A.methods,b)||!fa(A.events,p))&&(a=!1)}),a):!1}function yh(r){return fr(r,!1)&&r.includes(":")?r.split(":").length===2:!1}function HS(r){if(fr(r,!1)&&r.includes(":")){const e=r.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&yh(t)}}return!1}function KS(r){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(fr(r,!1)){if(e(r))return!0;const t=Fb(r);return e(t)}}catch{}return!1}function VS(r){var e;return(e=r==null?void 0:r.proposer)==null?void 0:e.publicKey}function GS(r){return r==null?void 0:r.topic}function WS(r,e){let t=null;return fr(r==null?void 0:r.publicKey,!1)||(t=Ae("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function Ag(r){let e=!0;return jn(r)?r.length&&(e=r.every(t=>fr(t,!1))):e=!1,e}function JS(r,e,t){let i=null;return jn(e)&&e.length?e.forEach(n=>{i||yh(n)||(i=Ut("UNSUPPORTED_CHAINS",`${t}, chain ${n} should be a string and conform to "namespace:chainId" format`))}):yh(r)||(i=Ut("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function YS(r,e,t){let i=null;return Object.entries(r).forEach(([n,a])=>{if(i)return;const f=JS(n,Pb(n,a),`${e} ${t}`);f&&(i=f)}),i}function QS(r,e){let t=null;return jn(r)?r.forEach(i=>{t||HS(i)||(t=Ut("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Ut("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function XS(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const n=QS(i==null?void 0:i.accounts,`${e} namespace`);n&&(t=n)}),t}function ZS(r,e){let t=null;return Ag(r==null?void 0:r.methods)?Ag(r==null?void 0:r.events)||(t=Ut("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Ut("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function x2(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const n=ZS(i,`${e}, namespace`);n&&(t=n)}),t}function eI(r,e,t){let i=null;if(r&&bc(r)){const n=x2(r,e);n&&(i=n);const a=YS(r,e,t);a&&(i=a)}else i=Ae("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function Cl(r,e){let t=null;if(r&&bc(r)){const i=x2(r,e);i&&(t=i);const n=XS(r,e);n&&(t=n)}else t=Ae("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function S2(r){return fr(r.protocol,!0)}function tI(r,e){let t=!1;return r?r&&jn(r)&&r.length&&r.forEach(i=>{t=S2(i)}):t=!0,t}function rI(r){return typeof r=="number"}function oi(r){return typeof r<"u"&&typeof r!==null}function iI(r){return!(!r||typeof r!="object"||!r.code||!Y0(r.code)||!r.message||!fr(r.message,!1))}function nI(r){return!(fi(r)||!fr(r.method,!1))}function sI(r){return!(fi(r)||fi(r.result)&&fi(r.error)||!Y0(r.id)||!fr(r.jsonrpc,!1))}function aI(r){return!(fi(r)||!fr(r.name,!1))}function Eg(r,e){return!(!yh(e)||!qS(r).includes(e))}function oI(r,e,t){return fr(t,!1)?LS(r,e).includes(t):!1}function cI(r,e,t){return fr(t,!1)?US(r,e).includes(t):!1}function xg(r,e,t){let i=null;const n=fI(r),a=hI(e),f=Object.keys(n),u=Object.keys(a),b=Sg(Object.keys(r)),p=Sg(Object.keys(e)),y=b.filter(A=>!p.includes(A));return y.length&&(i=Ae("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces. + Required: ${y.toString()} + Received: ${Object.keys(e).toString()}`)),fa(f,u)||(i=Ae("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces. + Required: ${f.toString()} + Approved: ${u.toString()}`)),Object.keys(e).forEach(A=>{if(!A.includes(":")||i)return;const R=_o(e[A].accounts);R.includes(A)||(i=Ae("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${A} + Required: ${A} + Approved: ${R.toString()}`))}),f.forEach(A=>{i||(fa(n[A].methods,a[A].methods)?fa(n[A].events,a[A].events)||(i=Ae("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${A}`)):i=Ae("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${A}`))}),i}function fI(r){const e={};return Object.keys(r).forEach(t=>{var i;t.includes(":")?e[t]=r[t]:(i=r[t].chains)==null||i.forEach(n=>{e[n]={methods:r[t].methods,events:r[t].events}})}),e}function Sg(r){return[...new Set(r.map(e=>e.includes(":")?e.split(":")[0]:e))]}function hI(r){const e={};return Object.keys(r).forEach(t=>{if(t.includes(":"))e[t]=r[t];else{const i=_o(r[t].accounts);i==null||i.forEach(n=>{e[n]={accounts:r[t].accounts.filter(a=>a.includes(`${n}:`)),methods:r[t].methods,events:r[t].events}})}}),e}function uI(r,e){return Y0(r)&&r<=e.max&&r>=e.min}function Ig(){const r=Ic();return new Promise(e=>{switch(r){case wi.browser:e(lI());break;case wi.reactNative:e(dI());break;case wi.node:e(pI());break;default:e(!0)}})}function lI(){return Sc()&&(navigator==null?void 0:navigator.onLine)}async function dI(){if(vo()&&typeof global<"u"&&global!=null&&global.NetInfo){const r=await(global==null?void 0:global.NetInfo.fetch());return r==null?void 0:r.isConnected}return!0}function pI(){return!0}function gI(r){switch(Ic()){case wi.browser:vI(r);break;case wi.reactNative:bI(r);break}}function vI(r){!vo()&&Sc()&&(window.addEventListener("online",()=>r(!0)),window.addEventListener("offline",()=>r(!1)))}function bI(r){vo()&&typeof global<"u"&&global!=null&&global.NetInfo&&(global==null||global.NetInfo.addEventListener(e=>r(e==null?void 0:e.isConnected)))}const Tl={};class Qo{static get(e){return Tl[e]}static set(e,t){Tl[e]=t}static delete(e){delete Tl[e]}}class Aa{}let mI=class extends Aa{constructor(e){super()}};const Mg=xe.FIVE_SECONDS,Ao={pulse:"heartbeat_pulse"};let yI=class I2 extends mI{constructor(e){super(e),this.events=new Hi.EventEmitter,this.interval=Mg,this.interval=(e==null?void 0:e.interval)||Mg}static async init(e){const t=new I2(e);return await t.init(),t}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),xe.toMiliseconds(this.interval))}pulse(){this.events.emit(Ao.pulse)}};const wI=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,_I=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,AI=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function EI(r,e){if(r==="__proto__"||r==="constructor"&&e&&typeof e=="object"&&"prototype"in e){xI(r);return}return e}function xI(r){console.warn(`[destr] Dropping "${r}" key to prevent prototype pollution.`)}function Hf(r,e={}){if(typeof r!="string")return r;const t=r.trim();if(r[0]==='"'&&r.endsWith('"')&&!r.includes("\\"))return t.slice(1,-1);if(t.length<=9){const i=t.toLowerCase();if(i==="true")return!0;if(i==="false")return!1;if(i==="undefined")return;if(i==="null")return null;if(i==="nan")return Number.NaN;if(i==="infinity")return Number.POSITIVE_INFINITY;if(i==="-infinity")return Number.NEGATIVE_INFINITY}if(!AI.test(r)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return r}try{if(wI.test(r)||_I.test(r)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(r,EI)}return JSON.parse(r)}catch(i){if(e.strict)throw i;return r}}function SI(r){return!r||typeof r.then!="function"?Promise.resolve(r):r}function _r(r,...e){try{return SI(r(...e))}catch(t){return Promise.reject(t)}}function II(r){const e=typeof r;return r===null||e!=="object"&&e!=="function"}function MI(r){const e=Object.getPrototypeOf(r);return!e||e.isPrototypeOf(Object)}function ih(r){if(II(r))return String(r);if(MI(r)||Array.isArray(r))return JSON.stringify(r);if(typeof r.toJSON=="function")return ih(r.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function M2(){if(typeof Buffer>"u")throw new TypeError("[unstorage] Buffer is not supported!")}const d0="base64:";function PI(r){if(typeof r=="string")return r;M2();const e=Buffer.from(r).toString("base64");return d0+e}function OI(r){return typeof r!="string"||!r.startsWith(d0)?r:(M2(),Buffer.from(r.slice(d0.length),"base64"))}function ai(r){return r?r.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function RI(...r){return ai(r.join(":"))}function Kf(r){return r=ai(r),r?r+":":""}const NI="memory",CI=()=>{const r=new Map;return{name:NI,getInstance:()=>r,hasItem(e){return r.has(e)},getItem(e){return r.get(e)??null},getItemRaw(e){return r.get(e)??null},setItem(e,t){r.set(e,t)},setItemRaw(e,t){r.set(e,t)},removeItem(e){r.delete(e)},getKeys(){return[...r.keys()]},clear(){r.clear()},dispose(){r.clear()}}};function TI(r={}){const e={mounts:{"":r.driver||CI()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=p=>{for(const y of e.mountpoints)if(p.startsWith(y))return{base:y,relativeKey:p.slice(y.length),driver:e.mounts[y]};return{base:"",relativeKey:p,driver:e.mounts[""]}},i=(p,y)=>e.mountpoints.filter(A=>A.startsWith(p)||y&&p.startsWith(A)).map(A=>({relativeBase:p.length>A.length?p.slice(A.length):void 0,mountpoint:A,driver:e.mounts[A]})),n=(p,y)=>{if(e.watching){y=ai(y);for(const A of e.watchListeners)A(p,y)}},a=async()=>{if(!e.watching){e.watching=!0;for(const p in e.mounts)e.unwatch[p]=await Pg(e.mounts[p],n,p)}},f=async()=>{if(e.watching){for(const p in e.unwatch)await e.unwatch[p]();e.unwatch={},e.watching=!1}},u=(p,y,A)=>{const R=new Map,O=N=>{let K=R.get(N.base);return K||(K={driver:N.driver,base:N.base,items:[]},R.set(N.base,K)),K};for(const N of p){const K=typeof N=="string",W=ai(K?N:N.key),Q=K?void 0:N.value,j=K||!N.options?y:{...y,...N.options},Y=t(W);O(Y).items.push({key:W,value:Q,relativeKey:Y.relativeKey,options:j})}return Promise.all([...R.values()].map(N=>A(N))).then(N=>N.flat())},b={hasItem(p,y={}){p=ai(p);const{relativeKey:A,driver:R}=t(p);return _r(R.hasItem,A,y)},getItem(p,y={}){p=ai(p);const{relativeKey:A,driver:R}=t(p);return _r(R.getItem,A,y).then(O=>Hf(O))},getItems(p,y){return u(p,y,A=>A.driver.getItems?_r(A.driver.getItems,A.items.map(R=>({key:R.relativeKey,options:R.options})),y).then(R=>R.map(O=>({key:RI(A.base,O.key),value:Hf(O.value)}))):Promise.all(A.items.map(R=>_r(A.driver.getItem,R.relativeKey,R.options).then(O=>({key:R.key,value:Hf(O)})))))},getItemRaw(p,y={}){p=ai(p);const{relativeKey:A,driver:R}=t(p);return R.getItemRaw?_r(R.getItemRaw,A,y):_r(R.getItem,A,y).then(O=>OI(O))},async setItem(p,y,A={}){if(y===void 0)return b.removeItem(p);p=ai(p);const{relativeKey:R,driver:O}=t(p);O.setItem&&(await _r(O.setItem,R,ih(y),A),O.watch||n("update",p))},async setItems(p,y){await u(p,y,async A=>{if(A.driver.setItems)return _r(A.driver.setItems,A.items.map(R=>({key:R.relativeKey,value:ih(R.value),options:R.options})),y);A.driver.setItem&&await Promise.all(A.items.map(R=>_r(A.driver.setItem,R.relativeKey,ih(R.value),R.options)))})},async setItemRaw(p,y,A={}){if(y===void 0)return b.removeItem(p,A);p=ai(p);const{relativeKey:R,driver:O}=t(p);if(O.setItemRaw)await _r(O.setItemRaw,R,y,A);else if(O.setItem)await _r(O.setItem,R,PI(y),A);else return;O.watch||n("update",p)},async removeItem(p,y={}){typeof y=="boolean"&&(y={removeMeta:y}),p=ai(p);const{relativeKey:A,driver:R}=t(p);R.removeItem&&(await _r(R.removeItem,A,y),(y.removeMeta||y.removeMata)&&await _r(R.removeItem,A+"$",y),R.watch||n("remove",p))},async getMeta(p,y={}){typeof y=="boolean"&&(y={nativeOnly:y}),p=ai(p);const{relativeKey:A,driver:R}=t(p),O=Object.create(null);if(R.getMeta&&Object.assign(O,await _r(R.getMeta,A,y)),!y.nativeOnly){const N=await _r(R.getItem,A+"$",y).then(K=>Hf(K));N&&typeof N=="object"&&(typeof N.atime=="string"&&(N.atime=new Date(N.atime)),typeof N.mtime=="string"&&(N.mtime=new Date(N.mtime)),Object.assign(O,N))}return O},setMeta(p,y,A={}){return this.setItem(p+"$",y,A)},removeMeta(p,y={}){return this.removeItem(p+"$",y)},async getKeys(p,y={}){p=Kf(p);const A=i(p,!0);let R=[];const O=[];for(const N of A){const K=await _r(N.driver.getKeys,N.relativeBase,y);for(const W of K){const Q=N.mountpoint+ai(W);R.some(j=>Q.startsWith(j))||O.push(Q)}R=[N.mountpoint,...R.filter(W=>!W.startsWith(N.mountpoint))]}return p?O.filter(N=>N.startsWith(p)&&N[N.length-1]!=="$"):O.filter(N=>N[N.length-1]!=="$")},async clear(p,y={}){p=Kf(p),await Promise.all(i(p,!1).map(async A=>{if(A.driver.clear)return _r(A.driver.clear,A.relativeBase,y);if(A.driver.removeItem){const R=await A.driver.getKeys(A.relativeBase||"",y);return Promise.all(R.map(O=>A.driver.removeItem(O,y)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(p=>Og(p)))},async watch(p){return await a(),e.watchListeners.push(p),async()=>{e.watchListeners=e.watchListeners.filter(y=>y!==p),e.watchListeners.length===0&&await f()}},async unwatch(){e.watchListeners=[],await f()},mount(p,y){if(p=Kf(p),p&&e.mounts[p])throw new Error(`already mounted at ${p}`);return p&&(e.mountpoints.push(p),e.mountpoints.sort((A,R)=>R.length-A.length)),e.mounts[p]=y,e.watching&&Promise.resolve(Pg(y,n,p)).then(A=>{e.unwatch[p]=A}).catch(console.error),b},async unmount(p,y=!0){p=Kf(p),!(!p||!e.mounts[p])&&(e.watching&&p in e.unwatch&&(e.unwatch[p](),delete e.unwatch[p]),y&&await Og(e.mounts[p]),e.mountpoints=e.mountpoints.filter(A=>A!==p),delete e.mounts[p])},getMount(p=""){p=ai(p)+":";const y=t(p);return{driver:y.driver,base:y.base}},getMounts(p="",y={}){return p=ai(p),i(p,y.parents).map(R=>({driver:R.driver,base:R.mountpoint}))},keys:(p,y={})=>b.getKeys(p,y),get:(p,y={})=>b.getItem(p,y),set:(p,y,A={})=>b.setItem(p,y,A),has:(p,y={})=>b.hasItem(p,y),del:(p,y={})=>b.removeItem(p,y),remove:(p,y={})=>b.removeItem(p,y)};return b}function Pg(r,e,t){return r.watch?r.watch((i,n)=>e(i,t+n)):()=>{}}async function Og(r){typeof r.dispose=="function"&&await _r(r.dispose)}function Ea(r){return new Promise((e,t)=>{r.oncomplete=r.onsuccess=()=>e(r.result),r.onabort=r.onerror=()=>t(r.error)})}function P2(r,e){const t=indexedDB.open(r);t.onupgradeneeded=()=>t.result.createObjectStore(e);const i=Ea(t);return(n,a)=>i.then(f=>a(f.transaction(e,n).objectStore(e)))}let Dl;function Rc(){return Dl||(Dl=P2("keyval-store","keyval")),Dl}function Rg(r,e=Rc()){return e("readonly",t=>Ea(t.get(r)))}function DI(r,e,t=Rc()){return t("readwrite",i=>(i.put(e,r),Ea(i.transaction)))}function FI(r,e=Rc()){return e("readwrite",t=>(t.delete(r),Ea(t.transaction)))}function BI(r=Rc()){return r("readwrite",e=>(e.clear(),Ea(e.transaction)))}function qI(r,e){return r.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Ea(r.transaction)}function LI(r=Rc()){return r("readonly",e=>{if(e.getAllKeys)return Ea(e.getAllKeys());const t=[];return qI(e,i=>t.push(i.key)).then(()=>t)})}const UI="idb-keyval";var $I=(r={})=>{const e=r.base&&r.base.length>0?`${r.base}:`:"",t=n=>e+n;let i;return r.dbName&&r.storeName&&(i=P2(r.dbName,r.storeName)),{name:UI,options:r,async hasItem(n){return!(typeof await Rg(t(n),i)>"u")},async getItem(n){return await Rg(t(n),i)??null},setItem(n,a){return DI(t(n),a,i)},removeItem(n){return FI(t(n),i)},getKeys(){return LI(i)},clear(){return BI(i)}}};const zI="WALLET_CONNECT_V2_INDEXED_DB",jI="keyvaluestorage";let kI=class{constructor(){this.indexedDb=TI({driver:$I({dbName:zI,storeName:jI})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,vs(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var Fl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},nh={exports:{}};(function(){let r;function e(){}r=e,r.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},r.prototype.setItem=function(t,i){this[t]=String(i)},r.prototype.removeItem=function(t){delete this[t]},r.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(i){t[i]=void 0,delete t[i]})},r.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},r.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Fl<"u"&&Fl.localStorage?nh.exports=Fl.localStorage:typeof window<"u"&&window.localStorage?nh.exports=window.localStorage:nh.exports=new e})();function HI(r){var e;return[r[0],ga((e=r[1])!=null?e:"")]}class KI{constructor(){this.localStorage=nh.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(HI)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return ga(t)}async setItem(e,t){this.localStorage.setItem(e,vs(t))}async removeItem(e){this.localStorage.removeItem(e)}}const VI="wc_storage_version",Ng=1,GI=async(r,e,t)=>{const i=VI,n=await e.getItem(i);if(n&&n>=Ng){t(e);return}const a=await r.getKeys();if(!a.length){t(e);return}const f=[];for(;a.length;){const u=a.shift();if(!u)continue;const b=u.toLowerCase();if(b.includes("wc@")||b.includes("walletconnect")||b.includes("wc_")||b.includes("wallet_connect")){const p=await r.getItem(u);await e.setItem(u,p),f.push(u)}}await e.setItem(i,Ng),t(e),WI(r,f)},WI=async(r,e)=>{e.length&&e.forEach(async t=>{await r.removeItem(t)})};let JI=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new KI;this.storage=e;try{const t=new kI;GI(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};function YI(r){try{return JSON.stringify(r)}catch{return'"[Circular]"'}}var QI=XI;function XI(r,e,t){var i=t&&t.stringify||YI,n=1;if(typeof r=="object"&&r!==null){var a=e.length+n;if(a===1)return r;var f=new Array(a);f[0]=i(r);for(var u=1;u-1?A:0,r.charCodeAt(O+1)){case 100:case 102:if(y>=b||e[y]==null)break;A=b||e[y]==null)break;A=b||e[y]===void 0)break;A",A=O+2,O++;break}p+=i(e[y]),A=O+2,O++;break;case 115:if(y>=b)break;A-1&&(a=!1);const f=["error","fatal","warn","info","debug","trace"];typeof t=="function"&&(t.error=t.fatal=t.warn=t.info=t.debug=t.trace=t),r.enabled===!1&&(r.level="silent");const u=r.level||"info",b=Object.create(t);b.log||(b.log=yc),Object.defineProperty(b,"levelVal",{get:y}),Object.defineProperty(b,"level",{get:A,set:R});const p={transmit:e,serialize:n,asObject:r.browser.asObject,levels:f,timestamp:sM(r)};b.levels=Ln.levels,b.level=u,b.setMaxListeners=b.getMaxListeners=b.emit=b.addListener=b.on=b.prependListener=b.once=b.prependOnceListener=b.removeListener=b.removeAllListeners=b.listeners=b.listenerCount=b.eventNames=b.write=b.flush=yc,b.serializers=i,b._serialize=n,b._stdErrSerialize=a,b.child=O,e&&(b._logEvent=p0());function y(){return this.level==="silent"?1/0:this.levels.values[this.level]}function A(){return this._level}function R(N){if(N!=="silent"&&!this.levels.values[N])throw Error("unknown level "+N);this._level=N,Ka(p,b,"error","log"),Ka(p,b,"fatal","error"),Ka(p,b,"warn","error"),Ka(p,b,"info","log"),Ka(p,b,"debug","log"),Ka(p,b,"trace","log")}function O(N,K){if(!N)throw new Error("missing bindings for child Pino");K=K||{},n&&N.serializers&&(K.serializers=N.serializers);const W=K.serializers;if(n&&W){var Q=Object.assign({},i,W),j=r.browser.serialize===!0?Object.keys(Q):n;delete N.serializers,kh([N],j,Q,this._stdErrSerialize)}function Y(U){this._childLevel=(U._childLevel|0)+1,this.error=Va(U,N,"error"),this.fatal=Va(U,N,"fatal"),this.warn=Va(U,N,"warn"),this.info=Va(U,N,"info"),this.debug=Va(U,N,"debug"),this.trace=Va(U,N,"trace"),Q&&(this.serializers=Q,this._serialize=j),e&&(this._logEvent=p0([].concat(U._logEvent.bindings,N)))}return Y.prototype=this,new Y(this)}return b}Ln.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};Ln.stdSerializers=ZI;Ln.stdTimeFunctions=Object.assign({},{nullTime:O2,epochTime:R2,unixTime:aM,isoTime:oM});function Ka(r,e,t,i){const n=Object.getPrototypeOf(e);e[t]=e.levelVal>e.levels.values[t]?yc:n[t]?n[t]:mc[t]||mc[i]||yc,tM(r,e,t)}function tM(r,e,t){!r.transmit&&e[t]===yc||(e[t]=function(i){return function(){const a=r.timestamp(),f=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===mc?mc:this;for(var b=0;b-1&&a in t&&(r[n][a]=t[a](r[n][a]))}function Va(r,e,t){return function(){const i=new Array(1+arguments.length);i[0]=e;for(var n=1;nthis.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;t!==null;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}},N2=class{constructor(e,t=Q0){this.level=e??"error",this.levelValue=Ja.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new Tg(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===Ja.levels.values.error?console.error(e):t===Ja.levels.values.warn?console.warn(e):t===Ja.levels.values.debug?console.debug(e):t===Ja.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(vs({timestamp:new Date().toISOString(),log:e}));const t=typeof e=="string"?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new Tg(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(vs({extraMetadata:e})),new Blob(t,{type:"application/json"})}},uM=class{constructor(e,t=Q0){this.baseChunkLogger=new N2(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=t,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}};class lM{constructor(e,t=Q0){this.baseChunkLogger=new N2(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var dM=Object.defineProperty,pM=Object.defineProperties,gM=Object.getOwnPropertyDescriptors,Dg=Object.getOwnPropertySymbols,vM=Object.prototype.hasOwnProperty,bM=Object.prototype.propertyIsEnumerable,Fg=(r,e,t)=>e in r?dM(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wh=(r,e)=>{for(var t in e||(e={}))vM.call(e,t)&&Fg(r,t,e[t]);if(Dg)for(var t of Dg(e))bM.call(e,t)&&Fg(r,t,e[t]);return r},_h=(r,e)=>pM(r,gM(e));function Hh(r){return _h(wh({},r),{level:(r==null?void 0:r.level)||fM.level})}function mM(r,e=Cc){return r[e]||""}function yM(r,e,t=Cc){return r[t]=e,r}function di(r,e=Cc){let t="";return typeof r.bindings>"u"?t=mM(r,e):t=r.bindings().context||"",t}function wM(r,e,t=Cc){const i=di(r,t);return i.trim()?`${i}/${e}`:e}function Yr(r,e,t=Cc){const i=wM(r,e,t),n=r.child({context:i});return yM(n,i,t)}function _M(r){var e,t;const i=new uM((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:Nc(_h(wh({},r.opts),{level:"trace",browser:_h(wh({},(t=r.opts)==null?void 0:t.browser),{write:n=>i.write(n)})})),chunkLoggerController:i}}function AM(r){var e;const t=new lM((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:Nc(_h(wh({},r.opts),{level:"trace"}),t),chunkLoggerController:t}}function EM(r){return typeof r.loggerOverride<"u"&&typeof r.loggerOverride!="string"?{logger:r.loggerOverride,chunkLoggerController:null}:typeof window<"u"?_M(r):AM(r)}let xM=class extends Aa{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},SM=class extends Aa{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}},IM=class{constructor(e,t){this.logger=e,this.core=t}},MM=class extends Aa{constructor(e,t){super(),this.relayer=e,this.logger=t}},PM=class extends Aa{constructor(e){super()}},OM=class{constructor(e,t,i,n){this.core=e,this.logger=t,this.name=i}},RM=class extends Aa{constructor(e,t){super(),this.relayer=e,this.logger=t}},NM=class extends Aa{constructor(e,t){super(),this.core=e,this.logger=t}},CM=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},TM=class{constructor(e,t){this.projectId=e,this.logger=t}},DM=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}},FM=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},BM=class{constructor(e){this.client=e}};const qM="PARSE_ERROR",LM="INVALID_REQUEST",UM="METHOD_NOT_FOUND",$M="INVALID_PARAMS",C2="INTERNAL_ERROR",X0="SERVER_ERROR",zM=[-32700,-32600,-32601,-32602,-32603],hc={[qM]:{code:-32700,message:"Parse error"},[LM]:{code:-32600,message:"Invalid Request"},[UM]:{code:-32601,message:"Method not found"},[$M]:{code:-32602,message:"Invalid params"},[C2]:{code:-32603,message:"Internal error"},[X0]:{code:-32e3,message:"Server error"}},T2=X0;function jM(r){return zM.includes(r)}function Bg(r){return Object.keys(hc).includes(r)?hc[r]:hc[T2]}function kM(r){const e=Object.values(hc).find(t=>t.code===r);return e||hc[T2]}function D2(r,e,t){return r.message.includes("getaddrinfo ENOTFOUND")||r.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${t} RPC url at ${e}`):r}var F2={};/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */var g0=function(r,e){return g0=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])},g0(r,e)};function HM(r,e){g0(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var v0=function(){return v0=Object.assign||function(e){for(var t,i=1,n=arguments.length;i=0;u--)(f=r[u])&&(a=(n<3?f(a):n>3?f(e,t,a):f(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a}function GM(r,e){return function(t,i){e(t,i,r)}}function WM(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function JM(r,e,t,i){function n(a){return a instanceof t?a:new t(function(f){f(a)})}return new(t||(t=Promise))(function(a,f){function u(y){try{p(i.next(y))}catch(A){f(A)}}function b(y){try{p(i.throw(y))}catch(A){f(A)}}function p(y){y.done?a(y.value):n(y.value).then(u,b)}p((i=i.apply(r,e||[])).next())})}function YM(r,e){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,n,a,f;return f={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function u(p){return function(y){return b([p,y])}}function b(p){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,n&&(a=p[0]&2?n.return:p[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,p[1])).done)return a;switch(n=0,a&&(p=[p[0]&2,a.value]),p[0]){case 0:case 1:a=p;break;case 4:return t.label++,{value:p[1],done:!1};case 5:t.label++,n=p[1],p=[0];continue;case 7:p=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(p[0]===6||p[0]===2)){t=0;continue}if(p[0]===3&&(!a||p[1]>a[0]&&p[1]=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function B2(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),n,a=[],f;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(u){f={error:u}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(f)throw f.error}}return a}function ZM(){for(var r=[],e=0;e1||u(R,O)})})}function u(R,O){try{b(i[R](O))}catch(N){A(a[0][3],N)}}function b(R){R.value instanceof wc?Promise.resolve(R.value.v).then(p,y):A(a[0][2],R)}function p(R){u("next",R)}function y(R){u("throw",R)}function A(R,O){R(O),a.shift(),a.length&&u(a[0][0],a[0][1])}}function rP(r){var e,t;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,a){e[n]=r[n]?function(f){return(t=!t)?{value:wc(r[n](f)),done:n==="return"}:a?a(f):f}:a}}function iP(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof b0=="function"?b0(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(a){t[a]=r[a]&&function(f){return new Promise(function(u,b){f=r[a](f),n(u,b,f.done,f.value)})}}function n(a,f,u,b){Promise.resolve(b).then(function(p){a({value:p,done:u})},f)}}function nP(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function sP(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function aP(r){return r&&r.__esModule?r:{default:r}}function oP(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function cP(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}const fP=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return v0},__asyncDelegator:rP,__asyncGenerator:tP,__asyncValues:iP,__await:wc,__awaiter:JM,__classPrivateFieldGet:oP,__classPrivateFieldSet:cP,__createBinding:QM,__decorate:VM,__exportStar:XM,__extends:HM,__generator:YM,__importDefault:aP,__importStar:sP,__makeTemplateObject:nP,__metadata:WM,__param:GM,__read:B2,__rest:KM,__spread:ZM,__spreadArrays:eP,__values:b0},Symbol.toStringTag,{value:"Module"})),hP=Tv(fP);var ss={},qg;function uP(){if(qg)return ss;qg=1,Object.defineProperty(ss,"__esModule",{value:!0}),ss.isBrowserCryptoAvailable=ss.getSubtleCrypto=ss.getBrowerCrypto=void 0;function r(){return(ji===null||ji===void 0?void 0:ji.crypto)||(ji===null||ji===void 0?void 0:ji.msCrypto)||{}}ss.getBrowerCrypto=r;function e(){const i=r();return i.subtle||i.webkitSubtle}ss.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return ss.isBrowserCryptoAvailable=t,ss}var as={},Lg;function lP(){if(Lg)return as;Lg=1,Object.defineProperty(as,"__esModule",{value:!0}),as.isBrowser=as.isNode=as.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}as.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}as.isNode=e;function t(){return!r()&&!e()}return as.isBrowser=t,as}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=hP;e.__exportStar(uP(),r),e.__exportStar(lP(),r)})(F2);function Cs(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function ha(r=6){return BigInt(Cs(r))}function qs(r,e,t){return{id:t||Cs(),jsonrpc:"2.0",method:r,params:e}}function Kh(r,e){return{id:r,jsonrpc:"2.0",result:e}}function Vh(r,e,t){return{id:r,jsonrpc:"2.0",error:dP(e)}}function dP(r,e){return typeof r>"u"?Bg(C2):(typeof r=="string"&&(r=Object.assign(Object.assign({},Bg(X0)),{message:r})),jM(r.code)&&(r=kM(r.code)),r)}class pP{}class gP extends pP{constructor(){super()}}class vP extends gP{constructor(e){super()}}const bP="^https?:",mP="^wss?:";function yP(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function q2(r,e){const t=yP(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function Ug(r){return q2(r,bP)}function $g(r){return q2(r,mP)}function wP(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function L2(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function Z0(r){return L2(r)&&"method"in r}function Gh(r){return L2(r)&&(Mn(r)||$i(r))}function Mn(r){return"result"in r}function $i(r){return"error"in r}let gn=class extends vP{constructor(e){super(e),this.events=new Hi.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(qs(e.method,e.params||[],e.id||ha().toString()),t)}async requestStrict(e,t){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(a){n(a)}this.events.on(`${e.id}`,a=>{$i(a)?n(a.error):i(a.result)});try{await this.connection.send(e,t)}catch(a){n(a)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Gh(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const _P=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),AP=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",zg=r=>r.split("?")[0],jg=10,EP=_P();let xP=class{constructor(e){if(this.url=e,this.events=new Hi.EventEmitter,this.registering=!1,!$g(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,t)=>{if(typeof this.socket>"u"){t(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(vs(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!$g(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,n)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),n(a)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,i)=>{const n=new URLSearchParams(e).get("origin"),a=F2.isReactNative()?{headers:{origin:n}}:{rejectUnauthorized:!wP(e)},f=new EP(e,[],a);AP()?f.onerror=u=>{const b=u;i(this.emitError(b.error))}:f.on("error",u=>{i(this.emitError(u))}),f.onopen=()=>{this.onOpen(f),t(f)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?ga(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),n=i.message||i.toString(),a=Vh(e,n);this.events.emit("payload",a)}parseError(e,t=this.url){return D2(e,zg(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>jg&&this.events.setMaxListeners(jg)}emitError(e){const t=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${zg(this.url)}`));return this.events.emit("register_error",t),t}};var Ah={exports:{}};Ah.exports;(function(r,e){var t=200,i="__lodash_hash_undefined__",n=1,a=2,f=9007199254740991,u="[object Arguments]",b="[object Array]",p="[object AsyncFunction]",y="[object Boolean]",A="[object Date]",R="[object Error]",O="[object Function]",N="[object GeneratorFunction]",K="[object Map]",W="[object Number]",Q="[object Null]",j="[object Object]",Y="[object Promise]",U="[object Proxy]",k="[object RegExp]",G="[object Set]",x="[object String]",B="[object Symbol]",ae="[object Undefined]",le="[object WeakMap]",F="[object ArrayBuffer]",m="[object DataView]",c="[object Float32Array]",h="[object Float64Array]",v="[object Int8Array]",_="[object Int16Array]",I="[object Int32Array]",M="[object Uint8Array]",S="[object Uint8ClampedArray]",d="[object Uint16Array]",g="[object Uint32Array]",T=/[\\^$.*+?()[\]{}|]/g,Z=/^\[object .+?Constructor\]$/,se=/^(?:0|[1-9]\d*)$/,P={};P[c]=P[h]=P[v]=P[_]=P[I]=P[M]=P[S]=P[d]=P[g]=!0,P[u]=P[b]=P[F]=P[y]=P[m]=P[A]=P[R]=P[O]=P[K]=P[W]=P[j]=P[k]=P[G]=P[x]=P[le]=!1;var ee=typeof ji=="object"&&ji&&ji.Object===Object&&ji,q=typeof self=="object"&&self&&self.Object===Object&&self,z=ee||q||Function("return this")(),H=e&&!e.nodeType&&e,w=H&&!0&&r&&!r.nodeType&&r,$=w&&w.exports===H,ne=$&&ee.process,ce=function(){try{return ne&&ne.binding&&ne.binding("util")}catch{}}(),he=ce&&ce.isTypedArray;function ye(V,te){for(var pe=-1,Ue=V==null?0:V.length,jt=0,pt=[];++pe-1}function Br(V,te){var pe=this.__data__,Ue=ks(pe,V);return Ue<0?(++this.size,pe.push([V,te])):pe[Ue][1]=te,this}bt.prototype.clear=Cr,bt.prototype.delete=Tr,bt.prototype.get=Dr,bt.prototype.has=Fr,bt.prototype.set=Br;function er(V){var te=-1,pe=V==null?0:V.length;for(this.clear();++tehr))return!1;var kt=pt.get(V);if(kt&&pt.get(te))return kt==te;var sr=-1,ei=!0,ur=pe&a?new Zr:void 0;for(pt.set(V,te),pt.set(te,V);++sr-1&&V%1==0&&V-1&&V%1==0&&V<=f}function Jc(V){var te=typeof V;return V!=null&&(te=="object"||te=="function")}function Vs(V){return V!=null&&typeof V=="object"}var Yc=he?Oe(he):qc;function tu(V){return Zh(V)?Fc(V):Lc(V)}function zt(){return[]}function $t(){return!1}r.exports=eu})(Ah,Ah.exports);var SP=Ah.exports;const IP=S0(SP),U2="wc",$2=2,ed="core",kn=`${U2}@2:${ed}:`,MP={name:ed,logger:"error"},PP={database:":memory:"},OP="crypto",kg="client_ed25519_seed",RP=xe.ONE_DAY,NP="keychain",CP="0.3",TP="messages",DP="0.3",FP=xe.SIX_HOURS,BP="publisher",z2="irn",qP="error",j2="wss://relay.walletconnect.org",LP="relayer",Gr={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},UP="_subscription",qi={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},$P=.1,m0="2.17.0",Kt={link_mode:"link_mode",relay:"relay"},zP="0.3",jP="WALLETCONNECT_CLIENT_ID",Hg="WALLETCONNECT_LINK_MODE_APPS",Pn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},kP="subscription",HP="0.3",KP=xe.FIVE_SECONDS*1e3,VP="pairing",GP="0.3",Xo={wc_pairingDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:0},res:{ttl:xe.ONE_DAY,prompt:!1,tag:0}}},ca={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},on={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},WP="history",JP="0.3",YP="expirer",Li={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},QP="0.3",XP="verify-api",ZP="https://verify.walletconnect.com",k2="https://verify.walletconnect.org",uc=k2,eO=`${uc}/v3`,tO=[ZP,k2],rO="echo",iO="https://echo.walletconnect.com",xn={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},os={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},cn={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},sa={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},aa={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Zo={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},nO=.1,sO="event-client",aO=86400,oO="https://pulse.walletconnect.org/batch";function cO(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i>>0,U=new Uint8Array(Y);Q!==j;){for(var k=N[Q],G=0,x=Y-1;(k!==0||G>>0,U[x]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");W=G,Q++}for(var B=Y-W;B!==Y&&U[B]===0;)B++;for(var ae=b.repeat(K);B>>0,Y=new Uint8Array(j);N[K];){var U=t[N.charCodeAt(K)];if(U===255)return;for(var k=0,G=j-1;(U!==0||k>>0,Y[G]=U%256>>>0,U=U/256>>>0;if(U!==0)throw new Error("Non-zero carry");Q=k,K++}if(N[K]!==" "){for(var x=j-Q;x!==j&&Y[x]===0;)x++;for(var B=new Uint8Array(W+(j-x)),ae=W;x!==j;)B[ae++]=Y[x++];return B}}}function O(N){var K=R(N);if(K)return K;throw new Error(`Non-${e} character`)}return{encode:A,decodeUnsafe:R,decode:O}}var fO=cO,hO=fO;const H2=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},uO=r=>new TextEncoder().encode(r),lO=r=>new TextDecoder().decode(r);class dO{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class pO{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return K2(this,e)}}class gO{constructor(e){this.decoders=e}or(e){return K2(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const K2=(r,e)=>new gO({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class vO{constructor(e,t,i,n){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=n,this.encoder=new dO(e,t,i),this.decoder=new pO(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Wh=({name:r,prefix:e,encode:t,decode:i})=>new vO(r,e,t,i),Tc=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:n}=hO(t,e);return Wh({prefix:r,name:e,encode:i,decode:a=>H2(n(a))})},bO=(r,e,t,i)=>{const n={};for(let y=0;y=8&&(u-=8,f[p++]=255&b>>u)}if(u>=t||255&b<<8-u)throw new SyntaxError("Unexpected end of data");return f},mO=(r,e,t)=>{const i=e[e.length-1]==="=",n=(1<t;)f-=t,a+=e[n&u>>f];if(f&&(a+=e[n&u<Wh({prefix:e,name:r,encode(n){return mO(n,i,t)},decode(n){return bO(n,i,t,r)}}),yO=Wh({prefix:"\0",name:"identity",encode:r=>lO(r),decode:r=>uO(r)});var wO=Object.freeze({__proto__:null,identity:yO});const _O=Nr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var AO=Object.freeze({__proto__:null,base2:_O});const EO=Nr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var xO=Object.freeze({__proto__:null,base8:EO});const SO=Tc({prefix:"9",name:"base10",alphabet:"0123456789"});var IO=Object.freeze({__proto__:null,base10:SO});const MO=Nr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),PO=Nr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var OO=Object.freeze({__proto__:null,base16:MO,base16upper:PO});const RO=Nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),NO=Nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),CO=Nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),TO=Nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),DO=Nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),FO=Nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),BO=Nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),qO=Nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),LO=Nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var UO=Object.freeze({__proto__:null,base32:RO,base32upper:NO,base32pad:CO,base32padupper:TO,base32hex:DO,base32hexupper:FO,base32hexpad:BO,base32hexpadupper:qO,base32z:LO});const $O=Tc({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zO=Tc({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var jO=Object.freeze({__proto__:null,base36:$O,base36upper:zO});const kO=Tc({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),HO=Tc({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var KO=Object.freeze({__proto__:null,base58btc:kO,base58flickr:HO});const VO=Nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),GO=Nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),WO=Nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),JO=Nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var YO=Object.freeze({__proto__:null,base64:VO,base64pad:GO,base64url:WO,base64urlpad:JO});const V2=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),QO=V2.reduce((r,e,t)=>(r[t]=e,r),[]),XO=V2.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function ZO(r){return r.reduce((e,t)=>(e+=QO[t],e),"")}function eR(r){const e=[];for(const t of r){const i=XO[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const tR=Wh({prefix:"🚀",name:"base256emoji",encode:ZO,decode:eR});var rR=Object.freeze({__proto__:null,base256emoji:tR}),iR=G2,Kg=128,nR=127,sR=~nR,aR=Math.pow(2,31);function G2(r,e,t){e=e||[],t=t||0;for(var i=t;r>=aR;)e[t++]=r&255|Kg,r/=128;for(;r&sR;)e[t++]=r&255|Kg,r>>>=7;return e[t]=r|0,G2.bytes=t-i+1,e}var oR=y0,cR=128,Vg=127;function y0(r,i){var t=0,i=i||0,n=0,a=i,f,u=r.length;do{if(a>=u)throw y0.bytes=0,new RangeError("Could not decode varint");f=r[a++],t+=n<28?(f&Vg)<=cR);return y0.bytes=a-i,t}var fR=Math.pow(2,7),hR=Math.pow(2,14),uR=Math.pow(2,21),lR=Math.pow(2,28),dR=Math.pow(2,35),pR=Math.pow(2,42),gR=Math.pow(2,49),vR=Math.pow(2,56),bR=Math.pow(2,63),mR=function(r){return r(W2.encode(r,e,t),e),Wg=r=>W2.encodingLength(r),w0=(r,e)=>{const t=e.byteLength,i=Wg(r),n=i+Wg(t),a=new Uint8Array(n+t);return Gg(r,a,0),Gg(t,a,i),a.set(e,n),new wR(r,t,e,a)};class wR{constructor(e,t,i,n){this.code=e,this.size=t,this.digest=i,this.bytes=n}}const J2=({name:r,code:e,encode:t})=>new _R(r,e,t);class _R{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?w0(this.code,t):t.then(i=>w0(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Y2=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),AR=J2({name:"sha2-256",code:18,encode:Y2("SHA-256")}),ER=J2({name:"sha2-512",code:19,encode:Y2("SHA-512")});var xR=Object.freeze({__proto__:null,sha256:AR,sha512:ER});const Q2=0,SR="identity",X2=H2,IR=r=>w0(Q2,X2(r)),MR={code:Q2,name:SR,encode:X2,digest:IR};var PR=Object.freeze({__proto__:null,identity:MR});new TextEncoder,new TextDecoder;const Jg={...wO,...AO,...xO,...IO,...OO,...UO,...jO,...KO,...YO,...rR};({...xR,...PR});function OR(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function Z2(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const Yg=Z2("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ql=Z2("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);const e=OR(r.length);for(let t=0;t{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()},this.get=i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:a}=Ae("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(a)}return n},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=Yr(t,this.name)}get context(){return di(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Nb(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Cb(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}}class TR{constructor(e,t,i){this.core=e,this.logger=t,this.name=OP,this.randomSessionIdentifier=u0(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=n=>(this.isInitialized(),this.keychain.has(n)),this.getClientId=async()=>{this.isInitialized();const n=await this.getClientSeed(),a=C1(n);return Mb(a.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const n=vS();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const a=await this.getClientSeed(),f=C1(a),u=this.randomSessionIdentifier;return await Q9(u,n,RP,f)},this.generateSharedKey=(n,a,f)=>{this.isInitialized();const u=this.getPrivateKey(n),b=bS(u,a);return this.setSymKey(b,f)},this.setSymKey=async(n,a)=>{this.isInitialized();const f=a||rh(n);return await this.keychain.set(f,n),f},this.deleteKeyPair=async n=>{this.isInitialized(),await this.keychain.del(n)},this.deleteSymKey=async n=>{this.isInitialized(),await this.keychain.del(n)},this.encode=async(n,a,f)=>{this.isInitialized();const u=E2(f),b=vs(a);if(gg(u))return yS(b,f==null?void 0:f.encoding);if(pg(u)){const R=u.senderPublicKey,O=u.receiverPublicKey;n=await this.generateSharedKey(R,O)}const p=this.getSymKey(n),{type:y,senderPublicKey:A}=u;return mS({type:y,symKey:p,message:b,senderPublicKey:A,encoding:f==null?void 0:f.encoding})},this.decode=async(n,a,f)=>{this.isInitialized();const u=AS(a,f);if(gg(u)){const b=_S(a,f==null?void 0:f.encoding);return ga(b)}if(pg(u)){const b=u.receiverPublicKey,p=u.senderPublicKey;n=await this.generateSharedKey(b,p)}try{const b=this.getSymKey(n),p=wS({symKey:b,encoded:a,encoding:f==null?void 0:f.encoding});return ga(p)}catch(b){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(b)}},this.getPayloadType=(n,a=Bs)=>{const f=vc({encoded:n,encoding:a});return ba(f.type)},this.getPayloadSenderPublicKey=(n,a=Bs)=>{const f=vc({encoded:n,encoding:a});return f.senderPublicKey?Er(f.senderPublicKey,Jr):void 0},this.core=e,this.logger=Yr(t,this.name),this.keychain=i||new CR(this.core,this.logger)}get context(){return di(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(kg)}catch{e=u0(),await this.keychain.set(kg,e)}return NR(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}}class DR extends IM{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=TP,this.version=DP,this.initialized=!1,this.storagePrefix=kn,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,n)=>{this.isInitialized();const a=fs(n);let f=this.messages.get(i);return typeof f>"u"&&(f={}),typeof f[a]<"u"||(f[a]=n,this.messages.set(i,f),await this.persist()),a},this.get=i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n},this.has=(i,n)=>{this.isInitialized();const a=this.get(i),f=fs(n);return typeof a[f]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=Yr(e,this.name),this.core=t}get context(){return di(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Nb(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Cb(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}}class FR extends MM{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new Hi.EventEmitter,this.name=BP,this.queue=new Map,this.publishTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.failedPublishTimeout=xe.toMiliseconds(xe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(i,n,a)=>{var f;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:a}});const u=(a==null?void 0:a.ttl)||FP,b=l0(a),p=(a==null?void 0:a.prompt)||!1,y=(a==null?void 0:a.tag)||0,A=(a==null?void 0:a.id)||ha().toString(),R={topic:i,message:n,opts:{ttl:u,relay:b,prompt:p,tag:y,id:A,attestation:a==null?void 0:a.attestation}},O=`Failed to publish payload, please try again. id:${A} tag:${y}`,N=Date.now();let K,W=1;try{for(;K===void 0;){if(Date.now()-N>this.publishTimeout)throw new Error(O);this.logger.trace({id:A,attempts:W},`publisher.publish - attempt ${W}`),K=await await Za(this.rpcPublish(i,n,u,b,p,y,A,a==null?void 0:a.attestation).catch(Q=>this.logger.warn(Q)),this.publishTimeout,O),W++,K||await new Promise(Q=>setTimeout(Q,this.failedPublishTimeout))}this.relayer.events.emit(Gr.publish,R),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:A,topic:i,message:n,opts:a}})}catch(Q){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(Q),(f=a==null?void 0:a.internal)!=null&&f.throwOnFailedPublish)throw Q;this.queue.set(A,R)}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.relayer=e,this.logger=Yr(t,this.name),this.registerEventListeners()}get context(){return di(this.logger)}rpcPublish(e,t,i,n,a,f,u,b){var p,y,A,R;const O={method:nc(n.protocol).publish,params:{topic:e,message:t,ttl:i,prompt:a,tag:f,attestation:b},id:u};return fi((p=O.params)==null?void 0:p.prompt)&&((y=O.params)==null||delete y.prompt),fi((A=O.params)==null?void 0:A.tag)&&((R=O.params)==null||delete R.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:O}),this.relayer.request(O)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:t,message:i,opts:n}=e;await this.publish(t,i,n)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ao.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Gr.connection_stalled);return}this.checkQueue()}),this.relayer.on(Gr.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class BR{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const n=i.filter(a=>a!==t);if(!n.length){this.map.delete(e);return}this.map.set(e,n)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var qR=Object.defineProperty,LR=Object.defineProperties,UR=Object.getOwnPropertyDescriptors,Qg=Object.getOwnPropertySymbols,$R=Object.prototype.hasOwnProperty,zR=Object.prototype.propertyIsEnumerable,Xg=(r,e,t)=>e in r?qR(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ec=(r,e)=>{for(var t in e||(e={}))$R.call(e,t)&&Xg(r,t,e[t]);if(Qg)for(var t of Qg(e))zR.call(e,t)&&Xg(r,t,e[t]);return r},Ll=(r,e)=>LR(r,UR(e));class jR extends RM{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new BR,this.events=new Hi.EventEmitter,this.name=kP,this.version=HP,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=kn,this.subscribeTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.pendingBatchMessages=[],this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId(),await this.restore()),this.initialized=!0},this.subscribe=async(i,n)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const a=l0(n),f={topic:i,relay:a,transportType:n==null?void 0:n.transportType};this.pending.set(i,f);const u=await this.rpcSubscribe(i,a,n==null?void 0:n.transportType);return typeof u=="string"&&(this.onSubscribe(u,f),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),u}catch(a){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(a),a}},this.unsubscribe=async(i,n)=>{await this.restartToComplete(),this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)},this.isSubscribed=async i=>{if(this.topics.includes(i))return!0;const n=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((a,f)=>{const u=new xe.Watch;u.start(n);const b=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(b),u.stop(n),a(!0)),u.elapsed(n)>=KP&&(clearInterval(b),u.stop(n),f(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=Yr(t,this.name),this.clientId=""}get context(){return di(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const n=l0(i);await this.rpcUnsubscribe(e,t,n);const a=Ut("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,a),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,t,i=Kt.relay){i===Kt.relay&&await this.restartToComplete();const n={method:nc(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{const a=fs(e+this.clientId);return i===Kt.link_mode?(setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(f=>this.logger.warn(f))},xe.toMiliseconds(xe.ONE_SECOND)),a):await await Za(this.relayer.request(n).catch(f=>this.logger.warn(f)),this.subscribeTimeout)?a:null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Gr.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:nc(t.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await await Za(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)}catch{this.relayer.events.emit(Gr.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:nc(t.protocol).batchFetchMessages,params:{topics:e.map(a=>a.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Za(this.relayer.request(i).catch(a=>this.logger.warn(a)),this.subscribeTimeout)}catch{this.relayer.events.emit(Gr.connection_stalled)}return n}rpcUnsubscribe(e,t,i){const n={method:nc(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,t){this.setSubscription(e,Ll(ec({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,ec({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,ec({},t)),this.topicMap.set(t.topic,e),this.events.emit(Pn.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=Ae("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Pn.deleted,Ll(ec({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Pn.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const t=await this.rpcBatchSubscribe(e);jn(t)&&this.onBatchSubscribe(t.map((i,n)=>Ll(ec({},e[n]),{id:i})))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(this.pendingBatchMessages=this.pendingBatchMessages.concat(t.messages))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e),this.pendingBatchMessages.length&&(await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages),this.pendingBatchMessages=[])}registerEventListeners(){this.relayer.core.heartbeat.on(Ao.pulse,async()=>{await this.checkPending()}),this.events.on(Pn.created,async e=>{const t=Pn.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(Pn.deleted,async e=>{const t=Pn.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen(),this.restartInProgress&&await new Promise(e=>{const t=setInterval(()=>{this.restartInProgress||(clearInterval(t),e())},this.pollingInterval)})}}var kR=Object.defineProperty,Zg=Object.getOwnPropertySymbols,HR=Object.prototype.hasOwnProperty,KR=Object.prototype.propertyIsEnumerable,ev=(r,e,t)=>e in r?kR(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,VR=(r,e)=>{for(var t in e||(e={}))HR.call(e,t)&&ev(r,t,e[t]);if(Zg)for(var t of Zg(e))KR.call(e,t)&&ev(r,t,e[t]);return r};class GR extends PM{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Hi.EventEmitter,this.name=LP,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=xe.toMiliseconds(xe.THIRTY_SECONDS+xe.ONE_SECOND),this.request=async t=>{var i,n;this.logger.debug("Publishing Request Payload");const a=t.id||ha().toString();await this.toEstablishConnection();try{const f=this.provider.request(t);this.requestsInFlight.set(a,{promise:f,request:t}),this.logger.trace({id:a,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - attempt to publish...");const u=await new Promise(async(b,p)=>{const y=()=>{p(new Error(`relayer.request - publish interrupted, id: ${a}`))};this.provider.on(qi.disconnect,y);const A=await f;this.provider.off(qi.disconnect,y),b(A)});return this.logger.trace({id:a,method:t.method,topic:(n=t.params)==null?void 0:n.topic},"relayer.request - published"),u}catch(f){throw this.logger.debug(`Failed to Publish Request: ${a}`),f}finally{this.requestsInFlight.delete(a)}},this.resetPingTimeout=()=>{if(dh())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,n;(n=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null||n.terminate()},this.heartBeatTimeout)}catch(t){this.logger.warn(t)}},this.onPayloadHandler=t=>{this.onProviderPayload(t),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.trace("relayer connected"),this.startPingTimeout(),this.events.emit(Gr.connect)},this.onDisconnectHandler=()=>{this.logger.trace("relayer disconnected"),this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.error(t),this.events.emit(Gr.error,t),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(qi.payload,this.onPayloadHandler),this.provider.on(qi.connect,this.onConnectHandler),this.provider.on(qi.disconnect,this.onDisconnectHandler),this.provider.on(qi.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Yr(e.logger,this.name):Nc(Hh({level:e.logger||qP})),this.messages=new DR(this.logger,e.core),this.subscriber=new jR(this,this.logger),this.publisher=new FR(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||j2,this.projectId=e.projectId,this.bundleId=aA(),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e)}}get context(){return di(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Kt.relay})}async subscribe(e,t){var i;this.isInitialized(),(t==null?void 0:t.transportType)==="relay"&&await this.toEstablishConnection();let n=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",a;const f=u=>{u.topic===e&&(this.subscriber.off(Pn.created,f),a())};return await Promise.all([new Promise(u=>{a=u,this.subscriber.on(Pn.created,f)}),new Promise(async u=>{n=await this.subscriber.subscribe(e,t)||n,u()})]),n}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await Za(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),await this.createProvider(),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(t,i)=>{const n=()=>{this.provider.off(qi.disconnect,n),i(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(qi.disconnect,n),await Za(this.provider.connect(),xe.toMiliseconds(xe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(a=>{i(a)}).finally(()=>{clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),this.subscriber.start().catch(a=>{this.logger.error(a),this.onDisconnectHandler()}),this.hasExperiencedNetworkDisruption=!1,t()})}catch(t){this.logger.error(t);const i=t;if(this.hasExperiencedNetworkDisruption=!0,!this.isConnectionStalled(i.message))throw t}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Ig())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.trace(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const n=vr(xe.FIVE_MINUTES),a={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,a)}this.events.emit(Gr.message,e),await this.recordMessageEvent(e)}startPingTimeout(){var e,t,i,n,a;if(dh())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((a=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||a.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(f){this.logger.warn(f)}}isConnectionStalled(e){return this.staleConnectionErrors.some(t=>e.includes(t))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new gn(new xP(hA({sdkVersion:m0,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const n=this.messages.has(t,i);return n&&this.logger.debug(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Z0(e)){if(!e.method.endsWith(UP))return;const t=e.params,{topic:i,message:n,publishedAt:a,attestation:f}=t.data,u={topic:i,message:n,publishedAt:a,transportType:Kt.relay,attestation:f};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(VR({type:"event",event:t.id},u)),this.events.emit(t.id,u),await this.acknowledgePayload(e),await this.onMessageEvent(u)}else Gh(e)&&this.events.emit(Gr.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Gr.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=Kh(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(qi.payload,this.onPayloadHandler),this.provider.off(qi.connect,this.onConnectHandler),this.provider.off(qi.disconnect,this.onDisconnectHandler),this.provider.off(qi.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Ig();gI(async t=>{e!==t&&(e=t,t?await this.restartTransport().catch(i=>this.logger.error(i)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.requestsInFlight.clear(),clearTimeout(this.pingTimeout),this.events.emit(Gr.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},xe.toMiliseconds($P))))}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{const t=setInterval(()=>{this.connected&&(clearInterval(t),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}}var WR=Object.defineProperty,tv=Object.getOwnPropertySymbols,JR=Object.prototype.hasOwnProperty,YR=Object.prototype.propertyIsEnumerable,rv=(r,e,t)=>e in r?WR(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,iv=(r,e)=>{for(var t in e||(e={}))JR.call(e,t)&&rv(r,t,e[t]);if(tv)for(var t of tv(e))YR.call(e,t)&&rv(r,t,e[t]);return r};class xa extends OM{constructor(e,t,i,n=kn,a=void 0){super(e,t,i,n),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version=zP,this.cached=[],this.initialized=!1,this.storagePrefix=kn,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(f=>{this.getKey&&f!==null&&!fi(f)?this.map.set(this.getKey(f),f):VS(f)?this.map.set(f.id,f):GS(f)&&this.map.set(f.topic,f)}),this.cached=[],this.initialized=!0)},this.set=async(f,u)=>{this.isInitialized(),this.map.has(f)?await this.update(f,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:f,value:u}),this.map.set(f,u),await this.persist())},this.get=f=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:f}),this.getData(f)),this.getAll=f=>(this.isInitialized(),f?this.values.filter(u=>Object.keys(f).every(b=>IP(u[b],f[b]))):this.values),this.update=async(f,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:f,update:u});const b=iv(iv({},this.getData(f)),u);this.map.set(f,b),await this.persist()},this.delete=async(f,u)=>{this.isInitialized(),this.map.has(f)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:f,reason:u}),this.map.delete(f),this.addToRecentlyDeleted(f),await this.persist())},this.logger=Yr(t,this.name),this.storagePrefix=n,this.getKey=a}get context(){return di(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:n}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=Ae("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}}class QR{constructor(e,t){this.core=e,this.logger=t,this.name=VP,this.version=GP,this.events=new I0,this.initialized=!1,this.storagePrefix=kn,this.ignoredPayloadTypes=[ds],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async i=>{this.isInitialized();const n=u0(),a=await this.core.crypto.setSymKey(n),f=vr(xe.FIVE_MINUTES),u={protocol:z2},b={topic:a,expiry:f,relay:u,active:!1,methods:i==null?void 0:i.methods},p=wg({protocol:this.core.protocol,version:this.core.version,topic:a,symKey:n,relay:u,expiryTimestamp:f,methods:i==null?void 0:i.methods});return this.events.emit(ca.create,b),this.core.expirer.set(a,f),await this.pairings.set(a,b),await this.core.relayer.subscribe(a,{transportType:i==null?void 0:i.transportType}),{topic:a,uri:p}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[xn.pairing_started]}});this.isValidPair(i,n);const{topic:a,symKey:f,relay:u,expiryTimestamp:b,methods:p}=yg(i.uri);n.props.properties.topic=a,n.addTrace(xn.pairing_uri_validation_success),n.addTrace(xn.pairing_uri_not_expired);let y;if(this.pairings.keys.includes(a)){if(y=this.pairings.get(a),n.addTrace(xn.existing_pairing),y.active)throw n.setError(os.active_pairing_already_exists),new Error(`Pairing already exists: ${a}. Please try again with a new connection URI.`);n.addTrace(xn.pairing_not_expired)}const A=b||vr(xe.FIVE_MINUTES),R={topic:a,relay:u,expiry:A,active:!1,methods:p};this.core.expirer.set(a,A),await this.pairings.set(a,R),n.addTrace(xn.store_new_pairing),i.activatePairing&&await this.activate({topic:a}),this.events.emit(ca.create,R),n.addTrace(xn.emit_inactive_pairing),this.core.crypto.keychain.has(a)||await this.core.crypto.setSymKey(f,a),n.addTrace(xn.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(os.no_internet_connection)}try{await this.core.relayer.subscribe(a,{relay:u})}catch(O){throw n.setError(os.subscribe_pairing_topic_failure),O}return n.addTrace(xn.subscribe_pairing_topic_success),R},this.activate=async({topic:i})=>{this.isInitialized();const n=vr(xe.THIRTY_DAYS);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:n}=i;if(this.pairings.keys.includes(n)){const a=await this.sendRequest(n,"wc_pairingPing",{}),{done:f,resolve:u,reject:b}=oa();this.events.once(St("pairing_ping",a),({error:p})=>{p?b(p):u()}),await f()}},this.updateExpiry=async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})},this.updateMetadata=async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",Ut("USER_DISCONNECTED")),await this.deletePairing(n))},this.formatUriFromPairing=i=>{this.isInitialized();const{topic:n,relay:a,expiry:f,methods:u}=i,b=this.core.crypto.keychain.get(n);return wg({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:b,relay:a,expiryTimestamp:f,methods:u})},this.sendRequest=async(i,n,a)=>{const f=qs(n,a),u=await this.core.crypto.encode(i,f),b=Xo[n].req;return this.core.history.set(i,f),this.core.relayer.publish(i,u,b),f.id},this.sendResult=async(i,n,a)=>{const f=Kh(i,a),u=await this.core.crypto.encode(n,f),b=await this.core.history.get(n,i),p=Xo[b.request.method].res;await this.core.relayer.publish(n,u,p),await this.core.history.resolve(f)},this.sendError=async(i,n,a)=>{const f=Vh(i,a),u=await this.core.crypto.encode(n,f),b=await this.core.history.get(n,i),p=Xo[b.request.method]?Xo[b.request.method].res:Xo.unregistered_method.res;await this.core.relayer.publish(n,u,p),await this.core.history.resolve(f)},this.deletePairing=async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Ut("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(n=>Rs(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))},this.onRelayEventRequest=i=>{const{topic:n,payload:a}=i;switch(a.method){case"wc_pairingPing":return this.onPairingPingRequest(n,a);case"wc_pairingDelete":return this.onPairingDeleteRequest(n,a);default:return this.onUnknownRpcMethodRequest(n,a)}},this.onRelayEventResponse=async i=>{const{topic:n,payload:a}=i,f=(await this.core.history.get(n,a.id)).request.method;switch(f){case"wc_pairingPing":return this.onPairingPingResponse(n,a);default:return this.onUnknownRpcMethodResponse(f)}},this.onPairingPingRequest=async(i,n)=>{const{id:a}=n;try{this.isValidPing({topic:i}),await this.sendResult(a,i,!0),this.events.emit(ca.ping,{id:a,topic:i})}catch(f){await this.sendError(a,i,f),this.logger.error(f)}},this.onPairingPingResponse=(i,n)=>{const{id:a}=n;setTimeout(()=>{Mn(n)?this.events.emit(St("pairing_ping",a),{}):$i(n)&&this.events.emit(St("pairing_ping",a),{error:n.error})},500)},this.onPairingDeleteRequest=async(i,n)=>{const{id:a}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(ca.delete,{id:a,topic:i})}catch(f){await this.sendError(a,i,f),this.logger.error(f)}},this.onUnknownRpcMethodRequest=async(i,n)=>{const{id:a,method:f}=n;try{if(this.registeredMethods.includes(f))return;const u=Ut("WC_METHOD_UNSUPPORTED",f);await this.sendError(a,i,u),this.logger.error(u)}catch(u){await this.sendError(a,i,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(Ut("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=(i,n)=>{var a;if(!oi(i)){const{message:u}=Ae("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(os.malformed_pairing_uri),new Error(u)}if(!KS(i.uri)){const{message:u}=Ae("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(os.malformed_pairing_uri),new Error(u)}const f=yg(i==null?void 0:i.uri);if(!((a=f==null?void 0:f.relay)!=null&&a.protocol)){const{message:u}=Ae("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(os.malformed_pairing_uri),new Error(u)}if(!(f!=null&&f.symKey)){const{message:u}=Ae("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(os.malformed_pairing_uri),new Error(u)}if(f!=null&&f.expiryTimestamp&&xe.toMiliseconds(f==null?void 0:f.expiryTimestamp){if(!oi(i)){const{message:a}=Ae("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(a)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidDisconnect=async i=>{if(!oi(i)){const{message:a}=Ae("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(a)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidPairingTopic=async i=>{if(!fr(i,!1)){const{message:n}=Ae("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(Rs(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=Ae("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}},this.core=e,this.logger=Yr(t,this.name),this.pairings=new xa(this.core,this.logger,this.name,this.storagePrefix)}get context(){return di(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Gr.message,async e=>{const{topic:t,message:i,transportType:n}=e;if(!this.pairings.keys.includes(t)||n===Kt.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const a=await this.core.crypto.decode(t,i);try{Z0(a)?(this.core.history.set(t,a),this.onRelayEventRequest({topic:t,payload:a})):Gh(a)&&(await this.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a}),this.core.history.delete(t,a.id))}catch(f){this.logger.error(f)}})}registerExpirerEvents(){this.core.expirer.on(Li.expired,async e=>{const{topic:t}=Db(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(ca.expire,{topic:t}))})}}class XR extends SM{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new Hi.EventEmitter,this.name=WP,this.version=JP,this.cached=[],this.initialized=!1,this.storagePrefix=kn,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,n,a)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:a}),this.records.has(n.id))return;const f={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:a,expiry:vr(xe.THIRTY_DAYS)};this.records.set(f.id,f),this.persist(),this.events.emit(on.created,f)},this.resolve=async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=$i(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(on.updated,n))},this.get=async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n)),this.delete=(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(a=>{if(a.topic===i){if(typeof n<"u"&&a.id!==n)return;this.records.delete(a.id),this.events.emit(on.deleted,a)}}),this.persist()},this.exists=async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1),this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=Yr(t,this.name)}get context(){return di(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:qs(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=Ae("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(on.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(on.created,e=>{const t=on.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(on.updated,e=>{const t=on.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(on.deleted,e=>{const t=on.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(Ao.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{xe.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(on.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ZR extends NM{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new Hi.EventEmitter,this.name=YP,this.version=QP,this.cached=[],this.initialized=!1,this.storagePrefix=kn,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}},this.set=(i,n)=>{this.isInitialized();const a=this.formatTarget(i),f={target:a,expiry:n};this.expirations.set(a,f),this.checkExpiry(a,f),this.events.emit(Li.created,{target:a,expiration:f})},this.get=i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)},this.del=i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),a=this.getExpiration(n);this.expirations.delete(n),this.events.emit(Li.deleted,{target:n,expiration:a})}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=Yr(t,this.name)}get context(){return di(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return uA(e);if(typeof e=="number")return lA(e);const{message:t}=Ae("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Li.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=Ae("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;xe.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Li.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Ao.pulse,()=>this.checkExpirations()),this.events.on(Li.created,e=>{const t=Li.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Li.expired,e=>{const t=Li.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Li.deleted,e=>{const t=Li.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Qt={};Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.getLocalStorage=Qt.getLocalStorageOrThrow=Qt.getCrypto=Qt.getCryptoOrThrow=Qt.getLocation=Qt.getLocationOrThrow=Qt.getNavigator=Qt.getNavigatorOrThrow=em=Qt.getDocument=Qt.getDocumentOrThrow=Qt.getFromWindowOrThrow=Qt.getFromWindow=void 0;function Sa(r){let e;return typeof window<"u"&&typeof window[r]<"u"&&(e=window[r]),e}Qt.getFromWindow=Sa;function Eo(r){const e=Sa(r);if(!e)throw new Error(`${r} is not defined in Window`);return e}Qt.getFromWindowOrThrow=Eo;function eN(){return Eo("document")}Qt.getDocumentOrThrow=eN;function tN(){return Sa("document")}var em=Qt.getDocument=tN;function rN(){return Eo("navigator")}Qt.getNavigatorOrThrow=rN;function iN(){return Sa("navigator")}Qt.getNavigator=iN;function nN(){return Eo("location")}Qt.getLocationOrThrow=nN;function sN(){return Sa("location")}Qt.getLocation=sN;function aN(){return Eo("crypto")}Qt.getCryptoOrThrow=aN;function oN(){return Sa("crypto")}Qt.getCrypto=oN;function cN(){return Eo("localStorage")}Qt.getLocalStorageOrThrow=cN;function fN(){return Sa("localStorage")}Qt.getLocalStorage=fN;class hN extends CM{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,this.name=XP,this.verifyUrlV3=eO,this.storagePrefix=kn,this.version=$2,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&xe.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt){if(!Sc()||this.isDevEnv)return;const a=window.location.origin,{id:f,decryptedId:u}=n,b=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${a}&id=${f}&decryptedId=${u}`;try{const p=em(),y=this.startAbortTimer(xe.ONE_SECOND*5),A=await new Promise((R,O)=>{const N=()=>{window.removeEventListener("message",W),p.body.removeChild(K),O("attestation aborted")};this.abortController.signal.addEventListener("abort",N);const K=p.createElement("iframe");K.src=b,K.style.display="none",K.addEventListener("error",N,{signal:this.abortController.signal});const W=Q=>{if(Q.data&&typeof Q.data=="string")try{const j=JSON.parse(Q.data);if(j.type==="verify_attestation"){if(n0(j.attestation).payload.id!==f)return;clearInterval(y),p.body.removeChild(K),this.abortController.signal.removeEventListener("abort",N),window.removeEventListener("message",W),R(j.attestation===null?"":j.attestation)}}catch(j){this.logger.warn(j)}};p.body.appendChild(K),window.addEventListener("message",W,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",A),A}catch(p){this.logger.warn(p)}return""},this.resolve=async n=>{if(this.isDevEnv)return"";const{attestationId:a,hash:f,encryptedId:u}=n;if(a===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(a){if(n0(a).payload.id!==u)return;const p=await this.isValidJwtAttestation(a);if(p){if(!p.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return p}}if(!f)return;const b=this.getVerifyUrl(n==null?void 0:n.verifyUrl);return this.fetchAttestation(f,b)},this.fetchAttestation=async(n,a)=>{this.logger.debug(`resolving attestation: ${n} from url: ${a}`);const f=this.startAbortTimer(xe.ONE_SECOND*5),u=await fetch(`${a}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(f),u.status===200?await u.json():void 0},this.getVerifyUrl=n=>{let a=n||uc;return tO.includes(a)||(this.logger.info(`verify url: ${a}, not included in trusted list, assigning default: ${uc}`),a=uc),a},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(xe.FIVE_SECONDS),a=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await a.json()}catch(n){this.logger.warn(n)}},this.persistPublicKey=async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async n=>{const a=await this.getPublicKey();try{if(a)return this.validateAttestation(n,a)}catch(u){this.logger.error(u),this.logger.warn("error validating attestation")}const f=await this.fetchAndPersistPublicKey();try{if(f)return this.validateAttestation(n,f)}catch(u){this.logger.error(u),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async a=>{const f=await this.fetchPublicKey();f&&(await this.persistPublicKey(f),a(f))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n},this.validateAttestation=(n,a)=>{const f=IS(n,a.publicKey),u={hasExpired:xe.toMiliseconds(f.exp)this.abortController.abort(),xe.toMiliseconds(e))}}class uN extends TM{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context=rO,this.registerDeviceToken=async i=>{const{clientId:n,token:a,notificationType:f,enableEncrypted:u=!1}=i,b=`${iO}/${this.projectId}/clients`;await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:f,token:a,always_raw:u})})},this.logger=Yr(t,this.context)}}var lN=Object.defineProperty,nv=Object.getOwnPropertySymbols,dN=Object.prototype.hasOwnProperty,pN=Object.prototype.propertyIsEnumerable,sv=(r,e,t)=>e in r?lN(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,tc=(r,e)=>{for(var t in e||(e={}))dN.call(e,t)&&sv(r,t,e[t]);if(nv)for(var t of nv(e))pN.call(e,t)&&sv(r,t,e[t]);return r};class gN extends DM{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,this.context=sO,this.storagePrefix=kn,this.storageVersion=nO,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!z0())try{const n={eventId:L1(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Rb(this.core.relayer.protocol,this.core.relayer.version,m0)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}},this.createEvent=n=>{const{event:a="ERROR",type:f="",properties:{topic:u,trace:b}}=n,p=L1(),y=this.core.projectId||"",A=Date.now(),R=tc({eventId:p,timestamp:A,props:{event:a,type:f,properties:{topic:u,trace:b}},bundleId:y,domain:this.getAppDomain()},this.setMethods(p));return this.telemetryEnabled&&(this.events.set(p,R),this.shouldPersist=!0),R},this.getEvent=n=>{const{eventId:a,topic:f}=n;if(a)return this.events.get(a);const u=Array.from(this.events.values()).find(b=>b.props.properties.topic===f);if(u)return tc(tc({},u),this.setMethods(u.eventId))},this.deleteEvent=n=>{const{eventId:a}=n;this.events.delete(a),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(Ao.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{xe.fromMiliseconds(Date.now())-xe.fromMiliseconds(n.timestamp)>aO&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})},this.setMethods=n=>({addTrace:a=>this.addTrace(n,a),setError:a=>this.setError(n,a)}),this.addTrace=(n,a)=>{const f=this.events.get(n);f&&(f.props.properties.trace.push(a),this.events.set(n,f),this.shouldPersist=!0)},this.setError=(n,a)=>{const f=this.events.get(n);f&&(f.props.type=a,f.timestamp=Date.now(),this.events.set(n,f),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(a=>{this.events.set(a.eventId,tc(tc({},a),this.setMethods(a.eventId)))})}catch(n){this.logger.warn(n)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[a,f]of this.events)f.props.type&&n.push(f);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const a of n)this.events.delete(a.eventId),this.shouldPersist=!0}catch(a){this.logger.warn(a)}},this.sendEvent=async n=>{const a=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${oO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${m0}${a}`,{method:"POST",body:JSON.stringify(n)})},this.getAppDomain=()=>Ob().url,this.logger=Yr(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var vN=Object.defineProperty,av=Object.getOwnPropertySymbols,bN=Object.prototype.hasOwnProperty,mN=Object.prototype.propertyIsEnumerable,ov=(r,e,t)=>e in r?vN(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,cv=(r,e)=>{for(var t in e||(e={}))bN.call(e,t)&&ov(r,t,e[t]);if(av)for(var t of av(e))mN.call(e,t)&&ov(r,t,e[t]);return r};class td extends xM{constructor(e){var t;super(e),this.protocol=U2,this.version=$2,this.name=ed,this.events=new Hi.EventEmitter,this.initialized=!1,this.on=(f,u)=>this.events.on(f,u),this.once=(f,u)=>this.events.once(f,u),this.off=(f,u)=>this.events.off(f,u),this.removeListener=(f,u)=>this.events.removeListener(f,u),this.dispatchEnvelope=({topic:f,message:u,sessionExists:b})=>{if(!f||!u)return;const p={topic:f,message:u,publishedAt:Date.now(),transportType:Kt.link_mode};this.relayer.onLinkMessageEvent(p,{sessionExists:b})},this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||j2,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Hh({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:MP.logger}),{logger:n,chunkLoggerController:a}=EM({opts:i,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=a,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var f,u;(f=this.logChunkController)!=null&&f.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Yr(n,this.name),this.heartbeat=new yI,this.crypto=new TR(this,this.logger,e==null?void 0:e.keychain),this.history=new XR(this,this.logger),this.expirer=new ZR(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new JI(cv(cv({},PP),e==null?void 0:e.storageOptions)),this.relayer=new GR({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new QR(this,this.logger),this.verify=new hN(this,this.logger,this.storage),this.echoClient=new uN(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new gN(this,this.logger,e==null?void 0:e.telemetryEnabled)}static async init(e){const t=new td(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(jP,i),t}get context(){return di(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Hg,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.eventClient.init(),this.linkModeSupportedApps=await this.storage.getItem(Hg)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const yN=td,tm="wc",rm=2,im="client",rd=`${tm}@${rm}:${im}:`,Ul={name:im,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},fv="WALLETCONNECT_DEEPLINK_CHOICE",wN="proposal",nm="Proposal expired",_N="session",Ga=xe.SEVEN_DAYS,AN="engine",wr={wc_sessionPropose:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1104},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1106},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1112},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1114},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:xe.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:xe.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1119}}},$l={min:xe.FIVE_MINUTES,max:xe.SEVEN_DAYS},En={idle:"IDLE",active:"ACTIVE"},EN="request",xN=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],SN="wc",IN="auth",MN="authKeys",PN="pairingTopics",ON="requests",Jh=`${SN}@${1.5}:${IN}:`,sh=`${Jh}:PUB_KEY`;var RN=Object.defineProperty,NN=Object.defineProperties,CN=Object.getOwnPropertyDescriptors,hv=Object.getOwnPropertySymbols,TN=Object.prototype.hasOwnProperty,DN=Object.prototype.propertyIsEnumerable,uv=(r,e,t)=>e in r?RN(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,rr=(r,e)=>{for(var t in e||(e={}))TN.call(e,t)&&uv(r,t,e[t]);if(hv)for(var t of hv(e))DN.call(e,t)&&uv(r,t,e[t]);return r},fn=(r,e)=>NN(r,CN(e));class FN extends BM{constructor(e){super(e),this.name=AN,this.events=new I0,this.initialized=!1,this.requestQueue={state:En.idle,queue:[]},this.sessionRequestQueue={state:En.idle,queue:[]},this.requestQueueDelay=xe.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(wr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay)))},this.connect=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=fn(rr({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:a,optionalNamespaces:f,sessionProperties:u,relays:b}=i;let p=n,y,A=!1;try{p&&(A=this.client.core.pairing.pairings.get(p).active)}catch(U){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),U}if(!p||!A){const{topic:U,uri:k}=await this.client.core.pairing.create();p=U,y=k}if(!p){const{message:U}=Ae("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(U)}const R=await this.client.core.crypto.generateKeyPair(),O=wr.wc_sessionPropose.req.ttl||xe.FIVE_MINUTES,N=vr(O),K=rr({requiredNamespaces:a,optionalNamespaces:f,relays:b??[{protocol:z2}],proposer:{publicKey:R,metadata:this.client.metadata},expiryTimestamp:N,pairingTopic:p},u&&{sessionProperties:u}),{reject:W,resolve:Q,done:j}=oa(O,nm);this.events.once(St("session_connect"),async({error:U,session:k})=>{if(U)W(U);else if(k){k.self.publicKey=R;const G=fn(rr({},k),{pairingTopic:K.pairingTopic,requiredNamespaces:K.requiredNamespaces,optionalNamespaces:K.optionalNamespaces,transportType:Kt.relay});await this.client.session.set(k.topic,G),await this.setExpiry(k.topic,k.expiry),p&&await this.client.core.pairing.updateMetadata({topic:p,metadata:k.peer.metadata}),this.cleanupDuplicatePairings(G),Q(G)}});const Y=await this.sendRequest({topic:p,method:"wc_sessionPropose",params:K,throwOnFailedPublish:!0});return await this.setProposal(Y,rr({id:Y},K)),{uri:y,approval:j}},this.pair=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}},this.approve=async t=>{var i,n,a;const f=this.client.core.eventClient.createEvent({properties:{topic:(i=t==null?void 0:t.id)==null?void 0:i.toString(),trace:[cn.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(B){throw f.setError(sa.no_internet_connection),B}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(B){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),f.setError(sa.proposal_not_found),B}try{await this.isValidApprove(t)}catch(B){throw this.client.logger.error("approve() -> isValidApprove() failed"),f.setError(sa.session_approve_namespace_validation_failure),B}const{id:u,relayProtocol:b,namespaces:p,sessionProperties:y,sessionConfig:A}=t,R=this.client.proposal.get(u);this.client.core.eventClient.deleteEvent({eventId:f.eventId});const{pairingTopic:O,proposer:N,requiredNamespaces:K,optionalNamespaces:W}=R;let Q=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:O});Q||(Q=(a=this.client.core.eventClient)==null?void 0:a.createEvent({type:cn.session_approve_started,properties:{topic:O,trace:[cn.session_approve_started,cn.session_namespaces_validation_success]}}));const j=await this.client.core.crypto.generateKeyPair(),Y=N.publicKey,U=await this.client.core.crypto.generateSharedKey(j,Y),k=rr(rr({relay:{protocol:b??"irn"},namespaces:p,controller:{publicKey:j,metadata:this.client.metadata},expiry:vr(Ga)},y&&{sessionProperties:y}),A&&{sessionConfig:A}),G=Kt.relay;Q.addTrace(cn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(U,{transportType:G})}catch(B){throw Q.setError(sa.subscribe_session_topic_failure),B}Q.addTrace(cn.subscribe_session_topic_success);const x=fn(rr({},k),{topic:U,requiredNamespaces:K,optionalNamespaces:W,pairingTopic:O,acknowledged:!1,self:k.controller,peer:{publicKey:N.publicKey,metadata:N.metadata},controller:j,transportType:Kt.relay});await this.client.session.set(U,x),Q.addTrace(cn.store_session);try{Q.addTrace(cn.publishing_session_settle),await this.sendRequest({topic:U,method:"wc_sessionSettle",params:k,throwOnFailedPublish:!0}).catch(B=>{throw Q==null||Q.setError(sa.session_settle_publish_failure),B}),Q.addTrace(cn.session_settle_publish_success),Q.addTrace(cn.publishing_session_approve),await this.sendResult({id:u,topic:O,result:{relay:{protocol:b??"irn"},responderPublicKey:j},throwOnFailedPublish:!0}).catch(B=>{throw Q==null||Q.setError(sa.session_approve_publish_failure),B}),Q.addTrace(cn.session_approve_publish_success)}catch(B){throw this.client.logger.error(B),this.client.session.delete(U,Ut("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(U),B}return this.client.core.eventClient.deleteEvent({eventId:Q.eventId}),await this.client.core.pairing.updateMetadata({topic:O,metadata:N.metadata}),await this.client.proposal.delete(u,Ut("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:O}),await this.setExpiry(U,vr(Ga)),{topic:U,acknowledged:()=>Promise.resolve(this.client.session.get(U))}},this.reject=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(f){throw this.client.logger.error("reject() -> isValidReject() failed"),f}const{id:i,reason:n}=t;let a;try{a=this.client.proposal.get(i).pairingTopic}catch(f){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),f}a&&(await this.sendError({id:i,topic:a,error:n,rpcOpts:wr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Ut("USER_DISCONNECTED")))},this.update=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(A){throw this.client.logger.error("update() -> isValidUpdate() failed"),A}const{topic:i,namespaces:n}=t,{done:a,resolve:f,reject:u}=oa(),b=Cs(),p=ha().toString(),y=this.client.session.get(i).namespaces;return this.events.once(St("session_update",b),({error:A})=>{A?u(A):f()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:b,relayRpcId:p}).catch(A=>{this.client.logger.error(A),this.client.session.update(i,{namespaces:y}),u(A)}),{acknowledged:a}},this.extend=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(b){throw this.client.logger.error("extend() -> isValidExtend() failed"),b}const{topic:i}=t,n=Cs(),{done:a,resolve:f,reject:u}=oa();return this.events.once(St("session_extend",n),({error:b})=>{b?u(b):f()}),await this.setExpiry(i,vr(Ga)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(b=>{u(b)}),{acknowledged:a}},this.request=async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(N){throw this.client.logger.error("request() -> isValidRequest() failed"),N}const{chainId:i,request:n,topic:a,expiry:f=wr.wc_sessionRequest.req.ttl}=t,u=this.client.session.get(a);(u==null?void 0:u.transportType)===Kt.relay&&await this.confirmOnlineStateOrThrow();const b=Cs(),p=ha().toString(),{done:y,resolve:A,reject:R}=oa(f,"Request expired. Please try again.");this.events.once(St("session_request",b),({error:N,result:K})=>{N?R(N):A(K)});const O=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);return O?(await this.sendRequest({clientRpcId:b,relayRpcId:p,topic:a,method:"wc_sessionRequest",params:{request:fn(rr({},n),{expiryTimestamp:vr(f)}),chainId:i},expiry:f,throwOnFailedPublish:!0,appLink:O}).catch(N=>R(N)),this.client.events.emit("session_request_sent",{topic:a,request:n,chainId:i,id:b}),await y()):await Promise.all([new Promise(async N=>{await this.sendRequest({clientRpcId:b,relayRpcId:p,topic:a,method:"wc_sessionRequest",params:{request:fn(rr({},n),{expiryTimestamp:vr(f)}),chainId:i},expiry:f,throwOnFailedPublish:!0}).catch(K=>R(K)),this.client.events.emit("session_request_sent",{topic:a,request:n,chainId:i,id:b}),N()}),new Promise(async N=>{var K;if(!((K=u.sessionConfig)!=null&&K.disableDeepLink)){const W=await gA(this.client.core.storage,fv);await dA({id:b,topic:a,wcDeepLink:W})}N()}),y()]).then(N=>N[2])},this.respond=async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:n}=t,{id:a}=n,f=this.client.session.get(i);f.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(f.peer.metadata,f.transportType);Mn(n)?await this.sendResult({id:a,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:u}):$i(n)&&await this.sendError({id:a,topic:i,error:n.error,appLink:u}),this.cleanupAfterResponse(t)},this.ping=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=t;if(this.client.session.keys.includes(i)){const n=Cs(),a=ha().toString(),{done:f,resolve:u,reject:b}=oa();this.events.once(St("session_ping",n),({error:p})=>{p?b(p):u()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:a}),f()])}else this.client.core.pairing.pairings.keys.includes(i)&&await this.client.core.pairing.ping({topic:i})},this.emit=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:n,chainId:a}=t,f=ha().toString();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:a},throwOnFailedPublish:!0,relayRpcId:f})},this.disconnect=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Ut("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=Ae("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}},this.find=t=>(this.isInitialized(),this.client.session.getAll().filter(i=>kS(i,t))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(t,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(t);const a=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),f=a?Kt.link_mode:Kt.relay;f===Kt.relay&&await this.confirmOnlineStateOrThrow();const{chains:u,statement:b="",uri:p,domain:y,nonce:A,type:R,exp:O,nbf:N,methods:K=[],expiry:W}=t,Q=[...t.resources||[]],{topic:j,uri:Y}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:f});this.client.logger.info({message:"Generated new pairing",pairing:{topic:j,uri:Y}});const U=await this.client.core.crypto.generateKeyPair(),k=rh(U);if(await Promise.all([this.client.auth.authKeys.set(sh,{responseTopic:k,publicKey:U}),this.client.auth.pairingTopics.set(k,{topic:k,pairingTopic:j})]),await this.client.core.relayer.subscribe(k,{transportType:f}),this.client.logger.info(`sending request to new pairing topic: ${j}`),K.length>0){const{namespace:M}=ac(u[0]);let S=hS(M,"request",K);th(Q)&&(S=lS(S,Q.pop())),Q.push(S)}const G=W&&W>wr.wc_sessionAuthenticate.req.ttl?W:wr.wc_sessionAuthenticate.req.ttl,x={authPayload:{type:R??"caip122",chains:u,statement:b,aud:p,domain:y,version:"1",nonce:A,iat:new Date().toISOString(),exp:O,nbf:N,resources:Q},requester:{publicKey:U,metadata:this.client.metadata},expiryTimestamp:vr(G)},B={eip155:{chains:u,methods:[...new Set(["personal_sign",...K])],events:["chainChanged","accountsChanged"]}},ae={requiredNamespaces:{},optionalNamespaces:B,relays:[{protocol:"irn"}],pairingTopic:j,proposer:{publicKey:U,metadata:this.client.metadata},expiryTimestamp:vr(wr.wc_sessionPropose.req.ttl)},{done:le,resolve:F,reject:m}=oa(G,"Request expired"),c=async({error:M,session:S})=>{if(this.events.off(St("session_request",v),h),M)m(M);else if(S){S.self.publicKey=U,await this.client.session.set(S.topic,S),await this.setExpiry(S.topic,S.expiry),j&&await this.client.core.pairing.updateMetadata({topic:j,metadata:S.peer.metadata});const d=this.client.session.get(S.topic);await this.deleteProposal(_),F({session:d})}},h=async M=>{var S,d,g;if(await this.deletePendingAuthRequest(v,{message:"fulfilled",code:0}),M.error){const z=Ut("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return M.error.code===z.code?void 0:(this.events.off(St("session_connect"),c),m(M.error.message))}await this.deleteProposal(_),this.events.off(St("session_connect"),c);const{cacaos:T,responder:Z}=M.result,se=[],P=[];for(const z of T){await hg({cacao:z,projectId:this.client.core.projectId})||(this.client.logger.error(z,"Signature verification failed"),m(Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:H}=z,w=th(H.resources),$=[fg(H.iss)],ne=mh(H.iss);if(w){const ce=ug(w),he=lg(w);se.push(...ce),$.push(...he)}for(const ce of $)P.push(`${ce}:${ne}`)}const ee=await this.client.core.crypto.generateSharedKey(U,Z.publicKey);let q;se.length>0&&(q={topic:ee,acknowledged:!0,self:{publicKey:U,metadata:this.client.metadata},peer:Z,controller:Z.publicKey,expiry:vr(Ga),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:j,namespaces:_g([...new Set(se)],[...new Set(P)]),transportType:f},await this.client.core.relayer.subscribe(ee,{transportType:f}),await this.client.session.set(ee,q),j&&await this.client.core.pairing.updateMetadata({topic:j,metadata:Z.metadata}),q=this.client.session.get(ee)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(d=Z.metadata.redirect)!=null&&d.linkMode&&(g=Z.metadata.redirect)!=null&&g.universal&&i&&(this.client.core.addLinkModeSupportedApp(Z.metadata.redirect.universal),this.client.session.update(ee,{transportType:Kt.link_mode})),F({auths:T,session:q})},v=Cs(),_=Cs();this.events.once(St("session_connect"),c),this.events.once(St("session_request",v),h);let I;try{if(a){const M=qs("wc_sessionAuthenticate",x,v);this.client.core.history.set(j,M);const S=await this.client.core.crypto.encode("",M,{type:Oc,encoding:Yo});I=kf(i,j,S)}else await Promise.all([this.sendRequest({topic:j,method:"wc_sessionAuthenticate",params:x,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:v}),this.sendRequest({topic:j,method:"wc_sessionPropose",params:ae,expiry:wr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:_})])}catch(M){throw this.events.off(St("session_connect"),c),this.events.off(St("session_request",v),h),M}return await this.setProposal(_,rr({id:_},ae)),await this.setAuthRequest(v,{request:fn(rr({},x),{verifyContext:{}}),pairingTopic:j,transportType:f}),{uri:I??Y,response:le}},this.approveSessionAuthenticate=async t=>{const{id:i,auths:n}=t,a=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[aa.authenticated_session_approve_started]}});try{this.isInitialized()}catch(W){throw a.setError(Zo.no_internet_connection),W}const f=this.getPendingAuthRequest(i);if(!f)throw a.setError(Zo.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const u=f.transportType||Kt.relay;u===Kt.relay&&await this.confirmOnlineStateOrThrow();const b=f.requester.publicKey,p=await this.client.core.crypto.generateKeyPair(),y=rh(b),A={type:ds,receiverPublicKey:b,senderPublicKey:p},R=[],O=[];for(const W of n){if(!await hg({cacao:W,projectId:this.client.core.projectId})){a.setError(Zo.invalid_cacao);const k=Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:y,error:k,encodeOpts:A}),new Error(k.message)}a.addTrace(aa.cacaos_verified);const{p:Q}=W,j=th(Q.resources),Y=[fg(Q.iss)],U=mh(Q.iss);if(j){const k=ug(j),G=lg(j);R.push(...k),Y.push(...G)}for(const k of Y)O.push(`${k}:${U}`)}const N=await this.client.core.crypto.generateSharedKey(p,b);a.addTrace(aa.create_authenticated_session_topic);let K;if((R==null?void 0:R.length)>0){K={topic:N,acknowledged:!0,self:{publicKey:p,metadata:this.client.metadata},peer:{publicKey:b,metadata:f.requester.metadata},controller:b,expiry:vr(Ga),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:f.pairingTopic,namespaces:_g([...new Set(R)],[...new Set(O)]),transportType:u},a.addTrace(aa.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(N,{transportType:u})}catch(W){throw a.setError(Zo.subscribe_authenticated_session_topic_failure),W}a.addTrace(aa.subscribe_authenticated_session_topic_success),await this.client.session.set(N,K),a.addTrace(aa.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:f.requester.metadata})}a.addTrace(aa.publishing_authenticated_session_approve);try{await this.sendResult({topic:y,id:i,result:{cacaos:n,responder:{publicKey:p,metadata:this.client.metadata}},encodeOpts:A,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(f.requester.metadata,u)})}catch(W){throw a.setError(Zo.authenticated_session_approve_publish_failure),W}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:f.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:a.eventId}),{session:K}},this.rejectSessionAuthenticate=async t=>{this.isInitialized();const{id:i,reason:n}=t,a=this.getPendingAuthRequest(i);if(!a)throw new Error(`Could not find pending auth request with id ${i}`);a.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const f=a.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),b=rh(f),p={type:ds,receiverPublicKey:f,senderPublicKey:u};await this.sendError({id:i,topic:b,error:n,encodeOpts:p,rpcOpts:wr.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(a.requester.metadata,a.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Ut("USER_DISCONNECTED"))},this.formatAuthMessage=t=>{this.isInitialized();const{request:i,iss:n}=t;return b2(i,n)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)},this.cleanupDuplicatePairings=async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(a=>{var f,u;return((f=a.peerMetadata)==null?void 0:f.url)&&((u=a.peerMetadata)==null?void 0:u.url)===t.peer.metadata.url&&a.topic&&a.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(a=>this.client.core.pairing.disconnect({topic:a.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}},this.deleteSession=async t=>{var i;const{topic:n,expirerHasDeleted:a=!1,emitEvent:f=!0,id:u=0}=t,{self:b}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Ut("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(b.publicKey)&&await this.client.core.crypto.deleteKeyPair(b.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),a||this.client.core.expirer.del(n),this.client.core.storage.removeItem(fv).catch(p=>this.client.logger.warn(p)),this.getPendingSessionRequests().forEach(p=>{p.topic===n&&this.deletePendingSessionRequest(p.id,Ut("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=En.idle),f&&this.client.events.emit("session_delete",{id:u,topic:n})},this.deleteProposal=async(t,i)=>{if(i)try{const n=this.client.proposal.get(t),a=this.client.core.eventClient.getEvent({topic:n.pairingTopic});a==null||a.setError(sa.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Ut("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")},this.deletePendingSessionRequest=async(t,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),n?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(a=>a.id!==t),n&&(this.sessionRequestQueue.state=En.idle,this.client.events.emit("session_request_expire",{id:t}))},this.deletePendingAuthRequest=async(t,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),n?Promise.resolve():this.client.core.expirer.del(t)])},this.setExpiry=async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))},this.setProposal=async(t,i)=>{this.client.core.expirer.set(t,vr(wr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)},this.setAuthRequest=async(t,i)=>{const{request:n,pairingTopic:a,transportType:f=Kt.relay}=i;this.client.core.expirer.set(t,n.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:t,pairingTopic:a,verifyContext:n.verifyContext,transportType:f})},this.setPendingSessionRequest=async t=>{const{id:i,topic:n,params:a,verifyContext:f}=t,u=a.request.expiryTimestamp||vr(wr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,u),await this.client.pendingRequest.set(i,{id:i,topic:n,params:a,verifyContext:f})},this.sendRequest=async t=>{const{topic:i,method:n,params:a,expiry:f,relayRpcId:u,clientRpcId:b,throwOnFailedPublish:p,appLink:y}=t,A=qs(n,a,b);let R;const O=!!y;try{const W=O?Yo:Bs;R=await this.client.core.crypto.encode(i,A,{encoding:W})}catch(W){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),W}let N;if(xN.includes(n)){const W=fs(JSON.stringify(A)),Q=fs(R);N=await this.client.core.verify.register({id:Q,decryptedId:W})}const K=wr[n].req;if(K.attestation=N,f&&(K.ttl=f),u&&(K.id=u),this.client.core.history.set(i,A),O){const W=kf(y,i,R);await global.Linking.openURL(W,this.client.name)}else{const W=wr[n].req;f&&(W.ttl=f),u&&(W.id=u),p?(W.internal=fn(rr({},W.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,R,W)):this.client.core.relayer.publish(i,R,W).catch(Q=>this.client.logger.error(Q))}return A.id},this.sendResult=async t=>{const{id:i,topic:n,result:a,throwOnFailedPublish:f,encodeOpts:u,appLink:b}=t,p=Kh(i,a);let y;const A=b&&typeof(global==null?void 0:global.Linking)<"u";try{const O=A?Yo:Bs;y=await this.client.core.crypto.encode(n,p,fn(rr({},u||{}),{encoding:O}))}catch(O){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),O}let R;try{R=await this.client.core.history.get(n,i)}catch(O){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),O}if(A){const O=kf(b,n,y);await global.Linking.openURL(O,this.client.name)}else{const O=wr[R.request.method].res;f?(O.internal=fn(rr({},O.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,y,O)):this.client.core.relayer.publish(n,y,O).catch(N=>this.client.logger.error(N))}await this.client.core.history.resolve(p)},this.sendError=async t=>{const{id:i,topic:n,error:a,encodeOpts:f,rpcOpts:u,appLink:b}=t,p=Vh(i,a);let y;const A=b&&typeof(global==null?void 0:global.Linking)<"u";try{const O=A?Yo:Bs;y=await this.client.core.crypto.encode(n,p,fn(rr({},f||{}),{encoding:O}))}catch(O){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),O}let R;try{R=await this.client.core.history.get(n,i)}catch(O){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),O}if(A){const O=kf(b,n,y);await global.Linking.openURL(O,this.client.name)}else{const O=u||wr[R.request.method].res;this.client.core.relayer.publish(n,y,O)}await this.client.core.history.resolve(p)},this.cleanup=async()=>{const t=[],i=[];this.client.session.getAll().forEach(n=>{let a=!1;Rs(n.expiry)&&(a=!0),this.client.core.crypto.keychain.has(n.topic)||(a=!0),a&&t.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{Rs(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...t.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])},this.onRelayEventRequest=async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===En.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=En.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=En.idle},this.processRequest=async t=>{const{topic:i,payload:n,attestation:a,transportType:f,encryptedId:u}=t,b=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:b}))switch(b){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:a,encryptedId:u});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:a,encryptedId:u,transportType:f});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:a,encryptedId:u,transportType:f});default:return this.client.logger.info(`Unsupported request method ${b}`)}},this.onRelayEventResponse=async t=>{const{topic:i,payload:n,transportType:a}=t,f=(await this.client.core.history.get(i,n.id)).request.method;switch(f){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,a);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${f}`)}},this.onRelayEventUnknownPayload=t=>{const{topic:i}=t,{message:n}=Ae("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},this.shouldIgnorePairingRequest=t=>{const{topic:i,requestMethod:n}=t,a=this.expectedPairingMethodMap.get(i);return!a||a.includes(n)?!1:!!(a.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async t=>{const{topic:i,payload:n,attestation:a,encryptedId:f}=t,{params:u,id:b}=n;try{const p=this.client.core.eventClient.getEvent({topic:i});this.isValidConnect(rr({},n.params));const y=u.expiryTimestamp||vr(wr.wc_sessionPropose.req.ttl),A=rr({id:b,pairingTopic:i,expiryTimestamp:y},u);await this.setProposal(b,A);const R=await this.getVerifyContext({attestationId:a,hash:fs(JSON.stringify(n)),encryptedId:f,metadata:A.proposer.metadata});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),p==null||p.setError(os.proposal_listener_not_found)),p==null||p.addTrace(xn.emit_session_proposal),this.client.events.emit("session_proposal",{id:b,params:A,verifyContext:R})}catch(p){await this.sendError({id:b,topic:i,error:p,rpcOpts:wr.wc_sessionPropose.autoReject}),this.client.logger.error(p)}},this.onSessionProposeResponse=async(t,i,n)=>{const{id:a}=i;if(Mn(i)){const{result:f}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:f});const u=this.client.proposal.get(a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:u});const b=u.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:b});const p=f.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:p});const y=await this.client.core.crypto.generateSharedKey(b,p);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:y});const A=await this.client.core.relayer.subscribe(y,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:A}),await this.client.core.pairing.activate({topic:t})}else if($i(i)){await this.client.proposal.delete(a,Ut("USER_DISCONNECTED"));const f=St("session_connect");if(this.events.listenerCount(f)===0)throw new Error(`emitting ${f} without any listeners, 954`);this.events.emit(St("session_connect"),{error:i.error})}},this.onSessionSettleRequest=async(t,i)=>{const{id:n,params:a}=i;try{this.isValidSessionSettleRequest(a);const{relay:f,controller:u,expiry:b,namespaces:p,sessionProperties:y,sessionConfig:A}=i.params,R=fn(rr(rr({topic:t,relay:f,expiry:b,namespaces:p,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},y&&{sessionProperties:y}),A&&{sessionConfig:A}),{transportType:Kt.relay}),O=St("session_connect");if(this.events.listenerCount(O)===0)throw new Error(`emitting ${O} without any listeners 997`);this.events.emit(St("session_connect"),{session:R}),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(f){await this.sendError({id:n,topic:t,error:f}),this.client.logger.error(f)}},this.onSessionSettleResponse=async(t,i)=>{const{id:n}=i;Mn(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(St("session_approve",n),{})):$i(i)&&(await this.client.session.delete(t,Ut("USER_DISCONNECTED")),this.events.emit(St("session_approve",n),{error:i.error}))},this.onSessionUpdateRequest=async(t,i)=>{const{params:n,id:a}=i;try{const f=`${t}_session_update`,u=Qo.get(f);if(u&&this.isRequestOutOfSync(u,a)){this.client.logger.info(`Discarding out of sync request - ${a}`),this.sendError({id:a,topic:t,error:Ut("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(rr({topic:t},n));try{Qo.set(f,a),await this.client.session.update(t,{namespaces:n.namespaces}),await this.sendResult({id:a,topic:t,result:!0,throwOnFailedPublish:!0})}catch(b){throw Qo.delete(f),b}this.client.events.emit("session_update",{id:a,topic:t,params:n})}catch(f){await this.sendError({id:a,topic:t,error:f}),this.client.logger.error(f)}},this.isRequestOutOfSync=(t,i)=>parseInt(i.toString().slice(0,-3))<=parseInt(t.toString().slice(0,-3)),this.onSessionUpdateResponse=(t,i)=>{const{id:n}=i,a=St("session_update",n);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);Mn(i)?this.events.emit(St("session_update",n),{}):$i(i)&&this.events.emit(St("session_update",n),{error:i.error})},this.onSessionExtendRequest=async(t,i)=>{const{id:n}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,vr(Ga)),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:n,topic:t})}catch(a){await this.sendError({id:n,topic:t,error:a}),this.client.logger.error(a)}},this.onSessionExtendResponse=(t,i)=>{const{id:n}=i,a=St("session_extend",n);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);Mn(i)?this.events.emit(St("session_extend",n),{}):$i(i)&&this.events.emit(St("session_extend",n),{error:i.error})},this.onSessionPingRequest=async(t,i)=>{const{id:n}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:t})}catch(a){await this.sendError({id:n,topic:t,error:a}),this.client.logger.error(a)}},this.onSessionPingResponse=(t,i)=>{const{id:n}=i,a=St("session_ping",n);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);setTimeout(()=>{Mn(i)?this.events.emit(St("session_ping",n),{}):$i(i)&&this.events.emit(St("session_ping",n),{error:i.error})},500)},this.onSessionDeleteRequest=async(t,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(a=>{this.client.core.relayer.once(Gr.publish,async()=>{a(await this.deleteSession({topic:t,id:n}))})}),this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Ut("USER_DISCONNECTED")})]).catch(a=>this.client.logger.error(a))}catch(a){this.client.logger.error(a)}},this.onSessionRequest=async t=>{var i,n,a;const{topic:f,payload:u,attestation:b,encryptedId:p,transportType:y}=t,{id:A,params:R}=u;try{await this.isValidRequest(rr({topic:f},R));const O=this.client.session.get(f),N=await this.getVerifyContext({attestationId:b,hash:fs(JSON.stringify(qs("wc_sessionRequest",R,A))),encryptedId:p,metadata:O.peer.metadata,transportType:y}),K={id:A,topic:f,params:R,verifyContext:N};await this.setPendingSessionRequest(K),y===Kt.link_mode&&(i=O.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=O.peer.metadata.redirect)==null?void 0:n.universal),(a=this.client.signConfig)!=null&&a.disableRequestQueue?this.emitSessionRequest(K):(this.addSessionRequestToSessionRequestQueue(K),this.processSessionRequestQueue())}catch(O){await this.sendError({id:A,topic:f,error:O}),this.client.logger.error(O)}},this.onSessionRequestResponse=(t,i)=>{const{id:n}=i,a=St("session_request",n);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);Mn(i)?this.events.emit(St("session_request",n),{result:i.result}):$i(i)&&this.events.emit(St("session_request",n),{error:i.error})},this.onSessionEventRequest=async(t,i)=>{const{id:n,params:a}=i;try{const f=`${t}_session_event_${a.event.name}`,u=Qo.get(f);if(u&&this.isRequestOutOfSync(u,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(rr({topic:t},a)),this.client.events.emit("session_event",{id:n,topic:t,params:a}),Qo.set(f,n)}catch(f){await this.sendError({id:n,topic:t,error:f}),this.client.logger.error(f)}},this.onSessionAuthenticateResponse=(t,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),Mn(i)?this.events.emit(St("session_request",n),{result:i.result}):$i(i)&&this.events.emit(St("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async t=>{var i;const{topic:n,payload:a,attestation:f,encryptedId:u,transportType:b}=t;try{const{requester:p,authPayload:y,expiryTimestamp:A}=a.params,R=await this.getVerifyContext({attestationId:f,hash:fs(JSON.stringify(a)),encryptedId:u,metadata:p.metadata,transportType:b}),O={requester:p,pairingTopic:n,id:a.id,authPayload:y,verifyContext:R,expiryTimestamp:A};await this.setAuthRequest(a.id,{request:O,pairingTopic:n,transportType:b}),b===Kt.link_mode&&(i=p.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(p.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:a.params,id:a.id,verifyContext:R})}catch(p){this.client.logger.error(p);const y=a.params.requester.publicKey,A=await this.client.core.crypto.generateKeyPair(),R=this.getAppLinkIfEnabled(a.params.requester.metadata,b),O={type:ds,receiverPublicKey:y,senderPublicKey:A};await this.sendError({id:a.id,topic:n,error:p,encodeOpts:O,rpcOpts:wr.wc_sessionAuthenticate.autoReject,appLink:R})}},this.addSessionRequestToSessionRequestQueue=t=>{this.sessionRequestQueue.queue.push(t)},this.cleanupAfterResponse=t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=En.idle,this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:t,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(a=>a.topic===t&&a.request.method==="wc_sessionRequest").forEach(a=>{const f=a.request.id,u=St("session_request",f);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(St("session_request",a.request.id),{error:i})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===En.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=En.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}},this.emitSessionRequest=t=>{this.client.events.emit("session_request",t)},this.onPairingCreated=t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:qs("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})},this.isValidConnect=async t=>{if(!oi(t)){const{message:b}=Ae("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(b)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:a,sessionProperties:f,relays:u}=t;if(fi(i)||await this.isValidPairingTopic(i),!tI(u)){const{message:b}=Ae("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(b)}!fi(n)&&bc(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!fi(a)&&bc(a)!==0&&this.validateNamespaces(a,"optionalNamespaces"),fi(f)||this.validateSessionProps(f,"sessionProperties")},this.validateNamespaces=(t,i)=>{const n=eI(t,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async t=>{if(!oi(t))throw new Error(Ae("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:n,relayProtocol:a,sessionProperties:f}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const u=this.client.proposal.get(i),b=Cl(n,"approve()");if(b)throw new Error(b.message);const p=xg(u.requiredNamespaces,n,"approve()");if(p)throw new Error(p.message);if(!fr(a,!0)){const{message:y}=Ae("MISSING_OR_INVALID",`approve() relayProtocol: ${a}`);throw new Error(y)}fi(f)||this.validateSessionProps(f,"sessionProperties")},this.isValidReject=async t=>{if(!oi(t)){const{message:a}=Ae("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(a)}const{id:i,reason:n}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!iI(n)){const{message:a}=Ae("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(a)}},this.isValidSessionSettleRequest=t=>{if(!oi(t)){const{message:p}=Ae("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(p)}const{relay:i,controller:n,namespaces:a,expiry:f}=t;if(!S2(i)){const{message:p}=Ae("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(p)}const u=WS(n,"onSessionSettleRequest()");if(u)throw new Error(u.message);const b=Cl(a,"onSessionSettleRequest()");if(b)throw new Error(b.message);if(Rs(f)){const{message:p}=Ae("EXPIRED","onSessionSettleRequest()");throw new Error(p)}},this.isValidUpdate=async t=>{if(!oi(t)){const{message:b}=Ae("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(b)}const{topic:i,namespaces:n}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const a=this.client.session.get(i),f=Cl(n,"update()");if(f)throw new Error(f.message);const u=xg(a.requiredNamespaces,n,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async t=>{if(!oi(t)){const{message:n}=Ae("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(n)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)},this.isValidRequest=async t=>{if(!oi(t)){const{message:b}=Ae("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(b)}const{topic:i,request:n,chainId:a,expiry:f}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:u}=this.client.session.get(i);if(!Eg(u,a)){const{message:b}=Ae("MISSING_OR_INVALID",`request() chainId: ${a}`);throw new Error(b)}if(!nI(n)){const{message:b}=Ae("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(b)}if(!oI(u,a,n.method)){const{message:b}=Ae("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(b)}if(f&&!uI(f,$l)){const{message:b}=Ae("MISSING_OR_INVALID",`request() expiry: ${f}. Expiry must be a number (in seconds) between ${$l.min} and ${$l.max}`);throw new Error(b)}},this.isValidRespond=async t=>{var i;if(!oi(t)){const{message:f}=Ae("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(f)}const{topic:n,response:a}=t;try{await this.isValidSessionTopic(n)}catch(f){throw(i=t==null?void 0:t.response)!=null&&i.id&&this.cleanupAfterResponse(t),f}if(!sI(a)){const{message:f}=Ae("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(a)}`);throw new Error(f)}},this.isValidPing=async t=>{if(!oi(t)){const{message:n}=Ae("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(n)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async t=>{if(!oi(t)){const{message:u}=Ae("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(u)}const{topic:i,event:n,chainId:a}=t;await this.isValidSessionTopic(i);const{namespaces:f}=this.client.session.get(i);if(!Eg(f,a)){const{message:u}=Ae("MISSING_OR_INVALID",`emit() chainId: ${a}`);throw new Error(u)}if(!aI(n)){const{message:u}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}if(!cI(f,a,n.name)){const{message:u}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}},this.isValidDisconnect=async t=>{if(!oi(t)){const{message:n}=Ae("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(n)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidAuthenticate=t=>{const{chains:i,uri:n,domain:a,nonce:f}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!fr(n,!1))throw new Error("uri is required parameter");if(!fr(a,!1))throw new Error("domain is required parameter");if(!fr(f,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(b=>ac(b).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:u}=ac(i[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async t=>{const{attestationId:i,hash:n,encryptedId:a,metadata:f,transportType:u}=t,b={verified:{verifyUrl:f.verifyUrl||uc,validation:"UNKNOWN",origin:f.url||""}};try{if(u===Kt.link_mode){const y=this.getAppLinkIfEnabled(f,u);return b.verified.validation=y&&new URL(y).origin===new URL(f.url).origin?"VALID":"INVALID",b}const p=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:a,verifyUrl:f.verifyUrl});p&&(b.verified.origin=p.origin,b.verified.isScam=p.isScam,b.verified.validation=p.origin===new URL(f.url).origin?"VALID":"INVALID")}catch(p){this.client.logger.warn(p)}return this.client.logger.debug(`Verify context: ${JSON.stringify(b)}`),b},this.validateSessionProps=(t,i)=>{Object.values(t).forEach(n=>{if(!fr(n,!1)){const{message:a}=Ae("MISSING_OR_INVALID",`${i} must be in Record format. Received: ${JSON.stringify(n)}`);throw new Error(a)}})},this.getPendingAuthRequest=t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0},this.addToRecentlyDeleted=(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const a=this.recentlyDeletedLimit/2;for(const f of this.recentlyDeletedMap.keys()){if(n++>=a)break;this.recentlyDeletedMap.delete(f)}}},this.checkRecentlyDeleted=t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:n}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(n)}},this.isLinkModeEnabled=(t,i)=>{var n,a,f,u,b,p,y,A,R;return!t||i!==Kt.link_mode?!1:((a=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:a.linkMode)===!0&&((u=(f=this.client.metadata)==null?void 0:f.redirect)==null?void 0:u.universal)!==void 0&&((p=(b=this.client.metadata)==null?void 0:b.redirect)==null?void 0:p.universal)!==""&&((y=t==null?void 0:t.redirect)==null?void 0:y.universal)!==void 0&&((A=t==null?void 0:t.redirect)==null?void 0:A.universal)!==""&&((R=t==null?void 0:t.redirect)==null?void 0:R.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"},this.getAppLinkIfEnabled=(t,i)=>{var n;return this.isLinkModeEnabled(t,i)?(n=t==null?void 0:t.redirect)==null?void 0:n.universal:void 0},this.handleLinkModeMessage=({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=q1(t,"topic")||"",n=decodeURIComponent(q1(t,"wc_ev")||""),a=this.client.session.keys.includes(i);a&&this.client.session.update(i,{transportType:Kt.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:a})},this.registerLinkModeListeners=async()=>{var t;if(z0()||vo()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}}isInitialized(){if(!this.initialized){const{message:e}=Ae("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Gr.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:n,transportType:a}=e,{publicKey:f}=this.client.auth.authKeys.keys.includes(sh)?this.client.auth.authKeys.get(sh):{responseTopic:void 0,publicKey:void 0},u=await this.client.core.crypto.decode(t,i,{receiverPublicKey:f,encoding:a===Kt.link_mode?Yo:Bs});try{Z0(u)?(this.client.core.history.set(t,u),this.onRelayEventRequest({topic:t,payload:u,attestation:n,transportType:a,encryptedId:fs(i)})):Gh(u)?(await this.client.core.history.resolve(u),await this.onRelayEventResponse({topic:t,payload:u,transportType:a}),this.client.core.history.delete(t,u.id)):this.onRelayEventUnknownPayload({topic:t,payload:u,transportType:a})}catch(b){this.client.logger.error(b)}}registerExpirerEvents(){this.client.core.expirer.on(Li.expired,async e=>{const{topic:t,id:i}=Db(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,Ae("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,Ae("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(ca.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(ca.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!fr(e,!1)){const{message:t}=Ae("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Rs(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=Ae("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!fr(e,!1)){const{message:t}=Ae("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=Ae("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Rs(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=Ae("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=Ae("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(fr(e,!1)){const{message:t}=Ae("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=Ae("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!rI(e)){const{message:t}=Ae("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=Ae("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Rs(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=Ae("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class BN extends xa{constructor(e,t){super(e,t,wN,rd),this.core=e,this.logger=t}}class qN extends xa{constructor(e,t){super(e,t,_N,rd),this.core=e,this.logger=t}}class LN extends xa{constructor(e,t){super(e,t,EN,rd,i=>i.id),this.core=e,this.logger=t}}class UN extends xa{constructor(e,t){super(e,t,MN,Jh,()=>sh),this.core=e,this.logger=t}}class $N extends xa{constructor(e,t){super(e,t,PN,Jh),this.core=e,this.logger=t}}class zN extends xa{constructor(e,t){super(e,t,ON,Jh,i=>i.id),this.core=e,this.logger=t}}class jN{constructor(e,t){this.core=e,this.logger=t,this.authKeys=new UN(this.core,this.logger),this.pairingTopics=new $N(this.core,this.logger),this.requests=new zN(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class id extends FM{constructor(e){super(e),this.protocol=tm,this.version=rm,this.name=Ul.name,this.events=new Hi.EventEmitter,this.on=(i,n)=>this.events.on(i,n),this.once=(i,n)=>this.events.once(i,n),this.off=(i,n)=>this.events.off(i,n),this.removeListener=(i,n)=>this.events.removeListener(i,n),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}},this.update=async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}},this.request=async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}},this.find=i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.authenticate=async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(a){throw this.logger.error(a.message),a}},this.formatAuthMessage=i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}},this.approveSessionAuthenticate=async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.rejectSessionAuthenticate=async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.name=(e==null?void 0:e.name)||Ul.name,this.metadata=(e==null?void 0:e.metadata)||Ob(),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Nc(Hh({level:(e==null?void 0:e.logger)||Ul.logger}));this.core=(e==null?void 0:e.core)||new yN(e),this.logger=Yr(t,this.name),this.session=new qN(this.core,this.logger),this.proposal=new BN(this.core,this.logger),this.pendingRequest=new LN(this.core,this.logger),this.engine=new FN(this),this.auth=new jN(this.core,this.logger)}static async init(e){const t=new id(e);return await t.initialize(),t}get context(){return di(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),this.engine.processRelayMessageCache()}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var _0={exports:{}};(function(r,e){var t=typeof self<"u"?self:ji,i=function(){function a(){this.fetch=!1,this.DOMException=t.DOMException}return a.prototype=t,new a}();(function(a){(function(f){var u={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function b(h){return h&&DataView.prototype.isPrototypeOf(h)}if(u.arrayBuffer)var p=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],y=ArrayBuffer.isView||function(h){return h&&p.indexOf(Object.prototype.toString.call(h))>-1};function A(h){if(typeof h!="string"&&(h=String(h)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(h))throw new TypeError("Invalid character in header field name");return h.toLowerCase()}function R(h){return typeof h!="string"&&(h=String(h)),h}function O(h){var v={next:function(){var _=h.shift();return{done:_===void 0,value:_}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function N(h){this.map={},h instanceof N?h.forEach(function(v,_){this.append(_,v)},this):Array.isArray(h)?h.forEach(function(v){this.append(v[0],v[1])},this):h&&Object.getOwnPropertyNames(h).forEach(function(v){this.append(v,h[v])},this)}N.prototype.append=function(h,v){h=A(h),v=R(v);var _=this.map[h];this.map[h]=_?_+", "+v:v},N.prototype.delete=function(h){delete this.map[A(h)]},N.prototype.get=function(h){return h=A(h),this.has(h)?this.map[h]:null},N.prototype.has=function(h){return this.map.hasOwnProperty(A(h))},N.prototype.set=function(h,v){this.map[A(h)]=R(v)},N.prototype.forEach=function(h,v){for(var _ in this.map)this.map.hasOwnProperty(_)&&h.call(v,this.map[_],_,this)},N.prototype.keys=function(){var h=[];return this.forEach(function(v,_){h.push(_)}),O(h)},N.prototype.values=function(){var h=[];return this.forEach(function(v){h.push(v)}),O(h)},N.prototype.entries=function(){var h=[];return this.forEach(function(v,_){h.push([_,v])}),O(h)},u.iterable&&(N.prototype[Symbol.iterator]=N.prototype.entries);function K(h){if(h.bodyUsed)return Promise.reject(new TypeError("Already read"));h.bodyUsed=!0}function W(h){return new Promise(function(v,_){h.onload=function(){v(h.result)},h.onerror=function(){_(h.error)}})}function Q(h){var v=new FileReader,_=W(v);return v.readAsArrayBuffer(h),_}function j(h){var v=new FileReader,_=W(v);return v.readAsText(h),_}function Y(h){for(var v=new Uint8Array(h),_=new Array(v.length),I=0;I-1?v:h}function B(h,v){v=v||{};var _=v.body;if(h instanceof B){if(h.bodyUsed)throw new TypeError("Already read");this.url=h.url,this.credentials=h.credentials,v.headers||(this.headers=new N(h.headers)),this.method=h.method,this.mode=h.mode,this.signal=h.signal,!_&&h._bodyInit!=null&&(_=h._bodyInit,h.bodyUsed=!0)}else this.url=String(h);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new N(v.headers)),this.method=x(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&_)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(_)}B.prototype.clone=function(){return new B(this,{body:this._bodyInit})};function ae(h){var v=new FormData;return h.trim().split("&").forEach(function(_){if(_){var I=_.split("="),M=I.shift().replace(/\+/g," "),S=I.join("=").replace(/\+/g," ");v.append(decodeURIComponent(M),decodeURIComponent(S))}}),v}function le(h){var v=new N,_=h.replace(/\r?\n[\t ]+/g," ");return _.split(/\r?\n/).forEach(function(I){var M=I.split(":"),S=M.shift().trim();if(S){var d=M.join(":").trim();v.append(S,d)}}),v}k.call(B.prototype);function F(h,v){v||(v={}),this.type="default",this.status=v.status===void 0?200:v.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in v?v.statusText:"OK",this.headers=new N(v.headers),this.url=v.url||"",this._initBody(h)}k.call(F.prototype),F.prototype.clone=function(){return new F(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new N(this.headers),url:this.url})},F.error=function(){var h=new F(null,{status:0,statusText:""});return h.type="error",h};var m=[301,302,303,307,308];F.redirect=function(h,v){if(m.indexOf(v)===-1)throw new RangeError("Invalid status code");return new F(null,{status:v,headers:{location:h}})},f.DOMException=a.DOMException;try{new f.DOMException}catch{f.DOMException=function(v,_){this.message=v,this.name=_;var I=Error(v);this.stack=I.stack},f.DOMException.prototype=Object.create(Error.prototype),f.DOMException.prototype.constructor=f.DOMException}function c(h,v){return new Promise(function(_,I){var M=new B(h,v);if(M.signal&&M.signal.aborted)return I(new f.DOMException("Aborted","AbortError"));var S=new XMLHttpRequest;function d(){S.abort()}S.onload=function(){var g={status:S.status,statusText:S.statusText,headers:le(S.getAllResponseHeaders()||"")};g.url="responseURL"in S?S.responseURL:g.headers.get("X-Request-URL");var T="response"in S?S.response:S.responseText;_(new F(T,g))},S.onerror=function(){I(new TypeError("Network request failed"))},S.ontimeout=function(){I(new TypeError("Network request failed"))},S.onabort=function(){I(new f.DOMException("Aborted","AbortError"))},S.open(M.method,M.url,!0),M.credentials==="include"?S.withCredentials=!0:M.credentials==="omit"&&(S.withCredentials=!1),"responseType"in S&&u.blob&&(S.responseType="blob"),M.headers.forEach(function(g,T){S.setRequestHeader(T,g)}),M.signal&&(M.signal.addEventListener("abort",d),S.onreadystatechange=function(){S.readyState===4&&M.signal.removeEventListener("abort",d)}),S.send(typeof M._bodyInit>"u"?null:M._bodyInit)})}return c.polyfill=!0,a.fetch||(a.fetch=c,a.Headers=N,a.Request=B,a.Response=F),f.Headers=N,f.Request=B,f.Response=F,f.fetch=c,Object.defineProperty(f,"__esModule",{value:!0}),f})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,r.exports=e})(_0,_0.exports);var kN=_0.exports;const lv=S0(kN);var HN=Object.defineProperty,KN=Object.defineProperties,VN=Object.getOwnPropertyDescriptors,dv=Object.getOwnPropertySymbols,GN=Object.prototype.hasOwnProperty,WN=Object.prototype.propertyIsEnumerable,pv=(r,e,t)=>e in r?HN(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,gv=(r,e)=>{for(var t in e||(e={}))GN.call(e,t)&&pv(r,t,e[t]);if(dv)for(var t of dv(e))WN.call(e,t)&&pv(r,t,e[t]);return r},vv=(r,e)=>KN(r,VN(e));const JN={Accept:"application/json","Content-Type":"application/json"},YN="POST",bv={headers:JN,method:YN},mv=10;class Gn{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new Hi.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ug(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const t=vs(e),i=await(await lv(this.url,vv(gv({},bv),{body:t}))).json();this.onPayload({data:i})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!Ug(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,n)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),n(a)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=vs({id:1,jsonrpc:"2.0",method:"test",params:[]});await lv(e,vv(gv({},bv),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?ga(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),n=i.message||i.toString(),a=Vh(e,n);this.events.emit("payload",a)}parseError(e,t=this.url){return D2(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>mv&&this.events.setMaxListeners(mv)}}const yv="error",QN="wss://relay.walletconnect.org",XN="wc",ZN="universal_provider",wv=`${XN}@2:${ZN}:`,sm="https://rpc.walletconnect.org/v1/",Ya="generic",eC=`${sm}bundler`,vn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var rc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},A0={exports:{}};/** +* @license +* Lodash +* Copyright OpenJS Foundation and other contributors +* Released under MIT license +* Based on Underscore.js 1.8.3 +* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +*/(function(r,e){(function(){var t,i="4.17.21",n=200,a="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",f="Expected a function",u="Invalid `variable` option passed into `_.template`",b="__lodash_hash_undefined__",p=500,y="__lodash_placeholder__",A=1,R=2,O=4,N=1,K=2,W=1,Q=2,j=4,Y=8,U=16,k=32,G=64,x=128,B=256,ae=512,le=30,F="...",m=800,c=16,h=1,v=2,_=3,I=1/0,M=9007199254740991,S=17976931348623157e292,d=NaN,g=4294967295,T=g-1,Z=g>>>1,se=[["ary",x],["bind",W],["bindKey",Q],["curry",Y],["curryRight",U],["flip",ae],["partial",k],["partialRight",G],["rearg",B]],P="[object Arguments]",ee="[object Array]",q="[object AsyncFunction]",z="[object Boolean]",H="[object Date]",w="[object DOMException]",$="[object Error]",ne="[object Function]",ce="[object GeneratorFunction]",he="[object Map]",ye="[object Number]",we="[object Null]",Ce="[object Object]",Qe="[object Promise]",Oe="[object Proxy]",Te="[object RegExp]",Ie="[object Set]",me="[object String]",Re="[object Symbol]",De="[object Undefined]",ve="[object WeakMap]",Ne="[object WeakSet]",Se="[object ArrayBuffer]",be="[object DataView]",Le="[object Float32Array]",Me="[object Float64Array]",_e="[object Int8Array]",He="[object Int16Array]",Ve="[object Int32Array]",Ee="[object Uint8Array]",Ke="[object Uint8ClampedArray]",ut="[object Uint16Array]",Ge="[object Uint32Array]",_t=/\b__p \+= '';/g,lt=/\b(__p \+=) '' \+/g,Je=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Et=/&(?:amp|lt|gt|quot|#39);/g,It=/[&<>"']/g,Fe=RegExp(Et.source),Xe=RegExp(It.source),tt=/<%-([\s\S]+?)%>/g,Be=/<%([\s\S]+?)%>/g,et=/<%=([\s\S]+?)%>/g,Ze=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$e=/^\w*$/,ft=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,rt=/[\\^$.*+?()[\]{}|]/g,ze=RegExp(rt.source),it=/^\s+/,st=/\s/,qe=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Ye=/\{\n\/\* \[wrapped with (.+)\] \*/,ht=/,? & /,je=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Tt=/[()=,{}\[\]\/\s]/,Dt=/\\(\\)?/g,at=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,bt=/\w*$/,Cr=/^[-+]0x[0-9a-f]+$/i,Tr=/^0b[01]+$/i,Dr=/^\[object .+?Constructor\]$/,Fr=/^0o[0-7]+$/i,Br=/^(?:0|[1-9]\d*)$/,er=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Qr=/($^)/,Gi=/['\n\r\u2028\u2029\\]/g,Xr="\\ud800-\\udfff",Wi="\\u0300-\\u036f",Ji="\\ufe20-\\ufe2f",Zr="\\u20d0-\\u20ff",Si=Wi+Ji+Zr,Ii="\\u2700-\\u27bf",lr="a-z\\xdf-\\xf6\\xf8-\\xff",Yi="\\xac\\xb1\\xd7\\xf7",Qi="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",Xi="\\u2000-\\u206f",js=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Dc="A-Z\\xc0-\\xd6\\xd8-\\xde",Fc="\\ufe0e\\ufe0f",ks=Yi+Qi+Xi+js,xo="['’]",Hs="["+Xr+"]",So="["+ks+"]",Ks="["+Si+"]",Bc="\\d+",Yh="["+Ii+"]",qc="["+lr+"]",Lc="[^"+Xr+ks+Bc+Ii+lr+Dc+"]",Ma="\\ud83c[\\udffb-\\udfff]",Qh="(?:"+Ks+"|"+Ma+")",Uc="[^"+Xr+"]",Pa="(?:\\ud83c[\\udde6-\\uddff]){2}",ms="[\\ud800-\\udbff][\\udc00-\\udfff]",pi="["+Dc+"]",$c="\\u200d",zc="(?:"+qc+"|"+Lc+")",bn="(?:"+pi+"|"+Lc+")",jc="(?:"+xo+"(?:d|ll|m|re|s|t|ve))?",kc="(?:"+xo+"(?:D|LL|M|RE|S|T|VE))?",Hc=Qh+"?",Kc="["+Fc+"]?",Xh="(?:"+$c+"(?:"+[Uc,Pa,ms].join("|")+")"+Kc+Hc+")*",Wn="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Vc="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Gc=Kc+Hc+Xh,Oa="(?:"+[Yh,Pa,ms].join("|")+")"+Gc,Zh="(?:"+[Uc+Ks+"?",Ks,Pa,ms,Hs].join("|")+")",Io=RegExp(xo,"g"),eu=RegExp(Ks,"g"),Ra=RegExp(Ma+"(?="+Ma+")|"+Zh+Gc,"g"),Wc=RegExp([pi+"?"+qc+"+"+jc+"(?="+[So,pi,"$"].join("|")+")",bn+"+"+kc+"(?="+[So,pi+zc,"$"].join("|")+")",pi+"?"+zc+"+"+jc,pi+"+"+kc,Vc,Wn,Bc,Oa].join("|"),"g"),Jc=RegExp("["+$c+Xr+Si+Fc+"]"),Vs=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Yc=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],tu=-1,zt={};zt[Le]=zt[Me]=zt[_e]=zt[He]=zt[Ve]=zt[Ee]=zt[Ke]=zt[ut]=zt[Ge]=!0,zt[P]=zt[ee]=zt[Se]=zt[z]=zt[be]=zt[H]=zt[$]=zt[ne]=zt[he]=zt[ye]=zt[Ce]=zt[Te]=zt[Ie]=zt[me]=zt[ve]=!1;var $t={};$t[P]=$t[ee]=$t[Se]=$t[be]=$t[z]=$t[H]=$t[Le]=$t[Me]=$t[_e]=$t[He]=$t[Ve]=$t[he]=$t[ye]=$t[Ce]=$t[Te]=$t[Ie]=$t[me]=$t[Re]=$t[Ee]=$t[Ke]=$t[ut]=$t[Ge]=!0,$t[$]=$t[ne]=$t[ve]=!1;var V={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},te={"&":"&","<":"<",">":">",'"':""","'":"'"},pe={"&":"&","<":"<",">":">",""":'"',"'":"'"},Ue={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},jt=parseFloat,pt=parseInt,Jt=typeof rc=="object"&&rc&&rc.Object===Object&&rc,hr=typeof self=="object"&&self&&self.Object===Object&&self,Nt=Jt||hr||Function("return this")(),kt=e&&!e.nodeType&&e,sr=kt&&!0&&r&&!r.nodeType&&r,ei=sr&&sr.exports===kt,ur=ei&&Jt.process,Yt=function(){try{var re=sr&&sr.require&&sr.require("util").types;return re||ur&&ur.binding&&ur.binding("util")}catch{}}(),jr=Yt&&Yt.isArrayBuffer,Zi=Yt&&Yt.isDate,Mi=Yt&&Yt.isMap,mn=Yt&&Yt.isRegExp,Mo=Yt&&Yt.isSet,Gs=Yt&&Yt.isTypedArray;function br(re,fe,oe){switch(oe.length){case 0:return re.call(fe);case 1:return re.call(fe,oe[0]);case 2:return re.call(fe,oe[0],oe[1]);case 3:return re.call(fe,oe[0],oe[1],oe[2])}return re.apply(fe,oe)}function cm(re,fe,oe,ke){for(var dt=-1,Ft=re==null?0:re.length;++dt-1}function ru(re,fe,oe){for(var ke=-1,dt=re==null?0:re.length;++ke-1;);return oe}function dd(re,fe){for(var oe=re.length;oe--&&Na(fe,re[oe],0)>-1;);return oe}function bm(re,fe){for(var oe=re.length,ke=0;oe--;)re[oe]===fe&&++ke;return ke}var mm=au(V),ym=au(te);function wm(re){return"\\"+Ue[re]}function _m(re,fe){return re==null?t:re[fe]}function Ca(re){return Jc.test(re)}function Am(re){return Vs.test(re)}function Em(re){for(var fe,oe=[];!(fe=re.next()).done;)oe.push(fe.value);return oe}function hu(re){var fe=-1,oe=Array(re.size);return re.forEach(function(ke,dt){oe[++fe]=[dt,ke]}),oe}function pd(re,fe){return function(oe){return re(fe(oe))}}function _s(re,fe){for(var oe=-1,ke=re.length,dt=0,Ft=[];++oe-1}function h6(s,o){var l=this.__data__,E=gf(l,s);return E<0?(++this.size,l.push([s,o])):l[E][1]=o,this}Jn.prototype.clear=a6,Jn.prototype.delete=o6,Jn.prototype.get=c6,Jn.prototype.has=f6,Jn.prototype.set=h6;function Yn(s){var o=-1,l=s==null?0:s.length;for(this.clear();++o=o?s:o)),s}function Ni(s,o,l,E,C,L){var J,X=o&A,ie=o&R,ue=o&O;if(l&&(J=C?l(s,E,C,L):l(s)),J!==t)return J;if(!Zt(s))return s;var de=gt(s);if(de){if(J=py(s),!X)return ti(s,J)}else{var ge=Lr(s),Pe=ge==ne||ge==ce;if(Ms(s))return Yd(s,X);if(ge==Ce||ge==P||Pe&&!C){if(J=ie||Pe?{}:gp(s),!X)return ie?iy(s,I6(J,s)):ry(s,Id(J,s))}else{if(!$t[ge])return C?s:{};J=gy(s,ge,X)}}L||(L=new tn);var We=L.get(s);if(We)return We;L.set(s,J),Hp(s)?s.forEach(function(ct){J.add(Ni(ct,o,l,ct,s,L))}):jp(s)&&s.forEach(function(ct,xt){J.set(xt,Ni(ct,o,l,xt,s,L))});var ot=ue?ie?Bu:Fu:ie?ii:mr,wt=de?t:ot(s);return Pi(wt||s,function(ct,xt){wt&&(xt=ct,ct=s[xt]),Do(J,xt,Ni(ct,o,l,xt,s,L))}),J}function M6(s){var o=mr(s);return function(l){return Md(l,s,o)}}function Md(s,o,l){var E=l.length;if(s==null)return!E;for(s=Ht(s);E--;){var C=l[E],L=o[C],J=s[C];if(J===t&&!(C in s)||!L(J))return!1}return!0}function Pd(s,o,l){if(typeof s!="function")throw new Oi(f);return zo(function(){s.apply(t,l)},o)}function Fo(s,o,l,E){var C=-1,L=Qc,J=!0,X=s.length,ie=[],ue=o.length;if(!X)return ie;l&&(o=Xt(o,gi(l))),E?(L=ru,J=!1):o.length>=n&&(L=Po,J=!1,o=new Ys(o));e:for(;++CC?0:C+l),E=E===t||E>C?C:yt(E),E<0&&(E+=C),E=l>E?0:Vp(E);l0&&l(X)?o>1?Mr(X,o-1,l,E,C):ws(C,X):E||(C[C.length]=X)}return C}var bu=rp(),Nd=rp(!0);function yn(s,o){return s&&bu(s,o,mr)}function mu(s,o){return s&&Nd(s,o,mr)}function bf(s,o){return ys(o,function(l){return ts(s[l])})}function Xs(s,o){o=Ss(o,s);for(var l=0,E=o.length;s!=null&&lo}function R6(s,o){return s!=null&&Lt.call(s,o)}function N6(s,o){return s!=null&&o in Ht(s)}function C6(s,o,l){return s>=qr(o,l)&&s=120&&de.length>=120)?new Ys(J&&de):t}de=s[0];var ge=-1,Pe=X[0];e:for(;++ge-1;)X!==s&&cf.call(X,ie,1),cf.call(s,ie,1);return s}function jd(s,o){for(var l=s?o.length:0,E=l-1;l--;){var C=o[l];if(l==E||C!==L){var L=C;es(C)?cf.call(s,C,1):Pu(s,C)}}return s}function Su(s,o){return s+uf(Ad()*(o-s+1))}function K6(s,o,l,E){for(var C=-1,L=pr(hf((o-s)/(l||1)),0),J=oe(L);L--;)J[E?L:++C]=s,s+=l;return J}function Iu(s,o){var l="";if(!s||o<1||o>M)return l;do o%2&&(l+=s),o=uf(o/2),o&&(s+=s);while(o);return l}function At(s,o){return ku(mp(s,o,ni),s+"")}function V6(s){return Sd(ka(s))}function G6(s,o){var l=ka(s);return Pf(l,Qs(o,0,l.length))}function Lo(s,o,l,E){if(!Zt(s))return s;o=Ss(o,s);for(var C=-1,L=o.length,J=L-1,X=s;X!=null&&++CC?0:C+o),l=l>C?C:l,l<0&&(l+=C),C=o>l?0:l-o>>>0,o>>>=0;for(var L=oe(C);++E>>1,J=s[L];J!==null&&!bi(J)&&(l?J<=o:J=n){var ue=o?null:oy(s);if(ue)return Zc(ue);J=!1,C=Po,ie=new Ys}else ie=o?[]:X;e:for(;++E=E?s:Ci(s,o,l)}var Jd=Lm||function(s){return Nt.clearTimeout(s)};function Yd(s,o){if(o)return s.slice();var l=s.length,E=bd?bd(l):new s.constructor(l);return s.copy(E),E}function Cu(s){var o=new s.constructor(s.byteLength);return new af(o).set(new af(s)),o}function X6(s,o){var l=o?Cu(s.buffer):s.buffer;return new s.constructor(l,s.byteOffset,s.byteLength)}function Z6(s){var o=new s.constructor(s.source,bt.exec(s));return o.lastIndex=s.lastIndex,o}function ey(s){return To?Ht(To.call(s)):{}}function Qd(s,o){var l=o?Cu(s.buffer):s.buffer;return new s.constructor(l,s.byteOffset,s.length)}function Xd(s,o){if(s!==o){var l=s!==t,E=s===null,C=s===s,L=bi(s),J=o!==t,X=o===null,ie=o===o,ue=bi(o);if(!X&&!ue&&!L&&s>o||L&&J&&ie&&!X&&!ue||E&&J&&ie||!l&&ie||!C)return 1;if(!E&&!L&&!ue&&s=X)return ie;var ue=l[E];return ie*(ue=="desc"?-1:1)}}return s.index-o.index}function Zd(s,o,l,E){for(var C=-1,L=s.length,J=l.length,X=-1,ie=o.length,ue=pr(L-J,0),de=oe(ie+ue),ge=!E;++X1?l[C-1]:t,J=C>2?l[2]:t;for(L=s.length>3&&typeof L=="function"?(C--,L):t,J&&Hr(l[0],l[1],J)&&(L=C<3?t:L,C=1),o=Ht(o);++E-1?C[L?o[J]:J]:t}}function sp(s){return Zn(function(o){var l=o.length,E=l,C=Ri.prototype.thru;for(s&&o.reverse();E--;){var L=o[E];if(typeof L!="function")throw new Oi(f);if(C&&!J&&If(L)=="wrapper")var J=new Ri([],!0)}for(E=J?E:l;++E1&&Ct.reverse(),de&&ieX))return!1;var ue=L.get(s),de=L.get(o);if(ue&&de)return ue==o&&de==s;var ge=-1,Pe=!0,We=l&K?new Ys:t;for(L.set(s,o),L.set(o,s);++ge1?"& ":"")+o[E],o=o.join(l>2?", ":" "),s.replace(qe,`{ +/* [wrapped with `+o+`] */ +`)}function by(s){return gt(s)||ta(s)||!!(wd&&s&&s[wd])}function es(s,o){var l=typeof s;return o=o??M,!!o&&(l=="number"||l!="symbol"&&Br.test(s))&&s>-1&&s%1==0&&s0){if(++o>=m)return arguments[0]}else o=0;return s.apply(t,arguments)}}function Pf(s,o){var l=-1,E=s.length,C=E-1;for(o=o===t?E:o;++l1?s[o-1]:t;return l=typeof l=="function"?(s.pop(),l):t,Rp(s,l)});function Np(s){var o=D(s);return o.__chain__=!0,o}function P3(s,o){return o(s),s}function Of(s,o){return o(s)}var O3=Zn(function(s){var o=s.length,l=o?s[0]:0,E=this.__wrapped__,C=function(L){return vu(L,s)};return o>1||this.__actions__.length||!(E instanceof Mt)||!es(l)?this.thru(C):(E=E.slice(l,+l+(o?1:0)),E.__actions__.push({func:Of,args:[C],thisArg:t}),new Ri(E,this.__chain__).thru(function(L){return o&&!L.length&&L.push(t),L}))});function R3(){return Np(this)}function N3(){return new Ri(this.value(),this.__chain__)}function C3(){this.__values__===t&&(this.__values__=Kp(this.value()));var s=this.__index__>=this.__values__.length,o=s?t:this.__values__[this.__index__++];return{done:s,value:o}}function T3(){return this}function D3(s){for(var o,l=this;l instanceof pf;){var E=xp(l);E.__index__=0,E.__values__=t,o?C.__wrapped__=E:o=E;var C=E;l=l.__wrapped__}return C.__wrapped__=s,o}function F3(){var s=this.__wrapped__;if(s instanceof Mt){var o=s;return this.__actions__.length&&(o=new Mt(this)),o=o.reverse(),o.__actions__.push({func:Of,args:[Hu],thisArg:t}),new Ri(o,this.__chain__)}return this.thru(Hu)}function B3(){return Gd(this.__wrapped__,this.__actions__)}var q3=_f(function(s,o,l){Lt.call(s,l)?++s[l]:Qn(s,l,1)});function L3(s,o,l){var E=gt(s)?ad:P6;return l&&Hr(s,o,l)&&(o=t),E(s,nt(o,3))}function U3(s,o){var l=gt(s)?ys:Rd;return l(s,nt(o,3))}var $3=np(Sp),z3=np(Ip);function j3(s,o){return Mr(Rf(s,o),1)}function k3(s,o){return Mr(Rf(s,o),I)}function H3(s,o,l){return l=l===t?1:yt(l),Mr(Rf(s,o),l)}function Cp(s,o){var l=gt(s)?Pi:Es;return l(s,nt(o,3))}function Tp(s,o){var l=gt(s)?fm:Od;return l(s,nt(o,3))}var K3=_f(function(s,o,l){Lt.call(s,l)?s[l].push(o):Qn(s,l,[o])});function V3(s,o,l,E){s=ri(s)?s:ka(s),l=l&&!E?yt(l):0;var C=s.length;return l<0&&(l=pr(C+l,0)),Ff(s)?l<=C&&s.indexOf(o,l)>-1:!!C&&Na(s,o,l)>-1}var G3=At(function(s,o,l){var E=-1,C=typeof o=="function",L=ri(s)?oe(s.length):[];return Es(s,function(J){L[++E]=C?br(o,J,l):Bo(J,o,l)}),L}),W3=_f(function(s,o,l){Qn(s,l,o)});function Rf(s,o){var l=gt(s)?Xt:Bd;return l(s,nt(o,3))}function J3(s,o,l,E){return s==null?[]:(gt(o)||(o=o==null?[]:[o]),l=E?t:l,gt(l)||(l=l==null?[]:[l]),$d(s,o,l))}var Y3=_f(function(s,o,l){s[l?0:1].push(o)},function(){return[[],[]]});function Q3(s,o,l){var E=gt(s)?iu:hd,C=arguments.length<3;return E(s,nt(o,4),l,C,Es)}function X3(s,o,l){var E=gt(s)?hm:hd,C=arguments.length<3;return E(s,nt(o,4),l,C,Od)}function Z3(s,o){var l=gt(s)?ys:Rd;return l(s,Tf(nt(o,3)))}function ew(s){var o=gt(s)?Sd:V6;return o(s)}function tw(s,o,l){(l?Hr(s,o,l):o===t)?o=1:o=yt(o);var E=gt(s)?E6:G6;return E(s,o)}function rw(s){var o=gt(s)?x6:J6;return o(s)}function iw(s){if(s==null)return 0;if(ri(s))return Ff(s)?Ta(s):s.length;var o=Lr(s);return o==he||o==Ie?s.size:Au(s).length}function nw(s,o,l){var E=gt(s)?nu:Y6;return l&&Hr(s,o,l)&&(o=t),E(s,nt(o,3))}var sw=At(function(s,o){if(s==null)return[];var l=o.length;return l>1&&Hr(s,o[0],o[1])?o=[]:l>2&&Hr(o[0],o[1],o[2])&&(o=[o[0]]),$d(s,Mr(o,1),[])}),Nf=Um||function(){return Nt.Date.now()};function aw(s,o){if(typeof o!="function")throw new Oi(f);return s=yt(s),function(){if(--s<1)return o.apply(this,arguments)}}function Dp(s,o,l){return o=l?t:o,o=s&&o==null?s.length:o,Xn(s,x,t,t,t,t,o)}function Fp(s,o){var l;if(typeof o!="function")throw new Oi(f);return s=yt(s),function(){return--s>0&&(l=o.apply(this,arguments)),s<=1&&(o=t),l}}var Vu=At(function(s,o,l){var E=W;if(l.length){var C=_s(l,za(Vu));E|=k}return Xn(s,E,o,l,C)}),Bp=At(function(s,o,l){var E=W|Q;if(l.length){var C=_s(l,za(Bp));E|=k}return Xn(o,E,s,l,C)});function qp(s,o,l){o=l?t:o;var E=Xn(s,Y,t,t,t,t,t,o);return E.placeholder=qp.placeholder,E}function Lp(s,o,l){o=l?t:o;var E=Xn(s,U,t,t,t,t,t,o);return E.placeholder=Lp.placeholder,E}function Up(s,o,l){var E,C,L,J,X,ie,ue=0,de=!1,ge=!1,Pe=!0;if(typeof s!="function")throw new Oi(f);o=Di(o)||0,Zt(l)&&(de=!!l.leading,ge="maxWait"in l,L=ge?pr(Di(l.maxWait)||0,o):L,Pe="trailing"in l?!!l.trailing:Pe);function We(or){var nn=E,is=C;return E=C=t,ue=or,J=s.apply(is,nn),J}function ot(or){return ue=or,X=zo(xt,o),de?We(or):J}function wt(or){var nn=or-ie,is=or-ue,n1=o-nn;return ge?qr(n1,L-is):n1}function ct(or){var nn=or-ie,is=or-ue;return ie===t||nn>=o||nn<0||ge&&is>=L}function xt(){var or=Nf();if(ct(or))return Ct(or);X=zo(xt,wt(or))}function Ct(or){return X=t,Pe&&E?We(or):(E=C=t,J)}function mi(){X!==t&&Jd(X),ue=0,E=ie=C=X=t}function Kr(){return X===t?J:Ct(Nf())}function yi(){var or=Nf(),nn=ct(or);if(E=arguments,C=this,ie=or,nn){if(X===t)return ot(ie);if(ge)return Jd(X),X=zo(xt,o),We(ie)}return X===t&&(X=zo(xt,o)),J}return yi.cancel=mi,yi.flush=Kr,yi}var ow=At(function(s,o){return Pd(s,1,o)}),cw=At(function(s,o,l){return Pd(s,Di(o)||0,l)});function fw(s){return Xn(s,ae)}function Cf(s,o){if(typeof s!="function"||o!=null&&typeof o!="function")throw new Oi(f);var l=function(){var E=arguments,C=o?o.apply(this,E):E[0],L=l.cache;if(L.has(C))return L.get(C);var J=s.apply(this,E);return l.cache=L.set(C,J)||L,J};return l.cache=new(Cf.Cache||Yn),l}Cf.Cache=Yn;function Tf(s){if(typeof s!="function")throw new Oi(f);return function(){var o=arguments;switch(o.length){case 0:return!s.call(this);case 1:return!s.call(this,o[0]);case 2:return!s.call(this,o[0],o[1]);case 3:return!s.call(this,o[0],o[1],o[2])}return!s.apply(this,o)}}function hw(s){return Fp(2,s)}var uw=Q6(function(s,o){o=o.length==1&>(o[0])?Xt(o[0],gi(nt())):Xt(Mr(o,1),gi(nt()));var l=o.length;return At(function(E){for(var C=-1,L=qr(E.length,l);++C=o}),ta=Td(function(){return arguments}())?Td:function(s){return tr(s)&&Lt.call(s,"callee")&&!yd.call(s,"callee")},gt=oe.isArray,Iw=jr?gi(jr):D6;function ri(s){return s!=null&&Df(s.length)&&!ts(s)}function ar(s){return tr(s)&&ri(s)}function Mw(s){return s===!0||s===!1||tr(s)&&kr(s)==z}var Ms=zm||nl,Pw=Zi?gi(Zi):F6;function Ow(s){return tr(s)&&s.nodeType===1&&!jo(s)}function Rw(s){if(s==null)return!0;if(ri(s)&&(gt(s)||typeof s=="string"||typeof s.splice=="function"||Ms(s)||ja(s)||ta(s)))return!s.length;var o=Lr(s);if(o==he||o==Ie)return!s.size;if($o(s))return!Au(s).length;for(var l in s)if(Lt.call(s,l))return!1;return!0}function Nw(s,o){return qo(s,o)}function Cw(s,o,l){l=typeof l=="function"?l:t;var E=l?l(s,o):t;return E===t?qo(s,o,t,l):!!E}function Wu(s){if(!tr(s))return!1;var o=kr(s);return o==$||o==w||typeof s.message=="string"&&typeof s.name=="string"&&!jo(s)}function Tw(s){return typeof s=="number"&&_d(s)}function ts(s){if(!Zt(s))return!1;var o=kr(s);return o==ne||o==ce||o==q||o==Oe}function zp(s){return typeof s=="number"&&s==yt(s)}function Df(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=M}function Zt(s){var o=typeof s;return s!=null&&(o=="object"||o=="function")}function tr(s){return s!=null&&typeof s=="object"}var jp=Mi?gi(Mi):q6;function Dw(s,o){return s===o||_u(s,o,Lu(o))}function Fw(s,o,l){return l=typeof l=="function"?l:t,_u(s,o,Lu(o),l)}function Bw(s){return kp(s)&&s!=+s}function qw(s){if(wy(s))throw new dt(a);return Dd(s)}function Lw(s){return s===null}function Uw(s){return s==null}function kp(s){return typeof s=="number"||tr(s)&&kr(s)==ye}function jo(s){if(!tr(s)||kr(s)!=Ce)return!1;var o=of(s);if(o===null)return!0;var l=Lt.call(o,"constructor")&&o.constructor;return typeof l=="function"&&l instanceof l&&rf.call(l)==Fm}var Ju=mn?gi(mn):L6;function $w(s){return zp(s)&&s>=-M&&s<=M}var Hp=Mo?gi(Mo):U6;function Ff(s){return typeof s=="string"||!gt(s)&&tr(s)&&kr(s)==me}function bi(s){return typeof s=="symbol"||tr(s)&&kr(s)==Re}var ja=Gs?gi(Gs):$6;function zw(s){return s===t}function jw(s){return tr(s)&&Lr(s)==ve}function kw(s){return tr(s)&&kr(s)==Ne}var Hw=Sf(Eu),Kw=Sf(function(s,o){return s<=o});function Kp(s){if(!s)return[];if(ri(s))return Ff(s)?en(s):ti(s);if(Oo&&s[Oo])return Em(s[Oo]());var o=Lr(s),l=o==he?hu:o==Ie?Zc:ka;return l(s)}function rs(s){if(!s)return s===0?s:0;if(s=Di(s),s===I||s===-I){var o=s<0?-1:1;return o*S}return s===s?s:0}function yt(s){var o=rs(s),l=o%1;return o===o?l?o-l:o:0}function Vp(s){return s?Qs(yt(s),0,g):0}function Di(s){if(typeof s=="number")return s;if(bi(s))return d;if(Zt(s)){var o=typeof s.valueOf=="function"?s.valueOf():s;s=Zt(o)?o+"":o}if(typeof s!="string")return s===0?s:+s;s=ud(s);var l=Tr.test(s);return l||Fr.test(s)?pt(s.slice(2),l?2:8):Cr.test(s)?d:+s}function Gp(s){return wn(s,ii(s))}function Vw(s){return s?Qs(yt(s),-M,M):s===0?s:0}function Bt(s){return s==null?"":vi(s)}var Gw=Ua(function(s,o){if($o(o)||ri(o)){wn(o,mr(o),s);return}for(var l in o)Lt.call(o,l)&&Do(s,l,o[l])}),Wp=Ua(function(s,o){wn(o,ii(o),s)}),Bf=Ua(function(s,o,l,E){wn(o,ii(o),s,E)}),Ww=Ua(function(s,o,l,E){wn(o,mr(o),s,E)}),Jw=Zn(vu);function Yw(s,o){var l=La(s);return o==null?l:Id(l,o)}var Qw=At(function(s,o){s=Ht(s);var l=-1,E=o.length,C=E>2?o[2]:t;for(C&&Hr(o[0],o[1],C)&&(E=1);++l1),L}),wn(s,Bu(s),l),E&&(l=Ni(l,A|R|O,cy));for(var C=o.length;C--;)Pu(l,o[C]);return l});function g5(s,o){return Yp(s,Tf(nt(o)))}var v5=Zn(function(s,o){return s==null?{}:k6(s,o)});function Yp(s,o){if(s==null)return{};var l=Xt(Bu(s),function(E){return[E]});return o=nt(o),zd(s,l,function(E,C){return o(E,C[0])})}function b5(s,o,l){o=Ss(o,s);var E=-1,C=o.length;for(C||(C=1,s=t);++Eo){var E=s;s=o,o=E}if(l||s%1||o%1){var C=Ad();return qr(s+C*(o-s+jt("1e-"+((C+"").length-1))),o)}return Su(s,o)}var P5=$a(function(s,o,l){return o=o.toLowerCase(),s+(l?Zp(o):o)});function Zp(s){return Xu(Bt(s).toLowerCase())}function e1(s){return s=Bt(s),s&&s.replace(er,mm).replace(eu,"")}function O5(s,o,l){s=Bt(s),o=vi(o);var E=s.length;l=l===t?E:Qs(yt(l),0,E);var C=l;return l-=o.length,l>=0&&s.slice(l,C)==o}function R5(s){return s=Bt(s),s&&Xe.test(s)?s.replace(It,ym):s}function N5(s){return s=Bt(s),s&&ze.test(s)?s.replace(rt,"\\$&"):s}var C5=$a(function(s,o,l){return s+(l?"-":"")+o.toLowerCase()}),T5=$a(function(s,o,l){return s+(l?" ":"")+o.toLowerCase()}),D5=ip("toLowerCase");function F5(s,o,l){s=Bt(s),o=yt(o);var E=o?Ta(s):0;if(!o||E>=o)return s;var C=(o-E)/2;return xf(uf(C),l)+s+xf(hf(C),l)}function B5(s,o,l){s=Bt(s),o=yt(o);var E=o?Ta(s):0;return o&&E>>0,l?(s=Bt(s),s&&(typeof o=="string"||o!=null&&!Ju(o))&&(o=vi(o),!o&&Ca(s))?Is(en(s),0,l):s.split(o,l)):[]}var k5=$a(function(s,o,l){return s+(l?" ":"")+Xu(o)});function H5(s,o,l){return s=Bt(s),l=l==null?0:Qs(yt(l),0,s.length),o=vi(o),s.slice(l,l+o.length)==o}function K5(s,o,l){var E=D.templateSettings;l&&Hr(s,o,l)&&(o=t),s=Bt(s),o=Bf({},o,E,hp);var C=Bf({},o.imports,E.imports,hp),L=mr(C),J=fu(C,L),X,ie,ue=0,de=o.interpolate||Qr,ge="__p += '",Pe=uu((o.escape||Qr).source+"|"+de.source+"|"+(de===et?at:Qr).source+"|"+(o.evaluate||Qr).source+"|$","g"),We="//# sourceURL="+(Lt.call(o,"sourceURL")?(o.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++tu+"]")+` +`;s.replace(Pe,function(ct,xt,Ct,mi,Kr,yi){return Ct||(Ct=mi),ge+=s.slice(ue,yi).replace(Gi,wm),xt&&(X=!0,ge+=`' + +__e(`+xt+`) + +'`),Kr&&(ie=!0,ge+=`'; +`+Kr+`; +__p += '`),Ct&&(ge+=`' + +((__t = (`+Ct+`)) == null ? '' : __t) + +'`),ue=yi+ct.length,ct}),ge+=`'; +`;var ot=Lt.call(o,"variable")&&o.variable;if(!ot)ge=`with (obj) { +`+ge+` +} +`;else if(Tt.test(ot))throw new dt(u);ge=(ie?ge.replace(_t,""):ge).replace(lt,"$1").replace(Je,"$1;"),ge="function("+(ot||"obj")+`) { +`+(ot?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(X?", __e = _.escape":"")+(ie?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+ge+`return __p +}`;var wt=r1(function(){return Ft(L,We+"return "+ge).apply(t,J)});if(wt.source=ge,Wu(wt))throw wt;return wt}function V5(s){return Bt(s).toLowerCase()}function G5(s){return Bt(s).toUpperCase()}function W5(s,o,l){if(s=Bt(s),s&&(l||o===t))return ud(s);if(!s||!(o=vi(o)))return s;var E=en(s),C=en(o),L=ld(E,C),J=dd(E,C)+1;return Is(E,L,J).join("")}function J5(s,o,l){if(s=Bt(s),s&&(l||o===t))return s.slice(0,gd(s)+1);if(!s||!(o=vi(o)))return s;var E=en(s),C=dd(E,en(o))+1;return Is(E,0,C).join("")}function Y5(s,o,l){if(s=Bt(s),s&&(l||o===t))return s.replace(it,"");if(!s||!(o=vi(o)))return s;var E=en(s),C=ld(E,en(o));return Is(E,C).join("")}function Q5(s,o){var l=le,E=F;if(Zt(o)){var C="separator"in o?o.separator:C;l="length"in o?yt(o.length):l,E="omission"in o?vi(o.omission):E}s=Bt(s);var L=s.length;if(Ca(s)){var J=en(s);L=J.length}if(l>=L)return s;var X=l-Ta(E);if(X<1)return E;var ie=J?Is(J,0,X).join(""):s.slice(0,X);if(C===t)return ie+E;if(J&&(X+=ie.length-X),Ju(C)){if(s.slice(X).search(C)){var ue,de=ie;for(C.global||(C=uu(C.source,Bt(bt.exec(C))+"g")),C.lastIndex=0;ue=C.exec(de);)var ge=ue.index;ie=ie.slice(0,ge===t?X:ge)}}else if(s.indexOf(vi(C),X)!=X){var Pe=ie.lastIndexOf(C);Pe>-1&&(ie=ie.slice(0,Pe))}return ie+E}function X5(s){return s=Bt(s),s&&Fe.test(s)?s.replace(Et,Mm):s}var Z5=$a(function(s,o,l){return s+(l?" ":"")+o.toUpperCase()}),Xu=ip("toUpperCase");function t1(s,o,l){return s=Bt(s),o=l?t:o,o===t?Am(s)?Rm(s):dm(s):s.match(o)||[]}var r1=At(function(s,o){try{return br(s,t,o)}catch(l){return Wu(l)?l:new dt(l)}}),e4=Zn(function(s,o){return Pi(o,function(l){l=_n(l),Qn(s,l,Vu(s[l],s))}),s});function t4(s){var o=s==null?0:s.length,l=nt();return s=o?Xt(s,function(E){if(typeof E[1]!="function")throw new Oi(f);return[l(E[0]),E[1]]}):[],At(function(E){for(var C=-1;++CM)return[];var l=g,E=qr(s,g);o=nt(o),s-=g;for(var C=cu(E,o);++l0||o<0)?new Mt(l):(s<0?l=l.takeRight(-s):s&&(l=l.drop(s)),o!==t&&(o=yt(o),l=o<0?l.dropRight(-o):l.take(o-s)),l)},Mt.prototype.takeRightWhile=function(s){return this.reverse().takeWhile(s).reverse()},Mt.prototype.toArray=function(){return this.take(g)},yn(Mt.prototype,function(s,o){var l=/^(?:filter|find|map|reject)|While$/.test(o),E=/^(?:head|last)$/.test(o),C=D[E?"take"+(o=="last"?"Right":""):o],L=E||/^find/.test(o);C&&(D.prototype[o]=function(){var J=this.__wrapped__,X=E?[1]:arguments,ie=J instanceof Mt,ue=X[0],de=ie||gt(J),ge=function(xt){var Ct=C.apply(D,ws([xt],X));return E&&Pe?Ct[0]:Ct};de&&l&&typeof ue=="function"&&ue.length!=1&&(ie=de=!1);var Pe=this.__chain__,We=!!this.__actions__.length,ot=L&&!Pe,wt=ie&&!We;if(!L&&de){J=wt?J:new Mt(this);var ct=s.apply(J,X);return ct.__actions__.push({func:Of,args:[ge],thisArg:t}),new Ri(ct,Pe)}return ot&&wt?s.apply(this,X):(ct=this.thru(ge),ot?E?ct.value()[0]:ct.value():ct)})}),Pi(["pop","push","shift","sort","splice","unshift"],function(s){var o=ef[s],l=/^(?:push|sort|unshift)$/.test(s)?"tap":"thru",E=/^(?:pop|shift)$/.test(s);D.prototype[s]=function(){var C=arguments;if(E&&!this.__chain__){var L=this.value();return o.apply(gt(L)?L:[],C)}return this[l](function(J){return o.apply(gt(J)?J:[],C)})}}),yn(Mt.prototype,function(s,o){var l=D[o];if(l){var E=l.name+"";Lt.call(qa,E)||(qa[E]=[]),qa[E].push({name:o,func:l})}}),qa[Af(t,Q).name]=[{name:"wrapper",func:t}],Mt.prototype.clone=Xm,Mt.prototype.reverse=Zm,Mt.prototype.value=e6,D.prototype.at=O3,D.prototype.chain=R3,D.prototype.commit=N3,D.prototype.next=C3,D.prototype.plant=D3,D.prototype.reverse=F3,D.prototype.toJSON=D.prototype.valueOf=D.prototype.value=B3,D.prototype.first=D.prototype.head,Oo&&(D.prototype[Oo]=T3),D},Da=Nm();sr?((sr.exports=Da)._=Da,kt._=Da):Nt._=Da}).call(rc)})(A0,A0.exports);var tC=Object.defineProperty,rC=Object.defineProperties,iC=Object.getOwnPropertyDescriptors,_v=Object.getOwnPropertySymbols,nC=Object.prototype.hasOwnProperty,sC=Object.prototype.propertyIsEnumerable,Av=(r,e,t)=>e in r?tC(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Gf=(r,e)=>{for(var t in e||(e={}))nC.call(e,t)&&Av(r,t,e[t]);if(_v)for(var t of _v(e))sC.call(e,t)&&Av(r,t,e[t]);return r},aC=(r,e)=>rC(r,iC(e));function pn(r,e,t){var i;const n=ac(r);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${sm}?chainId=${n.namespace}:${n.reference}&projectId=${t}`}function Ia(r){return r.includes(":")?r.split(":")[1]:r}function am(r){return r.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function oC(r,e){const t=Object.keys(e.namespaces).filter(n=>n.includes(r));if(!t.length)return[];const i=[];return t.forEach(n=>{const a=e.namespaces[n].accounts;i.push(...a)}),i}function zl(r={},e={}){const t=Ev(r),i=Ev(e);return A0.exports.merge(t,i)}function Ev(r){var e,t,i,n;const a={};if(!bc(r))return a;for(const[f,u]of Object.entries(r)){const b=J0(f)?[f]:u.chains,p=u.methods||[],y=u.events||[],A=u.rpcMap||{},R=sc(f);a[R]=aC(Gf(Gf({},a[R]),u),{chains:Qf(b,(e=a[R])==null?void 0:e.chains),methods:Qf(p,(t=a[R])==null?void 0:t.methods),events:Qf(y,(i=a[R])==null?void 0:i.events),rpcMap:Gf(Gf({},A),(n=a[R])==null?void 0:n.rpcMap)})}return a}function cC(r){return r.includes(":")?r.split(":")[2]:r}function xv(r){const e={};for(const[t,i]of Object.entries(r)){const n=i.methods||[],a=i.events||[],f=i.accounts||[],u=J0(t)?[t]:i.chains?i.chains:am(i.accounts);e[t]={chains:u,methods:n,events:a,accounts:f}}return e}function jl(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const om={},qt=r=>om[r],kl=(r,e)=>{om[r]=e};class fC{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=Ia(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||pn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new gn(new Gn(i,qt("disableProviderPing")))}}var hC=Object.defineProperty,uC=Object.defineProperties,lC=Object.getOwnPropertyDescriptors,Sv=Object.getOwnPropertySymbols,dC=Object.prototype.hasOwnProperty,pC=Object.prototype.propertyIsEnumerable,Iv=(r,e,t)=>e in r?hC(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Mv=(r,e)=>{for(var t in e||(e={}))dC.call(e,t)&&Iv(r,t,e[t]);if(Sv)for(var t of Sv(e))pC.call(e,t)&&Iv(r,t,e[t]);return r},Pv=(r,e)=>uC(r,lC(e));class gC{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||pn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new gn(new Gn(i,qt("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=parseInt(Ia(t));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let n=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const a=parseInt(n,16);if(this.isChainApproved(a))this.setDefaultChain(`${a}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${a}`);else throw new Error(`Failed to switch to chain 'eip155:${a}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,n;const a=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const f=this.client.session.get(e.topic),u=((n=f==null?void 0:f.sessionProperties)==null?void 0:n.capabilities)||{};if(u!=null&&u[a])return u==null?void 0:u[a];const b=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Pv(Mv({},f.sessionProperties||{}),{capabilities:Pv(Mv({},u||{}),{[a]:b})})})}catch(p){console.warn("Failed to update session with capabilities",p)}return b}async getCallStatus(e){var t,i;const n=this.client.session.get(e.topic),a=(t=n.sessionProperties)==null?void 0:t.bundler_name;if(a){const u=this.getBundlerUrl(e.chainId,a);try{return await this.getUserOperationReceipt(u,e)}catch(b){console.warn("Failed to fetch call status from bundler",b,u)}}const f=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(f)try{return await this.getUserOperationReceipt(f,e)}catch(u){console.warn("Failed to fetch call status from custom bundler",u,f)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const n=new URL(e),a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(qs("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!a.ok)throw new Error(`Failed to fetch user operation receipt - ${a.status}`);return await a.json()}getBundlerUrl(e,t){return`${eC}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}class vC{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=Ia(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||pn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new gn(new Gn(i,qt("disableProviderPing")))}}class bC{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=Ia(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||pn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new gn(new Gn(i,qt("disableProviderPing")))}}class mC{constructor(e){this.name="algorand",this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||pn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||pn(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new gn(new Gn(i,qt("disableProviderPing")))}}class yC{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),n=Ia(t);e[n]=this.createHttpProvider(n,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new gn(new Gn(i,qt("disableProviderPing")))}}class wC{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=Ia(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||pn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new gn(new Gn(i,qt("disableProviderPing")))}}class _C{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=Ia(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||pn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new gn(new Gn(i,qt("disableProviderPing")))}}class AC{constructor(e){this.name="near",this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||pn(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||pn(e,this.namespace);return typeof i>"u"?void 0:new gn(new Gn(i,qt("disableProviderPing")))}}class EC{constructor(e){this.name=Ya,this.namespace=e.namespace,this.events=qt("events"),this.client=qt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(n=>{const a=ac(n);i[`${a.namespace}:${a.reference}`]=this.createHttpProvider(n)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||pn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new gn(new Gn(i,qt("disableProviderPing")))}}var xC=Object.defineProperty,SC=Object.defineProperties,IC=Object.getOwnPropertyDescriptors,Ov=Object.getOwnPropertySymbols,MC=Object.prototype.hasOwnProperty,PC=Object.prototype.propertyIsEnumerable,Rv=(r,e,t)=>e in r?xC(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Wf=(r,e)=>{for(var t in e||(e={}))MC.call(e,t)&&Rv(r,t,e[t]);if(Ov)for(var t of Ov(e))PC.call(e,t)&&Rv(r,t,e[t]);return r},Hl=(r,e)=>SC(r,IC(e));class nd{constructor(e){this.events=new I0,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Nc(Hh({level:(e==null?void 0:e.logger)||yv})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new nd(e);return await t.initialize(),t}async request(e,t,i){const[n,a]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:Wf({},e),chainId:`${n}:${a}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,n){const a=new Date().getTime();this.request(e,i,n).then(f=>t(null,Kh(a,f))).catch(f=>t(f,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Ut("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const a=await n();if(this.session=a.session,this.session){const f=xv(this.session.namespaces);this.namespaces=zl(this.namespaces,f),this.persist("namespaces",this.namespaces),this.onConnect()}return a}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let t=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(t>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:i,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});i&&(this.uri=i,this.events.emit("display_uri",i)),await n().then(a=>{this.session=a;const f=xv(a.namespaces);this.namespaces=zl(this.namespaces,f),this.persist("namespaces",this.namespaces)}).catch(a=>{if(a.message!==nm)throw a;t++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,n]=this.validateChain(e),a=this.getProvider(i);a.name===Ya?a.setDefaultChain(`${i}:${n}`,t):a.setDefaultChain(n,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(jn(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await id.init({core:this.providerOpts.core,logger:this.providerOpts.logger||yv,relayUrl:this.providerOpts.relayUrl||QN,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>sc(t)))];kl("client",this.client),kl("events",this.events),kl("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=oC(t,this.session),n=am(i),a=zl(this.namespaces,this.optionalNamespaces),f=Hl(Wf({},a[t]),{accounts:i,chains:n});switch(t){case"eip155":this.rpcProviders[t]=new gC({namespace:f});break;case"algorand":this.rpcProviders[t]=new mC({namespace:f});break;case"solana":this.rpcProviders[t]=new vC({namespace:f});break;case"cosmos":this.rpcProviders[t]=new bC({namespace:f});break;case"polkadot":this.rpcProviders[t]=new fC({namespace:f});break;case"cip34":this.rpcProviders[t]=new yC({namespace:f});break;case"elrond":this.rpcProviders[t]=new wC({namespace:f});break;case"multiversx":this.rpcProviders[t]=new _C({namespace:f});break;case"near":this.rpcProviders[t]=new AC({namespace:f});break;default:this.rpcProviders[Ya]?this.rpcProviders[Ya].updateNamespace(f):this.rpcProviders[Ya]=new EC({namespace:f})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:t}=e,{event:i}=t;if(i.name==="accountsChanged"){const n=i.data;n&&jn(n)&&this.events.emit("accountsChanged",n.map(cC))}else if(i.name==="chainChanged"){const n=t.chainId,a=t.event.data,f=sc(n),u=jl(n)!==jl(a)?`${f}:${jl(a)}`:n;this.onChainChanged(u)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i;const{namespaces:n}=t,a=(i=this.client)==null?void 0:i.session.get(e);this.session=Hl(Wf({},a),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Hl(Wf({},Ut("USER_DISCONNECTED")),{data:e.topic}))}),this.on(vn.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Ya]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:n}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=n,this.persist("namespaces",t),this.persist("optionalNamespaces",i)}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(f=>sc(f)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const n=sc(Object.keys(this.namespaces)[0]),a=this.rpcProviders[n].getDefaultChain();return[n,a]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,n]=this.validateChain(e);n&&(t||this.getProvider(i).setDefaultChain(n),this.namespaces[i]?this.namespaces[i].defaultChain=n:this.namespaces[`${i}:${n}`]?this.namespaces[`${i}:${n}`].defaultChain=n:this.namespaces[`${i}:${n}`]={defaultChain:n},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",n))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,t){this.client.core.storage.setItem(`${wv}/${e}`,t)}async getFromStore(e){return await this.client.core.storage.getItem(`${wv}/${e}`)}}const OC=nd,RC="wc",NC="ethereum_provider",CC=`${RC}@2:${NC}:`,TC="https://rpc.walletconnect.org/v1/",E0=["eth_sendTransaction","personal_sign"],DC=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],x0=["chainChanged","accountsChanged"],FC=["chainChanged","accountsChanged","message","disconnect","connect"];var BC=Object.defineProperty,qC=Object.defineProperties,LC=Object.getOwnPropertyDescriptors,Nv=Object.getOwnPropertySymbols,UC=Object.prototype.hasOwnProperty,$C=Object.prototype.propertyIsEnumerable,Cv=(r,e,t)=>e in r?BC(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Qa=(r,e)=>{for(var t in e||(e={}))UC.call(e,t)&&Cv(r,t,e[t]);if(Nv)for(var t of Nv(e))$C.call(e,t)&&Cv(r,t,e[t]);return r},Kl=(r,e)=>qC(r,LC(e));function Eh(r){return Number(r[0].split(":")[1])}function Jf(r){return`0x${r.toString(16)}`}function zC(r){const{chains:e,optionalChains:t,methods:i,optionalMethods:n,events:a,optionalEvents:f,rpcMap:u}=r;if(!jn(e))throw new Error("Invalid chains");const b={chains:e,methods:i||E0,events:a||x0,rpcMap:Qa({},e.length?{[Eh(e)]:u[Eh(e)]}:{})},p=a==null?void 0:a.filter(O=>!x0.includes(O)),y=i==null?void 0:i.filter(O=>!E0.includes(O));if(!t&&!f&&!n&&!(p!=null&&p.length)&&!(y!=null&&y.length))return{required:e.length?b:void 0};const A=(p==null?void 0:p.length)&&(y==null?void 0:y.length)||!t,R={chains:[...new Set(A?b.chains.concat(t||[]):t)],methods:[...new Set(b.methods.concat(n!=null&&n.length?n:DC))],events:[...new Set(b.events.concat(f!=null&&f.length?f:FC))],rpcMap:u};return{required:e.length?b:void 0,optional:t.length?R:void 0}}class sd{constructor(){this.events=new Hi.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=CC,this.on=(e,t)=>(this.events.on(e,t),this),this.once=(e,t)=>(this.events.once(e,t),this),this.removeListener=(e,t)=>(this.events.removeListener(e,t),this),this.off=(e,t)=>(this.events.off(e,t),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const t=new sd;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:t,optional:i}=zC(this.rpc);try{const n=await new Promise(async(f,u)=>{var b;this.rpc.showQrModal&&((b=this.modal)==null||b.subscribeModal(p=>{!p.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),u(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(Kl(Qa({namespaces:Qa({},t&&{[this.namespace]:t})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e==null?void 0:e.pairingTopic})).then(p=>{f(p)}).catch(p=>{u(new Error(p.message))})});if(!n)return;const a=T1(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:a),this.setAccounts(a),this.events.emit("connect",{chainId:Jf(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async authenticate(e,t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const i=await new Promise(async(a,f)=>{var u;this.rpc.showQrModal&&((u=this.modal)==null||u.subscribeModal(b=>{!b.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),f(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Kl(Qa({},e),{chains:this.rpc.chains}),t).then(b=>{a(b)}).catch(b=>{f(new Error(b.message))})}),n=i.session;if(n){const a=T1(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:a),this.setAccounts(a),this.events.emit("connect",{chainId:Jf(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:i}=t;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",Jf(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",Kl(Qa({},Ut("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var t,i;this.rpc.showQrModal&&((t=this.modal)==null||t.closeModal(),(i=this.modal)==null||i.openModal({uri:e})),this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",Jf(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,n]=e.split(":");return{chainId:`${t}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,i;const n=(t=e==null?void 0:e.chains)!=null?t:[],a=(i=e==null?void 0:e.optionalChains)!=null?i:[],f=n.concat(a);if(!f.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const u=n.length?(e==null?void 0:e.methods)||E0:[],b=n.length?(e==null?void 0:e.events)||x0:[],p=(e==null?void 0:e.optionalMethods)||[],y=(e==null?void 0:e.optionalEvents)||[],A=(e==null?void 0:e.rpcMap)||this.buildRpcMap(f,e.projectId),R=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:n==null?void 0:n.map(O=>this.formatChainId(O)),optionalChains:a.map(O=>this.formatChainId(O)),methods:u,events:b,optionalMethods:p,optionalEvents:y,rpcMap:A,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:R,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,t)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Eh(this.rpc.chains):Eh(this.rpc.optionalChains),this.signer=await OC.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const{WalletConnectModal:i}=await j4(()=>import("./index-DY1ObU95.js").then(n=>n.i),__vite__mapDeps([0,1,2]));t=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(t)try{this.modal=new t(Qa({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:n}=e;t&&jn(t)&&(this.rpc.chains=t.map(a=>this.formatChainId(a)),t.forEach(a=>{this.rpc.rpcMap[a]=(n==null?void 0:n[a])||this.getRpcUrl(a)})),i&&jn(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(a=>this.formatChainId(a)),i.forEach(a=>{this.rpc.rpcMap[a]=(n==null?void 0:n[a])||this.getRpcUrl(a)}))}getRpcUrl(e,t){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${TC}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t==null?void 0:t.accounts),this.setAccounts(t==null?void 0:t.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const dT=sd;export{dT as EthereumProvider,FC as OPTIONAL_EVENTS,DC as OPTIONAL_METHODS,x0 as REQUIRED_EVENTS,E0 as REQUIRED_METHODS,sd as default}; diff --git a/buddybook/assets/inherits_browser-BwZ6FBWK.js b/buddybook/assets/inherits_browser-BwZ6FBWK.js new file mode 100644 index 0000000..6ff2c01 --- /dev/null +++ b/buddybook/assets/inherits_browser-BwZ6FBWK.js @@ -0,0 +1 @@ +import{g as n,u as s}from"./index-B-6Lwopd.js";const a=n(s);var r={exports:{}};typeof Object.create=="function"?r.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:r.exports=function(e,t){if(t){e.super_=t;var o=function(){};o.prototype=t.prototype,e.prototype=new o,e.prototype.constructor=e}};var u=r.exports;export{u as i,a as r}; diff --git a/buddybook/index.html b/buddybook/index.html new file mode 100644 index 0000000..53a323a --- /dev/null +++ b/buddybook/index.html @@ -0,0 +1,14 @@ + + + + + + + BuddyBook Dogfood + + + + +
+ + diff --git a/buddybook/vite.svg b/buddybook/vite.svg new file mode 100644 index 0000000..e7b8dfb --- /dev/null +++ b/buddybook/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/experimental/relay-direct-rtc/index.js b/experimental/relay-direct-rtc/index.js index a036a7d..5c49b29 100644 --- a/experimental/relay-direct-rtc/index.js +++ b/experimental/relay-direct-rtc/index.js @@ -16,7 +16,7 @@ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _waku_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/sdk */ \"./node_modules/@waku/sdk/dist/index.js\");\n/* harmony import */ var _libp2p_websockets__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/websockets */ \"./node_modules/@libp2p/websockets/dist/src/index.js\");\n/* harmony import */ var _libp2p_websockets_filters__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/websockets/filters */ \"./node_modules/@libp2p/websockets/dist/src/filters.js\");\n/* harmony import */ var _libp2p_webrtc__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/webrtc */ \"./node_modules/@libp2p/webrtc/dist/src/index.js\");\n/* harmony import */ var libp2p_circuit_relay__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! libp2p/circuit-relay */ \"./node_modules/libp2p/dist/src/circuit-relay/index.js\");\n\n\n\n\n\n\n\n\nconst CONTENT_TOPIC = \"/toy-chat/2/huilong/proto\";\n\nconst ui = initUI();\nrunApp(ui).catch((err) => {\n console.error(err);\n ui.setStatus(`error: ${err.message}`, \"error\");\n});\n\nasync function runApp(ui) {\n const {\n info,\n sendMessage,\n unsubscribeFromMessages,\n dial,\n dialWebRTCpeer,\n dropNetworkConnections,\n ensureWebRTCconnectionInRelayMesh,\n } = await initWakuContext({\n ui,\n contentTopic: CONTENT_TOPIC,\n });\n\n ui.setLocalPeer(info.localPeerId);\n ui.setContentTopic(info.contentTopic);\n\n ui.onSendMessage(sendMessage);\n ui.onRemoteNodeConnect(dial);\n ui.onWebrtcConnect(dialWebRTCpeer);\n ui.onRelayWebRTC(ensureWebRTCconnectionInRelayMesh);\n ui.onDropNonWebRTC(dropNetworkConnections);\n\n ui.onExit(async () => {\n ui.setStatus(\"disconnecting...\", \"progress\");\n await unsubscribeFromMessages();\n ui.setStatus(\"disconnected\", \"terminated\");\n ui.resetMessages();\n });\n}\n\nasync function initWakuContext({ ui, contentTopic }) {\n const Decoder = (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.createDecoder)(contentTopic);\n const Encoder = (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.createEncoder)({ contentTopic });\n\n const ChatMessage = new protobuf.Type(\"ChatMessage\")\n .add(new protobuf.Field(\"timestamp\", 1, \"uint64\"))\n .add(new protobuf.Field(\"nick\", 2, \"string\"))\n .add(new protobuf.Field(\"text\", 3, \"bytes\"));\n\n ui.setStatus(\"starting...\", \"progress\");\n\n const node = await (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.createRelayNode)({\n libp2p: {\n addresses: {\n listen: [\"/webrtc\"],\n },\n connectionGater: {\n denyDialMultiaddr: () => {\n // refuse to deny localhost addresses\n return false;\n },\n },\n transports: [\n (0,_libp2p_webrtc__WEBPACK_IMPORTED_MODULE_3__.webRTC)({}),\n (0,libp2p_circuit_relay__WEBPACK_IMPORTED_MODULE_4__.circuitRelayTransport)({\n discoverRelays: 1,\n }),\n (0,_libp2p_websockets__WEBPACK_IMPORTED_MODULE_1__.webSockets)({ filter: _libp2p_websockets_filters__WEBPACK_IMPORTED_MODULE_2__.all }),\n ],\n },\n });\n\n await node.start();\n\n // Set a filter by using Decoder for a given ContentTopic\n const unsubscribeFromMessages = await node.relay.subscribe(\n [Decoder],\n (wakuMessage) => {\n const messageObj = ChatMessage.decode(wakuMessage.payload);\n ui.renderMessage({\n ...messageObj,\n text: (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.bytesToUtf8)(messageObj.text),\n });\n }\n );\n\n ui.setStatus(\"started\", \"success\");\n\n const localPeerId = node.libp2p.peerId.toString();\n\n const remotePeers = await node.libp2p.peerStore.all();\n const remotePeerIds = new Set(remotePeers.map((peer) => peer.id.toString()));\n\n ui.setRemotePeer(Array.from(remotePeerIds.keys()));\n\n node.libp2p.addEventListener(\"peer:connect\", async (event) => {\n remotePeerIds.add(event.detail.toString());\n ui.setRemotePeer(Array.from(remotePeerIds.keys()));\n ui.setRelayMeshInfo(node.relay.gossipSub);\n });\n\n node.libp2p.addEventListener(\"peer:disconnect\", (event) => {\n remotePeerIds.delete(event.detail.toString());\n ui.setRemotePeer(Array.from(remotePeerIds.keys()));\n ui.setRelayMeshInfo(node.relay.gossipSub);\n });\n\n node.libp2p.addEventListener(\"peer:identify\", (event) => {\n const peer = event.detail;\n\n if (!peer.protocols.includes(\"/webrtc-signaling/0.0.1\")) {\n return;\n }\n\n ui.setWebrtcPeer(peer.peerId.toString());\n ui.setRelayMeshInfo(node.relay.gossipSub);\n });\n\n window.node = node;\n\n return {\n unsubscribeFromMessages,\n info: {\n contentTopic,\n localPeerId,\n },\n sendMessage: async ({ text, nick }) => {\n if (!text || !nick) {\n return;\n }\n\n const protoMessage = ChatMessage.create({\n nick,\n timestamp: Date.now(),\n text: (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)(text),\n });\n\n await node.relay.send(Encoder, {\n payload: ChatMessage.encode(protoMessage).finish(),\n });\n },\n dial: async (multiaddr) => {\n ui.setStatus(\"connecting...\", \"progress\");\n await node.dial(multiaddr);\n ui.setStatus(\"connected\", \"success\");\n },\n dialWebRTCpeer: async (peerId) => {\n const peers = await node.libp2p.peerStore.all();\n const circuitPeer = peers.filter(\n (p) =>\n p.protocols.includes(\"/libp2p/circuit/relay/0.2.0/hop\") &&\n p.protocols.includes(\"/libp2p/circuit/relay/0.2.0/stop\")\n )[0];\n\n if (!circuitPeer) {\n throw Error(\"No Circuit peer is found\");\n }\n\n let multiaddr = circuitPeer.addresses.pop().multiaddr;\n multiaddr = `${multiaddr}/p2p/${circuitPeer.id.toString()}/p2p-circuit/webrtc/p2p/${peerId}`;\n\n await node.dial(multiaddr);\n ui.setRelayMeshInfo(node.relay.gossipSub);\n },\n ensureWebRTCconnectionInRelayMesh: async () => {\n const promises = node.libp2p\n .getConnections()\n .filter((c) => c.stat.multiplexer === \"/webrtc\")\n .map(async (c) => {\n const outboundStream = node.relay.gossipSub.streamsOutbound.get(\n c.remotePeer.toString()\n );\n const isWebRTCOutbound =\n outboundStream.rawStream.constructor.name === \"WebRTCStream\";\n\n if (isWebRTCOutbound) {\n return;\n }\n\n node.relay.gossipSub.streamsOutbound.delete(c.remotePeer.toString());\n await node.relay.gossipSub.createOutboundStream(\n c.remotePeer.toString(),\n c\n );\n });\n await Promise.all(promises);\n ui.setRelayMeshInfo(node.relay.gossipSub);\n },\n dropNetworkConnections: async () => {\n const promises = node.libp2p\n .getConnections()\n .filter((c) => c.stat.multiplexer !== \"/webrtc\")\n .map(async (c) => {\n const peerId = c.remotePeer.toString();\n\n node.relay.gossipSub.peers.delete(peerId);\n node.relay.gossipSub.streamsInbound.delete(peerId);\n node.relay.gossipSub.streamsOutbound.delete(peerId);\n\n await node.libp2p.peerStore.delete(c.remotePeer);\n await c.close();\n });\n await Promise.all(promises);\n ui.setRelayMeshInfo(node.relay.gossipSub);\n },\n };\n}\n\n// UI adapter\nfunction initUI() {\n const exitButton = document.getElementById(\"exit\");\n const sendButton = document.getElementById(\"send\");\n\n const statusBlock = document.getElementById(\"status\");\n const localPeerBlock = document.getElementById(\"localPeerId\");\n const remotePeerId = document.getElementById(\"remotePeerId\");\n const contentTopicBlock = document.getElementById(\"contentTopic\");\n\n const messagesBlock = document.getElementById(\"messages\");\n\n const nickText = document.getElementById(\"nickText\");\n const messageText = document.getElementById(\"messageText\");\n\n const remoteNode = document.getElementById(\"remoteNode\");\n const connectRemoteNode = document.getElementById(\"connectRemoteNode\");\n\n const webrtcPeer = document.getElementById(\"webrtcPeer\");\n const connectWebrtcPeer = document.getElementById(\"connectWebrtcPeer\");\n\n const relayWebRTCbutton = document.getElementById(\"relayWebRTC\");\n const dropNonWebRTCbutton = document.getElementById(\"dropNonWebRTC\");\n\n const relayMeshInfo = document.getElementById(\"relayMeshInfo\");\n\n return {\n // UI events\n onExit: (cb) => {\n exitButton.addEventListener(\"click\", cb);\n },\n onSendMessage: (cb) => {\n sendButton.addEventListener(\"click\", async () => {\n await cb({\n nick: nickText.value,\n text: messageText.value,\n });\n messageText.value = \"\";\n });\n },\n // UI renderers\n setStatus: (value, className) => {\n statusBlock.innerHTML = `${value}`;\n },\n setLocalPeer: (id) => {\n localPeerBlock.innerText = id.toString();\n },\n setRemotePeer: (ids) => {\n remotePeerId.innerText = ids.join(\"\\n\");\n },\n setContentTopic: (topic) => {\n contentTopicBlock.innerText = topic.toString();\n },\n renderMessage: (messageObj) => {\n const { nick, text, timestamp } = messageObj;\n const date = new Date(timestamp);\n\n // WARNING: XSS vulnerable\n messagesBlock.innerHTML += `\n
\n

${nick} (${date.toDateString()}):

\n

${text}

\n
\n `;\n },\n resetMessages: () => {\n messagesBlock.innerHTML = \"\";\n },\n setWebrtcPeer: (peerId) => {\n webrtcPeer.value = peerId;\n },\n onRemoteNodeConnect: (cb) => {\n connectRemoteNode.addEventListener(\"click\", () => {\n const multiaddr = remoteNode.value;\n\n if (!multiaddr) {\n throw Error(\"No multiaddr set to dial\");\n }\n\n cb(multiaddr);\n });\n },\n onWebrtcConnect: (cb) => {\n connectWebrtcPeer.addEventListener(\"click\", () => {\n const multiaddr = webrtcPeer.value;\n\n if (!multiaddr) {\n throw Error(\"No multiaddr to dial webrtc\");\n }\n\n cb(multiaddr);\n });\n },\n onRelayWebRTC: (cb) => {\n relayWebRTCbutton.addEventListener(\"click\", cb);\n },\n onDropNonWebRTC: (cb) => {\n dropNonWebRTCbutton.addEventListener(\"click\", cb);\n },\n setRelayMeshInfo: (gossipSub) => {\n relayMeshInfo.innerHTML = \"\";\n\n Array.from(gossipSub.peers)\n .map((peerId) => {\n let inbound = gossipSub.streamsInbound.get(peerId);\n inbound = inbound ? inbound.rawStream.constructor.name : \"none\";\n\n let outbound = gossipSub.streamsOutbound.get(peerId);\n outbound = outbound ? outbound.rawStream.constructor.name : \"none\";\n\n return [peerId, inbound, outbound];\n })\n .map(([peerId, inbound, outbound]) => {\n relayMeshInfo.innerHTML += `${peerId}
inbound: ${inbound}\\toutbound: ${outbound}`;\n relayMeshInfo.innerHTML += \"

\";\n });\n },\n };\n}\n\n\n//# sourceURL=webpack://light/./index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _waku_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/sdk */ \"./node_modules/@waku/sdk/dist/index.js\");\n/* harmony import */ var _libp2p_websockets__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/websockets */ \"./node_modules/@libp2p/websockets/dist/src/index.js\");\n/* harmony import */ var _libp2p_websockets_filters__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/websockets/filters */ \"./node_modules/@libp2p/websockets/dist/src/filters.js\");\n/* harmony import */ var _libp2p_webrtc__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/webrtc */ \"./node_modules/@libp2p/webrtc/dist/src/index.js\");\n/* harmony import */ var libp2p_circuit_relay__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! libp2p/circuit-relay */ \"./node_modules/libp2p/dist/src/circuit-relay/index.js\");\n\n\n\n\n\n\n\n\nconst CONTENT_TOPIC = \"/toy-chat/2/huilong/proto\";\n\nconst ui = initUI();\nrunApp(ui).catch((err) => {\n console.error(err);\n ui.setStatus(`error: ${err.message}`, \"error\");\n});\n\nasync function runApp(ui) {\n const {\n info,\n sendMessage,\n unsubscribeFromMessages,\n dial,\n dialWebRTCpeer,\n dropNetworkConnections,\n ensureWebRTCconnectionInRelayMesh,\n } = await initWakuContext({\n ui,\n contentTopic: CONTENT_TOPIC,\n });\n\n ui.setLocalPeer(info.localPeerId);\n ui.setContentTopic(info.contentTopic);\n\n ui.onSendMessage(sendMessage);\n ui.onRemoteNodeConnect(dial);\n ui.onWebrtcConnect(dialWebRTCpeer);\n ui.onRelayWebRTC(ensureWebRTCconnectionInRelayMesh);\n ui.onDropNonWebRTC(dropNetworkConnections);\n\n ui.onExit(async () => {\n ui.setStatus(\"disconnecting...\", \"progress\");\n await unsubscribeFromMessages();\n ui.setStatus(\"disconnected\", \"terminated\");\n ui.resetMessages();\n });\n}\n\nasync function initWakuContext({ ui, contentTopic }) {\n const Decoder = (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.createDecoder)(contentTopic);\n const Encoder = (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.createEncoder)({ contentTopic });\n\n const ChatMessage = new protobuf.Type(\"ChatMessage\")\n .add(new protobuf.Field(\"timestamp\", 1, \"uint64\"))\n .add(new protobuf.Field(\"nick\", 2, \"string\"))\n .add(new protobuf.Field(\"text\", 3, \"bytes\"));\n\n ui.setStatus(\"starting...\", \"progress\");\n\n const node = await (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.createNode)({\n libp2p: {\n addresses: {\n listen: [\"/webrtc\"],\n },\n connectionGater: {\n denyDialMultiaddr: () => {\n // refuse to deny localhost addresses\n return false;\n },\n },\n transports: [\n (0,_libp2p_webrtc__WEBPACK_IMPORTED_MODULE_3__.webRTC)({}),\n (0,libp2p_circuit_relay__WEBPACK_IMPORTED_MODULE_4__.circuitRelayTransport)({\n discoverRelays: 1,\n }),\n (0,_libp2p_websockets__WEBPACK_IMPORTED_MODULE_1__.webSockets)({ filter: _libp2p_websockets_filters__WEBPACK_IMPORTED_MODULE_2__.all }),\n ],\n },\n });\n\n await node.start();\n\n // Set a filter by using Decoder for a given ContentTopic\n const unsubscribeFromMessages = await node.relay.subscribe(\n [Decoder],\n (wakuMessage) => {\n const messageObj = ChatMessage.decode(wakuMessage.payload);\n ui.renderMessage({\n ...messageObj,\n text: (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.bytesToUtf8)(messageObj.text),\n });\n }\n );\n\n ui.setStatus(\"started\", \"success\");\n\n const localPeerId = node.libp2p.peerId.toString();\n\n const remotePeers = await node.libp2p.peerStore.all();\n const remotePeerIds = new Set(remotePeers.map((peer) => peer.id.toString()));\n\n ui.setRemotePeer(Array.from(remotePeerIds.keys()));\n\n node.libp2p.addEventListener(\"peer:connect\", async (event) => {\n remotePeerIds.add(event.detail.toString());\n ui.setRemotePeer(Array.from(remotePeerIds.keys()));\n ui.setRelayMeshInfo(node.relay.gossipSub);\n });\n\n node.libp2p.addEventListener(\"peer:disconnect\", (event) => {\n remotePeerIds.delete(event.detail.toString());\n ui.setRemotePeer(Array.from(remotePeerIds.keys()));\n ui.setRelayMeshInfo(node.relay.gossipSub);\n });\n\n node.libp2p.addEventListener(\"peer:identify\", (event) => {\n const peer = event.detail;\n\n if (!peer.protocols.includes(\"/webrtc-signaling/0.0.1\")) {\n return;\n }\n\n ui.setWebrtcPeer(peer.peerId.toString());\n ui.setRelayMeshInfo(node.relay.gossipSub);\n });\n\n window.node = node;\n\n return {\n unsubscribeFromMessages,\n info: {\n contentTopic,\n localPeerId,\n },\n sendMessage: async ({ text, nick }) => {\n if (!text || !nick) {\n return;\n }\n\n const protoMessage = ChatMessage.create({\n nick,\n timestamp: Date.now(),\n text: (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)(text),\n });\n\n await node.relay.send(Encoder, {\n payload: ChatMessage.encode(protoMessage).finish(),\n });\n },\n dial: async (multiaddr) => {\n ui.setStatus(\"connecting...\", \"progress\");\n await node.dial(multiaddr);\n ui.setStatus(\"connected\", \"success\");\n },\n dialWebRTCpeer: async (peerId) => {\n const peers = await node.libp2p.peerStore.all();\n const circuitPeer = peers.filter(\n (p) =>\n p.protocols.includes(\"/libp2p/circuit/relay/0.2.0/hop\") &&\n p.protocols.includes(\"/libp2p/circuit/relay/0.2.0/stop\")\n )[0];\n\n if (!circuitPeer) {\n throw Error(\"No Circuit peer is found\");\n }\n\n let multiaddr = circuitPeer.addresses.pop().multiaddr;\n multiaddr = `${multiaddr}/p2p/${circuitPeer.id.toString()}/p2p-circuit/webrtc/p2p/${peerId}`;\n\n await node.dial(multiaddr);\n ui.setRelayMeshInfo(node.relay.gossipSub);\n },\n ensureWebRTCconnectionInRelayMesh: async () => {\n const promises = node.libp2p\n .getConnections()\n .filter((c) => c.stat.multiplexer === \"/webrtc\")\n .map(async (c) => {\n const outboundStream = node.relay.gossipSub.streamsOutbound.get(\n c.remotePeer.toString()\n );\n const isWebRTCOutbound =\n outboundStream.rawStream.constructor.name === \"WebRTCStream\";\n\n if (isWebRTCOutbound) {\n return;\n }\n\n node.relay.gossipSub.streamsOutbound.delete(c.remotePeer.toString());\n await node.relay.gossipSub.createOutboundStream(\n c.remotePeer.toString(),\n c\n );\n });\n await Promise.all(promises);\n ui.setRelayMeshInfo(node.relay.gossipSub);\n },\n dropNetworkConnections: async () => {\n const promises = node.libp2p\n .getConnections()\n .filter((c) => c.stat.multiplexer !== \"/webrtc\")\n .map(async (c) => {\n const peerId = c.remotePeer.toString();\n\n node.relay.gossipSub.peers.delete(peerId);\n node.relay.gossipSub.streamsInbound.delete(peerId);\n node.relay.gossipSub.streamsOutbound.delete(peerId);\n\n await node.libp2p.peerStore.delete(c.remotePeer);\n await c.close();\n });\n await Promise.all(promises);\n ui.setRelayMeshInfo(node.relay.gossipSub);\n },\n };\n}\n\n// UI adapter\nfunction initUI() {\n const exitButton = document.getElementById(\"exit\");\n const sendButton = document.getElementById(\"send\");\n\n const statusBlock = document.getElementById(\"status\");\n const localPeerBlock = document.getElementById(\"localPeerId\");\n const remotePeerId = document.getElementById(\"remotePeerId\");\n const contentTopicBlock = document.getElementById(\"contentTopic\");\n\n const messagesBlock = document.getElementById(\"messages\");\n\n const nickText = document.getElementById(\"nickText\");\n const messageText = document.getElementById(\"messageText\");\n\n const remoteNode = document.getElementById(\"remoteNode\");\n const connectRemoteNode = document.getElementById(\"connectRemoteNode\");\n\n const webrtcPeer = document.getElementById(\"webrtcPeer\");\n const connectWebrtcPeer = document.getElementById(\"connectWebrtcPeer\");\n\n const relayWebRTCbutton = document.getElementById(\"relayWebRTC\");\n const dropNonWebRTCbutton = document.getElementById(\"dropNonWebRTC\");\n\n const relayMeshInfo = document.getElementById(\"relayMeshInfo\");\n\n return {\n // UI events\n onExit: (cb) => {\n exitButton.addEventListener(\"click\", cb);\n },\n onSendMessage: (cb) => {\n sendButton.addEventListener(\"click\", async () => {\n await cb({\n nick: nickText.value,\n text: messageText.value,\n });\n messageText.value = \"\";\n });\n },\n // UI renderers\n setStatus: (value, className) => {\n statusBlock.innerHTML = `${value}`;\n },\n setLocalPeer: (id) => {\n localPeerBlock.innerText = id.toString();\n },\n setRemotePeer: (ids) => {\n remotePeerId.innerText = ids.join(\"\\n\");\n },\n setContentTopic: (topic) => {\n contentTopicBlock.innerText = topic.toString();\n },\n renderMessage: (messageObj) => {\n const { nick, text, timestamp } = messageObj;\n const date = new Date(timestamp);\n\n // WARNING: XSS vulnerable\n messagesBlock.innerHTML += `\n
\n

${nick} (${date.toDateString()}):

\n

${text}

\n
\n `;\n },\n resetMessages: () => {\n messagesBlock.innerHTML = \"\";\n },\n setWebrtcPeer: (peerId) => {\n webrtcPeer.value = peerId;\n },\n onRemoteNodeConnect: (cb) => {\n connectRemoteNode.addEventListener(\"click\", () => {\n const multiaddr = remoteNode.value;\n\n if (!multiaddr) {\n throw Error(\"No multiaddr set to dial\");\n }\n\n cb(multiaddr);\n });\n },\n onWebrtcConnect: (cb) => {\n connectWebrtcPeer.addEventListener(\"click\", () => {\n const multiaddr = webrtcPeer.value;\n\n if (!multiaddr) {\n throw Error(\"No multiaddr to dial webrtc\");\n }\n\n cb(multiaddr);\n });\n },\n onRelayWebRTC: (cb) => {\n relayWebRTCbutton.addEventListener(\"click\", cb);\n },\n onDropNonWebRTC: (cb) => {\n dropNonWebRTCbutton.addEventListener(\"click\", cb);\n },\n setRelayMeshInfo: (gossipSub) => {\n relayMeshInfo.innerHTML = \"\";\n\n Array.from(gossipSub.peers)\n .map((peerId) => {\n let inbound = gossipSub.streamsInbound.get(peerId);\n inbound = inbound ? inbound.rawStream.constructor.name : \"none\";\n\n let outbound = gossipSub.streamsOutbound.get(peerId);\n outbound = outbound ? outbound.rawStream.constructor.name : \"none\";\n\n return [peerId, inbound, outbound];\n })\n .map(([peerId, inbound, outbound]) => {\n relayMeshInfo.innerHTML += `${peerId}
inbound: ${inbound}\\toutbound: ${outbound}`;\n relayMeshInfo.innerHTML += \"

\";\n });\n },\n };\n}\n\n\n//# sourceURL=webpack://light/./index.js?"); /***/ }), diff --git a/experimental/web-chat/asset-manifest.json b/experimental/web-chat/asset-manifest.json index e6e6e9c..6d2ab0b 100644 --- a/experimental/web-chat/asset-manifest.json +++ b/experimental/web-chat/asset-manifest.json @@ -1,13 +1,13 @@ { "files": { - "main.css": "/web-chat/static/css/main.4df59f7b.css", - "main.js": "/web-chat/static/js/main.547d0ff0.js", + "main.css": "/web-chat/static/css/main.1a162b96.css", + "main.js": "/web-chat/static/js/main.b0962d94.js", "index.html": "/web-chat/index.html", - "main.4df59f7b.css.map": "/web-chat/static/css/main.4df59f7b.css.map", - "main.547d0ff0.js.map": "/web-chat/static/js/main.547d0ff0.js.map" + "main.1a162b96.css.map": "/web-chat/static/css/main.1a162b96.css.map", + "main.b0962d94.js.map": "/web-chat/static/js/main.b0962d94.js.map" }, "entrypoints": [ - "static/css/main.4df59f7b.css", - "static/js/main.547d0ff0.js" + "static/css/main.1a162b96.css", + "static/js/main.b0962d94.js" ] } \ No newline at end of file diff --git a/experimental/web-chat/index.html b/experimental/web-chat/index.html index 87cc813..4f3081e 100644 --- a/experimental/web-chat/index.html +++ b/experimental/web-chat/index.html @@ -1 +1 @@ -Waku v2 chat app
\ No newline at end of file +Waku v2 chat app
\ No newline at end of file diff --git a/experimental/web-chat/static/css/main.1a162b96.css b/experimental/web-chat/static/css/main.1a162b96.css new file mode 100644 index 0000000..03a6959 --- /dev/null +++ b/experimental/web-chat/static/css/main.1a162b96.css @@ -0,0 +1,4 @@ +/* +! tailwindcss v3.4.3 | MIT License | https://tailwindcss.com +*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{-webkit-text-size-adjust:100%;font-feature-settings:normal;-webkit-tap-highlight-color:transparent;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-variation-settings:normal;line-height:1.5;tab-size:4}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-feature-settings:normal;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:initial}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{font-feature-settings:inherit;color:inherit;font-family:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:initial;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:initial}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]{display:none}*,::backdrop,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#3b82f680;--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.static{position:static}.mt-2{margin-top:.5rem}.flex{display:flex}.hidden{display:none}.h-full{height:100%}.h-screen{height:100vh}.flex-none{flex:none}.flex-grow{flex-grow:1}.cursor-not-allowed{cursor:not-allowed}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-between{justify-content:space-between}.overflow-y-auto{overflow-y:auto}.rounded-l-md{border-bottom-left-radius:.375rem;border-top-left-radius:.375rem}.rounded-r-md{border-bottom-right-radius:.375rem;border-top-right-radius:.375rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity))}.border-gray-300{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity))}.bg-blue-300{--tw-bg-opacity:1;background-color:rgb(147 197 253/var(--tw-bg-opacity))}.bg-blue-500{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity))}.bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.p-2{padding:.5rem}.p-4{padding:1rem}.px-4{padding-left:1rem;padding-right:1rem}.py-2{padding-bottom:.5rem;padding-top:.5rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)} +/*# sourceMappingURL=main.1a162b96.css.map*/ \ No newline at end of file diff --git a/experimental/web-chat/static/css/main.1a162b96.css.map b/experimental/web-chat/static/css/main.1a162b96.css.map new file mode 100644 index 0000000..99ca112 --- /dev/null +++ b/experimental/web-chat/static/css/main.1a162b96.css.map @@ -0,0 +1 @@ +{"version":3,"file":"static/css/main.1a162b96.css","mappings":"AAAA;;CAAc,CAAd,uCAAc,CAAd,qBAAc,CAAd,8BAAc,CAAd,wCAAc,CAAd,4BAAc,CAAd,uCAAc,CAAd,gHAAc,CAAd,8BAAc,CAAd,eAAc,CAAd,UAAc,CAAd,wBAAc,CAAd,QAAc,CAAd,uBAAc,CAAd,aAAc,CAAd,QAAc,CAAd,4DAAc,CAAd,gCAAc,CAAd,mCAAc,CAAd,mBAAc,CAAd,eAAc,CAAd,uBAAc,CAAd,2BAAc,CAAd,8CAAc,CAAd,mGAAc,CAAd,aAAc,CAAd,8BAAc,CAAd,mBAAc,CAAd,qBAAc,CAAd,aAAc,CAAd,iBAAc,CAAd,sBAAc,CAAd,iBAAc,CAAd,aAAc,CAAd,8BAAc,CAAd,oBAAc,CAAd,aAAc,CAAd,mEAAc,CAAd,aAAc,CAAd,mBAAc,CAAd,cAAc,CAAd,+BAAc,CAAd,mBAAc,CAAd,sBAAc,CAAd,mBAAc,CAAd,QAAc,CAAd,SAAc,CAAd,iCAAc,CAAd,gHAAc,CAAd,wBAAc,CAAd,qBAAc,CAAd,4BAAc,CAAd,gCAAc,CAAd,+BAAc,CAAd,mEAAc,CAAd,0CAAc,CAAd,mBAAc,CAAd,mDAAc,CAAd,sDAAc,CAAd,YAAc,CAAd,yBAAc,CAAd,2DAAc,CAAd,iBAAc,CAAd,yBAAc,CAAd,0BAAc,CAAd,QAAc,CAAd,SAAc,CAAd,gBAAc,CAAd,wBAAc,CAAd,sDAAc,CAAd,SAAc,CAAd,mCAAc,CAAd,wBAAc,CAAd,4DAAc,CAAd,qBAAc,CAAd,qBAAc,CAAd,cAAc,CAAd,qBAAc,CAAd,mDAAc,CAAd,uBAAc,CAAd,kBAAc,CAAd,kBAAc,CAAd,aAAc,CAAd,aAAc,CAAd,aAAc,CAAd,cAAc,CAAd,cAAc,CAAd,YAAc,CAAd,YAAc,CAAd,iBAAc,CAAd,qCAAc,CAAd,6BAAc,CAAd,4BAAc,CAAd,2BAAc,CAAd,cAAc,CAAd,mBAAc,CAAd,qBAAc,CAAd,sBAAc,CAAd,uBAAc,CAAd,iBAAc,CAAd,0BAAc,CAAd,2BAAc,CAAd,yBAAc,CAAd,iCAAc,CAAd,0BAAc,CAAd,qBAAc,CAAd,6BAAc,CAAd,WAAc,CAAd,iBAAc,CAAd,eAAc,CAAd,gBAAc,CAAd,iBAAc,CAAd,aAAc,CAAd,eAAc,CAAd,YAAc,CAAd,kBAAc,CAAd,oBAAc,CAAd,0BAAc,CAAd,wBAAc,CAAd,yBAAc,CAAd,0BAAc,CAAd,sBAAc,CAAd,uBAAc,CAAd,wBAAc,CAAd,qBAAc,CAAd,mBAAc,CAAd,qBAAc,CAAd,oBAAc,CAAd,oBAAc,CAEd,uBAAmB,CAAnB,sBAAmB,CAAnB,kBAAmB,CAAnB,oBAAmB,CAAnB,mBAAmB,CAAnB,sBAAmB,CAAnB,oBAAmB,CAAnB,sBAAmB,CAAnB,sCAAmB,CAAnB,+BAAmB,CAAnB,gCAAmB,CAAnB,8CAAmB,CAAnB,gCAAmB,CAAnB,8EAAmB,CAAnB,gFAAmB,CAAnB,wBAAmB,CAAnB,iCAAmB,CAAnB,sCAAmB,CAAnB,sDAAmB,CAAnB,sCAAmB,CAAnB,sDAAmB,CAAnB,8BAAmB,CAAnB,sDAAmB,CAAnB,8BAAmB,CAAnB,qDAAmB,CAAnB,8BAAmB,CAAnB,mDAAmB,CAAnB,kBAAmB,CAAnB,iBAAmB,CAAnB,uBAAmB,CAAnB,kBAAmB,CAAnB,4CAAmB,CAAnB,0BAAmB,CAAnB,mBAAmB,CAAnB,kCAAmB,CAAnB,6CAAmB,CAAnB,kCAAmB,CAAnB,0CAAmB,CAAnB,+BAAmB,CAAnB,6CAAmB,CAAnB,wLAAmB","sources":["index.css"],"sourcesContent":["@tailwind base;\n@tailwind components;\n@tailwind utilities;\n"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/experimental/web-chat/static/css/main.4df59f7b.css b/experimental/web-chat/static/css/main.4df59f7b.css deleted file mode 100644 index 4eb5be5..0000000 --- a/experimental/web-chat/static/css/main.4df59f7b.css +++ /dev/null @@ -1,4 +0,0 @@ -/* -! tailwindcss v3.4.3 | MIT License | https://tailwindcss.com -*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{-webkit-text-size-adjust:100%;font-feature-settings:normal;-webkit-tap-highlight-color:transparent;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-variation-settings:normal;line-height:1.5;tab-size:4}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-feature-settings:normal;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:initial}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{font-feature-settings:inherit;color:inherit;font-family:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:initial;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:initial}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]{display:none}*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#3b82f680;--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#3b82f680;--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.static{position:static}.mt-2{margin-top:.5rem}.flex{display:flex}.hidden{display:none}.h-full{height:100%}.h-screen{height:100vh}.flex-none{flex:none}.flex-grow{flex-grow:1}.cursor-not-allowed{cursor:not-allowed}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-between{justify-content:space-between}.overflow-y-auto{overflow-y:auto}.rounded-l-md{border-bottom-left-radius:.375rem;border-top-left-radius:.375rem}.rounded-r-md{border-bottom-right-radius:.375rem;border-top-right-radius:.375rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity))}.border-gray-300{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity))}.bg-blue-300{--tw-bg-opacity:1;background-color:rgb(147 197 253/var(--tw-bg-opacity))}.bg-blue-500{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity))}.bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.p-2{padding:.5rem}.p-4{padding:1rem}.px-4{padding-left:1rem;padding-right:1rem}.py-2{padding-bottom:.5rem;padding-top:.5rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)} -/*# sourceMappingURL=main.4df59f7b.css.map*/ \ No newline at end of file diff --git a/experimental/web-chat/static/css/main.4df59f7b.css.map b/experimental/web-chat/static/css/main.4df59f7b.css.map deleted file mode 100644 index 12a8265..0000000 --- a/experimental/web-chat/static/css/main.4df59f7b.css.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"static/css/main.4df59f7b.css","mappings":"AAAA;;CAAc,CAAd,uCAAc,CAAd,qBAAc,CAAd,8BAAc,CAAd,wCAAc,CAAd,4BAAc,CAAd,uCAAc,CAAd,gHAAc,CAAd,8BAAc,CAAd,eAAc,CAAd,UAAc,CAAd,wBAAc,CAAd,QAAc,CAAd,uBAAc,CAAd,aAAc,CAAd,QAAc,CAAd,4DAAc,CAAd,gCAAc,CAAd,mCAAc,CAAd,mBAAc,CAAd,eAAc,CAAd,uBAAc,CAAd,2BAAc,CAAd,8CAAc,CAAd,mGAAc,CAAd,aAAc,CAAd,8BAAc,CAAd,mBAAc,CAAd,qBAAc,CAAd,aAAc,CAAd,iBAAc,CAAd,sBAAc,CAAd,iBAAc,CAAd,aAAc,CAAd,8BAAc,CAAd,oBAAc,CAAd,aAAc,CAAd,mEAAc,CAAd,aAAc,CAAd,mBAAc,CAAd,cAAc,CAAd,+BAAc,CAAd,mBAAc,CAAd,sBAAc,CAAd,mBAAc,CAAd,QAAc,CAAd,SAAc,CAAd,iCAAc,CAAd,gHAAc,CAAd,wBAAc,CAAd,qBAAc,CAAd,4BAAc,CAAd,gCAAc,CAAd,+BAAc,CAAd,mEAAc,CAAd,0CAAc,CAAd,mBAAc,CAAd,mDAAc,CAAd,sDAAc,CAAd,YAAc,CAAd,yBAAc,CAAd,2DAAc,CAAd,iBAAc,CAAd,yBAAc,CAAd,0BAAc,CAAd,QAAc,CAAd,SAAc,CAAd,gBAAc,CAAd,wBAAc,CAAd,sDAAc,CAAd,SAAc,CAAd,mCAAc,CAAd,wBAAc,CAAd,4DAAc,CAAd,qBAAc,CAAd,qBAAc,CAAd,cAAc,CAAd,qBAAc,CAAd,wCAAc,CAAd,uBAAc,CAAd,kBAAc,CAAd,kBAAc,CAAd,aAAc,CAAd,aAAc,CAAd,aAAc,CAAd,cAAc,CAAd,cAAc,CAAd,YAAc,CAAd,YAAc,CAAd,iBAAc,CAAd,qCAAc,CAAd,6BAAc,CAAd,4BAAc,CAAd,2BAAc,CAAd,cAAc,CAAd,mBAAc,CAAd,qBAAc,CAAd,sBAAc,CAAd,uBAAc,CAAd,iBAAc,CAAd,0BAAc,CAAd,2BAAc,CAAd,yBAAc,CAAd,iCAAc,CAAd,0BAAc,CAAd,qBAAc,CAAd,6BAAc,CAAd,WAAc,CAAd,iBAAc,CAAd,eAAc,CAAd,gBAAc,CAAd,iBAAc,CAAd,aAAc,CAAd,eAAc,CAAd,YAAc,CAAd,kBAAc,CAAd,oBAAc,CAAd,0BAAc,CAAd,wBAAc,CAAd,yBAAc,CAAd,0BAAc,CAAd,sBAAc,CAAd,uBAAc,CAAd,wBAAc,CAAd,qBAAc,CAAd,mBAAc,CAAd,qBAAc,CAAd,oBAAc,CAAd,oBAAc,CAAd,kCAAc,CAAd,uBAAc,CAAd,kBAAc,CAAd,kBAAc,CAAd,aAAc,CAAd,aAAc,CAAd,aAAc,CAAd,cAAc,CAAd,cAAc,CAAd,YAAc,CAAd,YAAc,CAAd,iBAAc,CAAd,qCAAc,CAAd,6BAAc,CAAd,4BAAc,CAAd,2BAAc,CAAd,cAAc,CAAd,mBAAc,CAAd,qBAAc,CAAd,sBAAc,CAAd,uBAAc,CAAd,iBAAc,CAAd,0BAAc,CAAd,2BAAc,CAAd,yBAAc,CAAd,iCAAc,CAAd,0BAAc,CAAd,qBAAc,CAAd,6BAAc,CAAd,WAAc,CAAd,iBAAc,CAAd,eAAc,CAAd,gBAAc,CAAd,iBAAc,CAAd,aAAc,CAAd,eAAc,CAAd,YAAc,CAAd,kBAAc,CAAd,oBAAc,CAAd,0BAAc,CAAd,wBAAc,CAAd,yBAAc,CAAd,0BAAc,CAAd,sBAAc,CAAd,uBAAc,CAAd,wBAAc,CAAd,qBAAc,CAAd,mBAAc,CAAd,qBAAc,CAAd,oBAAc,CAAd,oBAAc,CAEd,uBAAmB,CAAnB,sBAAmB,CAAnB,kBAAmB,CAAnB,oBAAmB,CAAnB,mBAAmB,CAAnB,sBAAmB,CAAnB,oBAAmB,CAAnB,sBAAmB,CAAnB,sCAAmB,CAAnB,+BAAmB,CAAnB,gCAAmB,CAAnB,8CAAmB,CAAnB,gCAAmB,CAAnB,8EAAmB,CAAnB,gFAAmB,CAAnB,wBAAmB,CAAnB,iCAAmB,CAAnB,sCAAmB,CAAnB,sDAAmB,CAAnB,sCAAmB,CAAnB,sDAAmB,CAAnB,8BAAmB,CAAnB,sDAAmB,CAAnB,8BAAmB,CAAnB,qDAAmB,CAAnB,8BAAmB,CAAnB,mDAAmB,CAAnB,kBAAmB,CAAnB,iBAAmB,CAAnB,uBAAmB,CAAnB,kBAAmB,CAAnB,4CAAmB,CAAnB,0BAAmB,CAAnB,mBAAmB,CAAnB,kCAAmB,CAAnB,6CAAmB,CAAnB,kCAAmB,CAAnB,0CAAmB,CAAnB,+BAAmB,CAAnB,6CAAmB,CAAnB,wLAAmB","sources":["index.css"],"sourcesContent":["@tailwind base;\n@tailwind components;\n@tailwind utilities;\n"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/experimental/web-chat/static/js/main.547d0ff0.js b/experimental/web-chat/static/js/main.547d0ff0.js deleted file mode 100644 index e402f80..0000000 --- a/experimental/web-chat/static/js/main.547d0ff0.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see main.547d0ff0.js.LICENSE.txt */ -(()=>{var __webpack_modules__={4762:e=>{"use strict";e.exports=function(e,t){var r=new Array(arguments.length-1),n=0,i=2,o=!0;for(;i{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),i=new Array(123),o=0;o<64;)i[n[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;r.encode=function(e,t,r){for(var i,o=null,s=[],a=0,c=0;t>2],i=(3&u)<<4,c=1;break;case 1:s[a++]=n[i|u>>4],i=(15&u)<<2,c=2;break;case 2:s[a++]=n[i|u>>6],s[a++]=n[63&u],c=0}a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0)}return c&&(s[a++]=n[i],s[a++]=61,1===c&&(s[a++]=61)),o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};var s="invalid encoding";r.decode=function(e,t,r){for(var n,o=r,a=0,c=0;c1)break;if(void 0===(u=i[u]))throw Error(s);switch(a){case 0:n=u,a=1;break;case 1:t[r++]=n<<2|(48&u)>>4,n=u,a=2;break;case 2:t[r++]=(15&n)<<4|(60&u)>>2,n=u,a=3;break;case 3:t[r++]=(3&n)<<6|u,a=0}}if(1===a)throw Error(s);return r-o},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},7351:e=>{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n{"use strict";function t(e){return"undefined"!==typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3]}function o(e,n,i){t[0]=e,n[i]=r[3],n[i+1]=r[2],n[i+2]=r[1],n[i+3]=r[0]}function s(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?i:o,e.writeFloatBE=n?o:i,e.readFloatLE=n?s:a,e.readFloatBE=n?a:s}():function(){function t(e,t,r,n){var i=t<0?1:0;if(i&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((i<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((i<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var o=Math.floor(Math.log(t)/Math.LN2);e((i<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,r,n)}}function s(e,t,r){var n=e(t,r),i=2*(n>>31)+1,o=n>>>23&255,s=8388607&n;return 255===o?s?NaN:i*(1/0):0===o?1401298464324817e-60*i*s:i*Math.pow(2,o-150)*(s+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=s.bind(null,i),e.readFloatBE=s.bind(null,o)}(),"undefined"!==typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3],n[i+4]=r[4],n[i+5]=r[5],n[i+6]=r[6],n[i+7]=r[7]}function o(e,n,i){t[0]=e,n[i]=r[7],n[i+1]=r[6],n[i+2]=r[5],n[i+3]=r[4],n[i+4]=r[3],n[i+5]=r[2],n[i+6]=r[1],n[i+7]=r[0]}function s(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?i:o,e.writeDoubleBE=n?o:i,e.readDoubleLE=n?s:a,e.readDoubleBE=n?a:s}():function(){function t(e,t,r,n,i,o){var s=n<0?1:0;if(s&&(n=-n),0===n)e(0,i,o+t),e(1/n>0?0:2147483648,i,o+r);else if(isNaN(n))e(0,i,o+t),e(2146959360,i,o+r);else if(n>17976931348623157e292)e(0,i,o+t),e((s<<31|2146435072)>>>0,i,o+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,i,o+t),e((s<<31|a/4294967296)>>>0,i,o+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,i,o+t),e((s<<31|c+1023<<20|1048576*a&1048575)>>>0,i,o+r)}}}function s(e,t,r,n,i){var o=e(n,i+t),s=e(n,i+r),a=2*(s>>31)+1,c=s>>>20&2047,u=4294967296*(1048575&s)+o;return 2047===c?u?NaN:a*(1/0):0===c?5e-324*a*u:a*Math.pow(2,c-1075)*(u+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=s.bind(null,i,0,4),e.readDoubleBE=s.bind(null,o,4,0)}(),e}function r(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function i(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function o(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},4882:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},6931:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,i=n>>>1,o=null,s=n;return function(r){if(r<1||r>i)return e(r);s+r>n&&(o=e(n),s=0);var a=t.call(o,s,s+=r);return 7&s&&(s=1+(7|s)),a}}},8626:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?o[s++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[s++]=55296+(n>>10),o[s++]=56320+(1023&n)):o[s++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))},r.write=function(e,t,r){for(var n,i,o=r,s=0;s>6|192,t[r++]=63&n|128):55296===(64512&n)&&56320===(64512&(i=e.charCodeAt(s+1)))?(n=65536+((1023&n)<<10)+(1023&i),++s,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-o}},6522:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(r){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(r){}!e&&"undefined"!==typeof process&&"env"in process&&(e={NODE_ENV:"production",PUBLIC_URL:"/web-chat",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}.DEBUG);return e},t.useColors=function(){if("undefined"!==typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!==typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!==typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(5237)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}},5237:(e,t,r)=>{e.exports=function(e){function t(e){let r,i,o,s=null;function a(){for(var e=arguments.length,n=new Array(e),i=0;i{if("%%"===e)return"%";u++;const i=t.formatters[r];if("function"===typeof i){const t=n[u];e=i.call(o,t),n.splice(u,1),u--}return e})),t.formatArgs.call(o,n);(o.log||t.log).apply(o,n)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{s=e}}),"function"===typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+("undefined"===typeof r?":":r)+e);return n.log=this.log,n}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"===typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";function t(e,t){t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(e)?this._fromArray(e):(this._capacityMask=3,this._list=new Array(4))}t.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}},t.prototype.get=function(e){return this.peekAt(e)},t.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},t.prototype.peekFront=function(){return this.peek()},t.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(t.prototype,"length",{get:function(){return this.size()}}),t.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},t.prototype.push=function(e){if(0===arguments.length)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var i,o=this._list[t];if(e0;i--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(i=r-1-e;i>0;i--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return o}}},t.prototype.remove=function(e,t){var r,n=e,i=t;if(n===(0|n)&&this._head!==this._tail){var o=this.size(),s=this._list.length;if(!(n>=o||n<-o||t<1)){if(n<0&&(n+=o),1===t||!t)return(r=new Array(1))[0]=this.removeOne(n),r;if(0===n&&n+t>=o)return r=this.toArray(),this.clear(),r;var a;for(n+t>o&&(t=o-n),r=new Array(t),a=0;a0;a--)this._list[n=n+1+s&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+s&this._capacityMask,a=t-1;a>0;a--)this._list[n=n+1+s&this._capacityMask]=void 0;return r}if(n0;a--)this.unshift(this._list[n=n-1+s&this._capacityMask]);for(n=this._head-1+s&this._capacityMask;i>0;)this._list[n=n-1+s&this._capacityMask]=void 0,i--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+s&this._capacityMask,a=o-(t+e);a>0;a--)this.push(this._list[n++]);for(n=this._tail;i>0;)this._list[n=n+1+s&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=s>>>2&&this._shrinkArray(),r}}},t.prototype.splice=function(e,t){var r=e;if(r===(0|r)){var n=this.size();if(r<0&&(r+=n),!(r>n)){if(arguments.length>2){var i,o,s,a=arguments.length,c=this._list.length,u=2;if(!n||r0&&(this._head=this._head+r+c&this._capacityMask)):(s=this.remove(r,t),this._head=this._head+r+c&this._capacityMask);a>u;)this.unshift(arguments[--a]);for(i=r;i>0;i--)this.unshift(o[i-1])}else{var l=(o=new Array(n-(r+t))).length;for(i=0;ithis._tail){for(o=this._head;o>>=1,this._capacityMask>>>=1},t.prototype._nextPowerOf2=function(e){var t=1<{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,n){if(!e||"string"===typeof e)throw new TypeError("Please pass an Error to err-code");n||(n={}),"object"===typeof r&&(n=r,r=""),r&&(n.code=r);try{return t(e,n)}catch(i){n.message=e.message,n.stack=e.stack;const r=function(){};r.prototype=Object.create(Object.getPrototypeOf(e));return t(new r,n)}}},2605:(e,t,r)=>{"use strict";const n=r(9020);t.PP=n.EventIterator,n.EventIterator},9020:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn("EventIterator queue reached ".concat(this.pushQueue.length," items")))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e){let{highWaterMark:t=100,lowWaterMark:n=1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new r;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},7283:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,n,o,s){if("function"!==typeof n)throw new TypeError("The listener must be a function");var a=new i(n,o||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i{e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function i(i,o){r[i]=o,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},5411:(e,t,r)=>{var n;!function(){"use strict";var t="object"===typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"===typeof process&&process.versions&&process.versions.node&&(t=r.g);var i=!t.HI_BASE32_NO_COMMON_JS&&e.exports,o=r.amdO,s="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},c=[0,0,0,0,0,0,0,0],u=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},l=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,r,n,i,o,s,c,u,l=[],h=0,d=(e=e.replace(/=/g,"")).length,f=0,p=d>>3<<3;f>>2),l[h++]=255&(r<<6|n<<1|i>>>4),l[h++]=255&(i<<4|o>>>1),l[h++]=255&(o<<7|s<<2|c>>>3),l[h++]=255&(c<<5|u);var g=d-p;return 2===g?(t=a[e.charAt(f++)],r=a[e.charAt(f++)],l[h++]=255&(t<<3|r>>>2)):4===g?(t=a[e.charAt(f++)],r=a[e.charAt(f++)],n=a[e.charAt(f++)],i=a[e.charAt(f++)],l[h++]=255&(t<<3|r>>>2),l[h++]=255&(r<<6|n<<1|i>>>4)):5===g?(t=a[e.charAt(f++)],r=a[e.charAt(f++)],n=a[e.charAt(f++)],i=a[e.charAt(f++)],o=a[e.charAt(f++)],l[h++]=255&(t<<3|r>>>2),l[h++]=255&(r<<6|n<<1|i>>>4),l[h++]=255&(i<<4|o>>>1)):7===g&&(t=a[e.charAt(f++)],r=a[e.charAt(f++)],n=a[e.charAt(f++)],i=a[e.charAt(f++)],o=a[e.charAt(f++)],s=a[e.charAt(f++)],c=a[e.charAt(f++)],l[h++]=255&(t<<3|r>>>2),l[h++]=255&(r<<6|n<<1|i>>>4),l[h++]=255&(i<<4|o>>>1),l[h++]=255&(o<<7|s<<2|c>>>3)),l},h=function(e,t){if(!t)return function(e){for(var t,r,n="",i=e.length,o=0,s=0;o191&&t<=223?(r=31&t,s=1):t<=239?(r=15&t,s=2):t<=247?(r=7&t,s=3):u(o,n);for(var a=0;a191)&&u(o,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&u(o,n),r>1114111&&u(o,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296+(r>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n}(l(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var r,n,i,o,s,c,h,d,f="",p=e.indexOf("=");-1===p&&(p=e.length);for(var g=0,b=p>>3<<3;g>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))+String.fromCharCode(255&(o<<4|s>>>1))+String.fromCharCode(255&(s<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=p-b;return 2===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))):4===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))):5===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],s=a[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))+String.fromCharCode(255&(o<<4|s>>>1))):7===y&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],s=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))+String.fromCharCode(255&(o<<4|s>>>1))+String.fromCharCode(255&(s<<7|c<<2|h>>>3))),f},d={encode:function(e,t){var r="string"!==typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?function(e){for(var t,r,n,i,o,a="",c=e.length,u=0,l=5*parseInt(c/5);u>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[31&(r<<4|n>>>4)]+s[31&(n<<1|i>>>7)]+s[i>>>2&31]+s[31&(i<<3|o>>>5)]+s[31&o];var h=c-l;return 1===h?(t=e[u],a+=s[t>>>3]+s[t<<2&31]+"======"):2===h?(t=e[u++],r=e[u],a+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[r<<4&31]+"===="):3===h?(t=e[u++],r=e[u++],n=e[u],a+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[31&(r<<4|n>>>4)]+s[n<<1&31]+"==="):4===h&&(t=e[u++],r=e[u++],n=e[u++],i=e[u],a+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[31&(r<<4|n>>>4)]+s[31&(n<<1|i>>>7)]+s[i>>>2&31]+s[i<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,i,o,a="",c=e.length,u=0,l=5*parseInt(c/5);u>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[31&(r<<4|n>>>4)]+s[31&(n<<1|i>>>7)]+s[i>>>2&31]+s[31&(i<<3|o>>>5)]+s[31&o];var h=c-l;return 1===h?(t=e.charCodeAt(u),a+=s[t>>>3]+s[t<<2&31]+"======"):2===h?(t=e.charCodeAt(u++),r=e.charCodeAt(u),a+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[r<<4&31]+"===="):3===h?(t=e.charCodeAt(u++),r=e.charCodeAt(u++),n=e.charCodeAt(u),a+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[31&(r<<4|n>>>4)]+s[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(u++),r=e.charCodeAt(u++),n=e.charCodeAt(u++),i=e.charCodeAt(u),a+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[31&(r<<4|n>>>4)]+s[31&(n<<1|i>>>7)]+s[i>>>2&31]+s[i<<3&31]+"="),a}(e):function(e){var t,r,n,i,o,a,u,l=!1,h="",d=0,f=0,p=e.length;if(""===e)return h;do{for(c[0]=c[5],c[1]=c[6],c[2]=c[7],u=f;d>6,c[u++]=128|63&a):a<55296||a>=57344?(c[u++]=224|a>>12,c[u++]=128|a>>6&63,c[u++]=128|63&a):(a=65536+((1023&a)<<10|1023&e.charCodeAt(++d)),c[u++]=240|a>>18,c[u++]=128|a>>12&63,c[u++]=128|a>>6&63,c[u++]=128|63&a);f=u-5,d===p&&++d,d>p&&u<6&&(l=!0),t=c[0],u>4?(r=c[1],n=c[2],i=c[3],o=c[4],h+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[31&(r<<4|n>>>4)]+s[31&(n<<1|i>>>7)]+s[i>>>2&31]+s[31&(i<<3|o>>>5)]+s[31&o]):1===u?h+=s[t>>>3]+s[t<<2&31]+"======":2===u?(r=c[1],h+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[r<<4&31]+"===="):3===u?(r=c[1],n=c[2],h+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[31&(r<<4|n>>>4)]+s[n<<1&31]+"==="):(r=c[1],n=c[2],i=c[3],h+=s[t>>>3]+s[31&(t<<2|r>>>6)]+s[r>>>1&31]+s[31&(r<<4|n>>>4)]+s[31&(n<<1|i>>>7)]+s[i>>>2&31]+s[i<<3&31]+"=")}while(!l);return h}(e)},decode:h};h.asBytes=l,i?e.exports=d:(t.base32=d,o&&(void 0===(n=function(){return d}.call(d,r,d,e))||(e.exports=n)))}()},4053:e=>{e.exports=function(){return"undefined"!==typeof window&&"object"===typeof window.process&&"renderer"===window.process.type||(!("undefined"===typeof process||"object"!==typeof process.versions||!process.versions.electron)||"object"===typeof navigator&&"string"===typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0)}},8313:e=>{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},2161:(e,t,r)=>{var n;!function(){"use strict";var i="input is invalid type",o="object"===typeof window,s=o?window:{};s.JS_SHA3_NO_WINDOW&&(o=!1);var a=!o&&"object"===typeof self;!s.JS_SHA3_NO_NODE_JS&&"object"===typeof process&&process.versions&&process.versions.node?s=r.g:a&&(s=self);for(var c=!s.JS_SHA3_NO_COMMON_JS&&e.exports,u=r.amdO,l=!s.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!==typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],f=[0,8,16,24],p=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],b=[128,256],y=["hex","buffer","arrayBuffer","array","digest"],m={128:168,256:136},v=s.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,w=!l||!s.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(e){return"object"===typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer},_=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(i);if(l&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!v(e)&&!w(e))throw new Error(i);return[e,!1]},E=function(e){return 0===_(e)[0].length},S=function(e){for(var t=[],r=0;r>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function K(e,t,r){q.call(this,e,t,r)}q.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=_(e);e=t[0];for(var r,n,i=t[1],o=this.blocks,s=this.byteCount,a=e.length,c=this.blockCount,u=0,l=this.s;u>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(o[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=e[u]<=s){for(this.start=r-s,this.block=o[c],r=0;r>=8);r>0;)i.unshift(r),r=255&(e>>=8),++n;return t?i.push(n):i.unshift(n),this.update(i),i.length},q.prototype.encodeString=function(e){var t=_(e);e=t[0];var r=t[1],n=0,i=e.length;if(r)for(var o=0;o=57344?n+=3:(s=65536+((1023&s)<<10|1023&e.charCodeAt(++o)),n+=4)}else n=i;return n+=this.encode(8*n),this.update(e),n},q.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];s%t===0&&(r=S(r),F(r),o=0)}return i&&(e=r[o],a+=h[e>>4&15]+h[15&e],i>1&&(a+=h[e>>12&15]+h[e>>8&15]),i>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},q.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,o=0,s=0,a=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);s>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r===0&&(n=S(n),F(n))}return o&&(e=a<<2,t=n[s],c[e]=255&t,o>1&&(c[e+1]=t>>8&255),o>2&&(c[e+2]=t>>16&255)),c},K.prototype=new q,K.prototype.finalize=function(){return this.encode(this.outputBits,!0),q.prototype.finalize.call(this)};var F=function(e){var t,r,n,i,o,s,a,c,u,l,h,d,f,g,b,y,m,v,w,_,E,S,A,k,x,I,C,T,R,P,D,N,B,U,L,M,O,q,K,F,V,z,j,H,G,W,Y,Q,J,X,Z,$,ee,te,re,ne,ie,oe,se,ae,ce,ue,le;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],s=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],u=e[5]^e[15]^e[25]^e[35]^e[45],l=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(s<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|s>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|u>>>31),r=o^(u<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=s^(l<<1|h>>>31),r=a^(h<<1|l>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|f>>>31),r=u^(f<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=l^(i<<1|o>>>31),r=h^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],b=e[1],W=e[11]<<4|e[10]>>>28,Y=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,R=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,j=e[41]<<18|e[40]>>>14,U=e[2]<<1|e[3]>>>31,L=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,m=e[12]<<12|e[13]>>>20,Q=e[22]<<10|e[23]>>>22,J=e[23]<<10|e[22]>>>22,P=e[33]<<13|e[32]>>>19,D=e[32]<<13|e[33]>>>19,ue=e[42]<<2|e[43]>>>30,le=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,M=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,v=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,X=e[34]<<15|e[35]>>>17,Z=e[35]<<15|e[34]>>>17,N=e[45]<<29|e[44]>>>3,B=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,x=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,q=e[26]<<25|e[27]>>>7,K=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,E=e[37]<<21|e[36]>>>11,$=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,H=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,I=e[18]<<20|e[19]>>>12,C=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,se=e[28]<<7|e[29]>>>25,F=e[38]<<8|e[39]>>>24,V=e[39]<<8|e[38]>>>24,S=e[48]<<14|e[49]>>>18,A=e[49]<<14|e[48]>>>18,e[0]=g^~y&v,e[1]=b^~m&w,e[10]=k^~I&T,e[11]=x^~C&R,e[20]=U^~M&q,e[21]=L^~O&K,e[30]=H^~W&Q,e[31]=G^~Y&J,e[40]=te^~ne&oe,e[41]=re^~ie&se,e[2]=y^~v&_,e[3]=m^~w&E,e[12]=I^~T&P,e[13]=C^~R&D,e[22]=M^~q&F,e[23]=O^~K&V,e[32]=W^~Q&X,e[33]=Y^~J&Z,e[42]=ne^~oe&ae,e[43]=ie^~se&ce,e[4]=v^~_&S,e[5]=w^~E&A,e[14]=T^~P&N,e[15]=R^~D&B,e[24]=q^~F&z,e[25]=K^~V&j,e[34]=Q^~X&$,e[35]=J^~Z&ee,e[44]=oe^~ae&ue,e[45]=se^~ce&le,e[6]=_^~S&g,e[7]=E^~A&b,e[16]=P^~N&k,e[17]=D^~B&x,e[26]=F^~z&U,e[27]=V^~j&L,e[36]=X^~$&H,e[37]=Z^~ee&G,e[46]=ae^~ue&te,e[47]=ce^~le&re,e[8]=S^~g&y,e[9]=A^~b&m,e[18]=N^~k&I,e[19]=B^~x&C,e[28]=z^~U&M,e[29]=j^~L&O,e[38]=$^~H&W,e[39]=ee^~G&Y,e[48]=ue^~te&ne,e[49]=le^~re&ie,e[0]^=p[n],e[1]^=p[n+1]};if(c)e.exports=P;else{for(N=0;NObject.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},u=e=>{const t=[];for(const r in e)i.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)o.call(e,n)&&t.push(n)}return t};function l(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return u(e).forEach((r=>{s(t,r,l(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return u(e).forEach((r=>{s(t,r,l(e[r]))})),t}(e):e}const h=(e,t,r,n)=>(r.forEach((r=>{"undefined"===typeof t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?s(e,r,f(e[r],t[r],n)):s(e,r,l(t[r])))})),e),d=(e,t,r)=>{let n=e.slice(0,0),o=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r!a.includes(e))),r)})),n};function f(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?d(e,t,r):n(t)&&n(e)?h(e,t,u(t),r):l(t)}e.exports=function(){const e=f(l(c),this!==a&&this||{},c);let t={_:{}};for(var r=arguments.length,i=new Array(r),o=0;o{var t=1e3,r=60*t,n=60*r,i=24*n,o=7*i,s=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var u=typeof e;if("string"===u&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*o;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===u&&isFinite(e))return c.long?function(e){var o=Math.abs(e);if(o>=i)return a(e,o,i,"day");if(o>=n)return a(e,o,n,"hour");if(o>=r)return a(e,o,r,"minute");if(o>=t)return a(e,o,t,"second");return e+" ms"}(e):function(e){var o=Math.abs(e);if(o>=i)return Math.round(e/i)+"d";if(o>=n)return Math.round(e/n)+"h";if(o>=r)return Math.round(e/r)+"m";if(o>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},7364:function(e,t){(function(){var e,r,n,i,o,s,a,c;c=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,i,o,s,a;for(t=[],i=o=0;o<=3&&0!==e.length;i=++o){if(i>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}s=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(s)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},i=(n=function(e){return e.charCodeAt(0)})("0"),s=n("a"),o=n("A"),r=function(e){var t,r,a,c,u;for(c=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),u=a;a>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-s)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-o)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===u)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,i;if("string"!==typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"===typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(o){throw o,new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(o){throw o,new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"===typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(c(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},9353:(e,t,r)=>{var n=r(45);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.aes.Algorithm(e,t)}))}r(9151),r(1655),r(3900),e.exports=n.aes=n.aes||{},n.aes.startEncrypting=function(e,t,r,n){var i=g({key:e,output:r,decrypt:!1,mode:n});return i.start(t),i},n.aes.createEncryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!1,mode:t})},n.aes.startDecrypting=function(e,t,r,n){var i=g({key:e,output:r,decrypt:!0,mode:n});return i.start(t),i},n.aes.createDecryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!0,mode:t})},n.aes.Algorithm=function(e,t){l||d();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return p(r._w,e,t,!1)},decrypt:function(e,t){return p(r._w,e,t,!0)}}}),r._init=!1},n.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!==typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(n.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=n.util.createBuffer();for(var i=0;i>>=2;for(i=0;i>8^255&h^99,o[g]=h,s[h]=g,f=(d=e[h])<<24^h<<16^h<<8^h^d,p=((r=e[g])^(n=e[r])^(i=e[n]))<<24^(g^i)<<16^(g^n^i)<<8^g^r^i;for(var y=0;y<4;++y)c[y][g]=f,u[y][h]=p,f=f<<24|f>>>8,p=p<<24|p>>>8;0===g?g=b=1:(g=r^e[e[e[r^i]]],b^=e[e[b]])}}function f(e,t){for(var r,n=e.slice(0),i=1,s=n.length,c=h*(s+6+1),l=s;l>>16&255]<<24^o[r>>>8&255]<<16^o[255&r]<<8^o[r>>>24]^a[i]<<24,i++):s>6&&l%s===4&&(r=o[r>>>24]<<24^o[r>>>16&255]<<16^o[r>>>8&255]<<8^o[255&r]),n[l]=n[l-s]^r;if(t){for(var d,f=u[0],p=u[1],g=u[2],b=u[3],y=n.slice(0),m=(l=0,(c=n.length)-h);l>>24]]^p[o[d>>>16&255]]^g[o[d>>>8&255]]^b[o[255&d]];n=y}return n}function p(e,t,r,n){var i,a,l,h,d,f,p,g,b,y,m,v,w=e.length/4-1;n?(i=u[0],a=u[1],l=u[2],h=u[3],d=s):(i=c[0],a=c[1],l=c[2],h=c[3],d=o),f=t[0]^e[0],p=t[n?3:1]^e[1],g=t[2]^e[2],b=t[n?1:3]^e[3];for(var _=3,E=1;E>>24]^a[p>>>16&255]^l[g>>>8&255]^h[255&b]^e[++_],m=i[p>>>24]^a[g>>>16&255]^l[b>>>8&255]^h[255&f]^e[++_],v=i[g>>>24]^a[b>>>16&255]^l[f>>>8&255]^h[255&p]^e[++_],b=i[b>>>24]^a[f>>>16&255]^l[p>>>8&255]^h[255&g]^e[++_],f=y,p=m,g=v;r[0]=d[f>>>24]<<24^d[p>>>16&255]<<16^d[g>>>8&255]<<8^d[255&b]^e[++_],r[n?3:1]=d[p>>>24]<<24^d[g>>>16&255]<<16^d[b>>>8&255]<<8^d[255&f]^e[++_],r[2]=d[g>>>24]<<24^d[b>>>16&255]<<16^d[f>>>8&255]<<8^d[255&p]^e[++_],r[n?1:3]=d[b>>>24]<<24^d[f>>>16&255]<<16^d[p>>>8&255]<<8^d[255&g]^e[++_]}function g(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var o=null;r instanceof n.util.ByteBuffer&&(o=r,r={}),(r=r||{}).output=o,r.iv=e,i.call(t,r)},t}},5465:(e,t,r)=>{var n=r(45);r(3900),r(3225);var i=e.exports=n.asn1=n.asn1||{};function o(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}i.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},i.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},i.create=function(e,t,r,o,s){if(n.util.isArray(o)){for(var a=[],c=0;ct){if(n.strict){var p=new Error("Too few bytes to read ASN.1 value.");throw p.available=e.length(),p.remaining=t,p.requested=f,p}f=t}var g=32===(32&c);if(g)if(h=[],void 0===f)for(;;){if(o(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}a=e.length(),h.push(s(e,t,r+1,n)),t-=a-e.length()}else for(;f>0;)a=e.length(),h.push(s(e,f,r+1,n)),t-=a-e.length(),f-=a-e.length();if(void 0===h&&u===i.Class.UNIVERSAL&&l===i.Type.BITSTRING&&(d=e.bytes(f)),void 0===h&&n.decodeBitStrings&&u===i.Class.UNIVERSAL&&l===i.Type.BITSTRING&&f>1){var b=e.read,y=t,m=0;if(l===i.Type.BITSTRING&&(o(e,t,1),m=e.getByte(),t--),0===m)try{a=e.length();var v=s(e,t,r+1,{strict:!0,decodeBitStrings:!0}),w=a-e.length();t-=w,l==i.Type.BITSTRING&&w++;var _=v.tagClass;w!==f||_!==i.Class.UNIVERSAL&&_!==i.Class.CONTEXT_SPECIFIC||(h=[v])}catch(S){}void 0===h&&(e.read=b,t=y)}if(void 0===h){if(void 0===f){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");f=t}if(l===i.Type.BMPSTRING)for(h="";f>0;f-=2)o(e,t,2),h+=String.fromCharCode(e.getInt16()),t-=2;else h=e.getBytes(f),t-=f}var E=void 0===d?null:{bitStringContents:d};return i.create(u,l,g,h,E)}i.fromDer=function(e,t){void 0===t&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"===typeof t&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.length(),i=s(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var o=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw o.byteCount=r,o.remaining=e.length(),o}return i},i.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,o=n.util.createBuffer(),s=!1;if("bitStringContents"in e&&(s=!0,e.original&&(s=i.equals(e,e.original))),s)o.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:o.putByte(0);for(var a=0;a1&&(0===e.value.charCodeAt(0)&&0===(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128===(128&e.value.charCodeAt(1)))?o.putBytes(e.value.substr(1)):o.putBytes(e.value);if(t.putByte(r),o.length()<=127)t.putByte(127&o.length());else{var c=o.length(),u="";do{u+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|u.length);for(a=u.length-1;a>=0;--a)t.putByte(u.charCodeAt(a))}return t.putBuffer(o),t},i.oidToDer=function(e){var t,r,i,o,s=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(s[0],10)+parseInt(s[1],10));for(var c=2;c>>=7,t||(o|=128),r.push(o),t=!1}while(i>0);for(var u=r.length-1;u>=0;--u)a.putByte(r[u])}return a},i.derToOid=function(e){var t;"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var i=0;e.length()>0;)i<<=7,128&(r=e.getByte())?i+=127&r:(t+="."+(i+r),i=0);return t},i.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),o=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),u=10;"+"!==c&&"-"!==c&&(a=parseInt(e.substr(10,2),10),u+=2)}if(t.setUTCFullYear(r,n,i),t.setUTCHours(o,s,a,0),u&&("+"===(c=e.charAt(u))||"-"===c)){var l=60*parseInt(e.substr(u+1,2),10)+parseInt(e.substr(u+4,2),10);l*=6e4,"+"===c?t.setTime(+t-l):t.setTime(+t+l)}return t},i.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;"Z"===e.charAt(e.length-1)&&(l=!0);var h=e.length-5,d=e.charAt(h);"+"!==d&&"-"!==d||(u=60*parseInt(e.substr(h+1,2),10)+parseInt(e.substr(h+4,2),10),u*=6e4,"+"===d&&(u*=-1),l=!0);return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),l?(t.setUTCFullYear(r,n,i),t.setUTCHours(o,s,a,c),t.setTime(+t+u)):(t.setFullYear(r,n,i),t.setHours(o,s,a,c)),t},i.dateToUtcTime=function(e){if("string"===typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},i.derToInteger=function(e){"string"===typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},i.validate=function(e,t,r,o){var s=!1;if(e.tagClass!==t.tagClass&&"undefined"!==typeof t.tagClass||e.type!==t.type&&"undefined"!==typeof t.type)o&&(e.tagClass!==t.tagClass&&o.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&o.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||"undefined"===typeof t.constructed){if(s=!0,t.value&&n.util.isArray(t.value))for(var a=0,c=0;s&&c0&&(o+="\n");for(var s="",c=0;c1?o+="0x"+n.util.bytesToHex(e.value.slice(1)):o+="(none)",e.value.length>0){var d=e.value.charCodeAt(0);1==d?o+=" (1 unused bit shown)":d>1&&(o+=" ("+d+" unused bits shown)")}}else if(e.type===i.Type.OCTETSTRING)a.test(e.value)||(o+="("+e.value+") "),o+="0x"+n.util.bytesToHex(e.value);else if(e.type===i.Type.UTF8)try{o+=n.util.decodeUtf8(e.value)}catch(p){if("URI malformed"!==p.message)throw p;o+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===i.Type.PRINTABLESTRING||e.type===i.Type.IA5String?o+=e.value:a.test(e.value)?o+="0x"+n.util.bytesToHex(e.value):0===e.value.length?o+="[null]":o+=e.value}return o}},6407:e=>{var t={};e.exports=t;var r={};t.encode=function(e,t,r){if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!==typeof r)throw new TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var i=0,o=t.length,s=t.charAt(0),a=[0];for(i=0;i0;)a.push(u%o),u=u/o|0}for(i=0;0===e[i]&&i=0;--i)n+=t[a[i]]}else n=function(e,t){var r=0,n=t.length,i=t.charAt(0),o=[0];for(r=0;r0;)o.push(a%n),a=a/n|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[o[r]];return c}(e,t);if(r){var l=new RegExp(".{1,"+r+"}","g");n=n.match(l).join("\r\n")}return n},t.decode=function(e,t){if("string"!==typeof e)throw new TypeError('"input" must be a string.');if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');var n=r[t];if(!n){n=r[t]=[];for(var i=0;i>=8;for(;l>0;)a.push(255&l),l>>=8}for(var h=0;e[h]===s&&h{var n=r(45);r(3900),e.exports=n.cipher=n.cipher||{},n.cipher.algorithms=n.cipher.algorithms||{},n.cipher.createCipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!1})},n.cipher.createDecipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!0})},n.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),n.cipher.algorithms[e]=t},n.cipher.getAlgorithm=function(e){return(e=e.toUpperCase())in n.cipher.algorithms?n.cipher.algorithms[e]:null};var i=n.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};i.prototype.start=function(e){e=e||{};var t={};for(var r in e)t[r]=e[r];t.decrypt=this._decrypt,this._finish=!1,this._input=n.util.createBuffer(),this.output=e.output||n.util.createBuffer(),this.mode.start(t)},i.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},i.prototype.finish=function(e){!e||"ECB"!==this.mode.name&&"CBC"!==this.mode.name||(this.mode.pad=function(t){return e(this.blockSize,t,!1)},this.mode.unpad=function(t){return e(this.blockSize,t,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t))&&(this._finish=!0,this.update(),!(this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))&&!(this.mode.afterFinish&&!this.mode.afterFinish(this.output,t)))}},1655:(e,t,r)=>{var n=r(45);r(3900),n.cipher=n.cipher||{};var i=e.exports=n.cipher.modes=n.cipher.modes||{};function o(e,t){if("string"===typeof e&&(e=n.util.createBuffer(e)),n.util.isArray(e)&&e.length>4){var r=e;e=n.util.createBuffer();for(var i=0;i0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},i.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=o(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},i.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=o(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=o(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb.prototype.decrypt=i.ofb.prototype.encrypt,i.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=o(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}s(this._inBlock)},i.ctr.prototype.decrypt=i.ctr.prototype.encrypt,i.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},i.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t,r=n.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?n.util.createBuffer(e.additionalData):n.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var i=r.length();if(12===i)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(a(8*i)))}this._inBlock=this._j0.slice(0),s(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var o=t.length()%this.blockSize;for(o&&t.fillWithByte(0,this.blockSize-o),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},i.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),s(this._inBlock)},i.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),s(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},i.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>4*(7-r%8)&15,i=this._m[r][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t},i.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},i.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,i=16*r,o=new Array(i),s=0;s>>1,i=new Array(r);i[n]=e.slice(0);for(var o=n>>>1;o>0;)this.pow(i[2*o],i[o]=[]),o>>=1;for(o=2;o{var n=r(45);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.des.Algorithm(e,t)}))}r(9151),r(1655),r(3900),e.exports=n.des=n.des||{},n.des.startEncrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createEncryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!1,mode:t})},n.des.startDecrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createDecryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!0,mode:t})},n.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return f(r._keys,e,t,!1)},decrypt:function(e,t){return f(r._keys,e,t,!0)}}}),r._init=!1},n.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=n.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw new Error("Invalid Triple-DES key size: "+8*t.length());this._keys=function(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],n=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],o=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],u=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],l=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],p=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],b=e.length()>8?3:1,y=[],m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],v=0,w=0;w>>4^E))<<4,_^=t=65535&((E^=t)>>>-16^_),_^=(t=858993459&(_>>>2^(E^=t<<-16)))<<2,_^=t=65535&((E^=t)>>>-16^_),_^=(t=1431655765&(_>>>1^(E^=t<<-16)))<<1,_^=t=16711935&((E^=t)>>>8^_),t=(_^=(t=1431655765&(_>>>1^(E^=t<<8)))<<1)<<8|(E^=t)>>>20&240,_=E<<24|E<<8&16711680|E>>>8&65280|E>>>24&240,E=t;for(var S=0;S>>26,E=E<<2|E>>>26):(_=_<<1|_>>>27,E=E<<1|E>>>27),E&=-15;var A=r[(_&=-15)>>>28]|n[_>>>24&15]|i[_>>>20&15]|o[_>>>16&15]|s[_>>>12&15]|a[_>>>8&15]|c[_>>>4&15],k=u[E>>>28]|l[E>>>24&15]|h[E>>>20&15]|d[E>>>16&15]|f[E>>>12&15]|p[E>>>8&15]|g[E>>>4&15];t=65535&(k>>>16^A),y[v++]=A^t,y[v++]=k^t<<16}}return y}(t),this._init=!0}},i("DES-ECB",n.cipher.modes.ecb),i("DES-CBC",n.cipher.modes.cbc),i("DES-CFB",n.cipher.modes.cfb),i("DES-OFB",n.cipher.modes.ofb),i("DES-CTR",n.cipher.modes.ctr),i("3DES-ECB",n.cipher.modes.ecb),i("3DES-CBC",n.cipher.modes.cbc),i("3DES-CFB",n.cipher.modes.cfb),i("3DES-OFB",n.cipher.modes.ofb),i("3DES-CTR",n.cipher.modes.ctr);var o=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],s=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],a=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],c=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],u=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],h=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],d=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function f(e,t,r,n){var i,f,p=32===e.length?3:9;i=3===p?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],b=t[1];g^=(f=252645135&(g>>>4^b))<<4,g^=(f=65535&(g>>>16^(b^=f)))<<16,g^=f=858993459&((b^=f)>>>2^g),g^=f=16711935&((b^=f<<2)>>>8^g),g=(g^=(f=1431655765&(g>>>1^(b^=f<<8)))<<1)<<1|g>>>31,b=(b^=f)<<1|b>>>31;for(var y=0;y>>4|b<<28)^e[w+1];f=g,g=b,b=f^(s[_>>>24&63]|c[_>>>16&63]|l[_>>>8&63]|d[63&_]|o[E>>>24&63]|a[E>>>16&63]|u[E>>>8&63]|h[63&E])}f=g,g=b,b=f}b=b>>>1|b<<31,b^=f=1431655765&((g=g>>>1|g<<31)>>>1^b),b^=(f=16711935&(b>>>8^(g^=f<<1)))<<8,b^=(f=858993459&(b>>>2^(g^=f)))<<2,b^=f=65535&((g^=f)>>>16^b),b^=f=252645135&((g^=f<<16)>>>4^b),g^=f<<4,r[0]=g,r[1]=b}function p(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var o=null;r instanceof n.util.ByteBuffer&&(o=r,r={}),(r=r||{}).output=o,r.iv=e,i.call(t,r)},t}},45:e=>{e.exports={options:{usePureJavaScript:!1}}},8163:(e,t,r)=>{var n=r(45);r(5693),r(3900),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,i=null,o={start:function(o,s){if(null!==o)if("string"===typeof o){if(!((o=o.toLowerCase())in n.md.algorithms))throw new Error('Unknown hash algorithm "'+o+'"');t=n.md.algorithms[o].create()}else t=o;if(null===s)s=e;else{if("string"===typeof s)s=n.util.createBuffer(s);else if(n.util.isArray(s)){var a=s;s=n.util.createBuffer();for(var c=0;ct.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),r=n.util.createBuffer(),i=n.util.createBuffer(),u=s.length();for(c=0;c{var n,i=r(45);e.exports=i.jsbn=i.jsbn||{};function o(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function s(){return new o(null)}function a(e,t,r,n,i,o){for(var s=16383&t,a=t>>14;--o>=0;){var c=16383&this.data[e],u=this.data[e++]>>14,l=a*c+u*s;i=((c=s*c+((16383&l)<<14)+r.data[n]+i)>>28)+(l>>14)+a*u,r.data[n++]=268435455&c}return i}i.jsbn.BigInteger=o,"undefined"===typeof navigator?(o.prototype.am=a,n=28):"Microsoft Internet Explorer"==navigator.appName?(o.prototype.am=function(e,t,r,n,i,o){for(var s=32767&t,a=t>>15;--o>=0;){var c=32767&this.data[e],u=this.data[e++]>>15,l=a*c+u*s;i=((c=s*c+((32767&l)<<15)+r.data[n]+(1073741823&i))>>>30)+(l>>>15)+a*u+(i>>>30),r.data[n++]=1073741823&c}return i},n=30):"Netscape"!=navigator.appName?(o.prototype.am=function(e,t,r,n,i,o){for(;--o>=0;){var s=t*this.data[e++]+r.data[n]+i;i=Math.floor(s/67108864),r.data[n++]=67108863&s}return i},n=26):(o.prototype.am=a,n=28),o.prototype.DB=n,o.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function b(e){this.m=e}function y(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function S(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function A(){}function k(e){return e}function x(e){this.r2=s(),this.q3=s(),o.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}b.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},b.prototype.revert=function(e){return e},b.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},b.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},b.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},y.prototype.convert=function(e){var t=s();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(o.ZERO)>0&&this.m.subTo(t,t),t},y.prototype.revert=function(e){var t=s();return e.copyTo(t),this.reduce(t),t},y.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},o.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},o.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},o.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,s=0;--n>=0;){var a=8==r?255&e[n]:f(e,n);a<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==s?this.data[this.t++]=a:s+r>this.DB?(this.data[this.t-1]|=(a&(1<>this.DB-s):this.data[this.t-1]|=a<=this.DB&&(s-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},o.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},o.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+s+1]=this.data[r]>>i|a,a=(this.data[r]&o)<=0;--r)t.data[r]=0;t.data[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()},o.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,o=(1<>n;for(var s=r+1;s>n;n>0&&(t.data[this.t-r-1]|=(this.s&o)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()},o.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t.data[i]=0;for(i=0;i=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},o.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(l,a),i.lShiftTo(l,r)):(n.copyTo(a),i.copyTo(r));var h=a.t,d=a.data[h-1];if(0!=d){var f=d*(1<1?a.data[h-2]>>this.F2:0),p=this.FV/f,b=(1<=0&&(r.data[r.t++]=1,r.subTo(w,r)),o.ONE.dlShiftTo(h,w),w.subTo(a,a);a.t=0;){var _=r.data[--m]==d?this.DM:Math.floor(r.data[m]*p+(r.data[m-1]+y)*b);if((r.data[m]+=a.am(0,_,r,v,0,h))<_)for(a.dlShiftTo(v,w),r.subTo(w,r);r.data[m]<--_;)r.subTo(w,r)}null!=t&&(r.drShiftTo(h,t),c!=u&&o.ZERO.subTo(t,t)),r.t=h,r.clamp(),l>0&&r.rShiftTo(l,r),c<0&&o.ZERO.subTo(r,r)}}},o.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},o.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},o.prototype.exp=function(e,t){if(e>4294967295||e<1)return o.ONE;var r=s(),n=s(),i=t.convert(this),a=g(e)-1;for(i.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var c=r;r=n,n=c}return t.revert(r)},o.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,o=d(r));s>=0;)a>(a+=this.DB-t)):(r=this.data[s]>>(a-=t)&n,a<=0&&(a+=this.DB,--s)),r>0&&(i=!0),i&&(o+=d(r));return i?o:"0"},o.prototype.negate=function(){var e=s();return o.ZERO.subTo(this,e),e},o.prototype.abs=function(){return this.s<0?this.negate():this},o.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},o.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+g(this.data[this.t-1]^this.s&this.DM)},o.prototype.mod=function(e){var t=s();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(o.ZERO)>0&&e.subTo(t,t),t},o.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new b(t):new y(t),this.exp(e,r)},o.ZERO=p(0),o.ONE=p(1),A.prototype.convert=k,A.prototype.revert=k,A.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},A.prototype.sqrTo=function(e,t){e.squareTo(t)},x.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=s();return e.copyTo(t),this.reduce(t),t},x.prototype.revert=function(e){return e},x.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},x.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},x.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var I=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],C=(1<<26)/I[I.length-1];o.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},o.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=p(r),i=s(),o=s(),a="";for(this.divRemTo(n,i,o);i.signum()>0;)a=(r+o.intValue()).toString(e).substr(1)+a,i.divRemTo(n,i,o);return o.intValue().toString(e)+a},o.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,s=0,a=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(a,0),s=0,a=0))}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(a,0)),i&&o.ZERO.subTo(this,this)},o.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(o.ONE.shiftLeft(e-1),v,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(o.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()},o.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},o.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},o.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r.data[--i]=0;for(n=r.t-this.t;i=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n0)if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r},o.prototype.millerRabin=function(e){var t=this.subtract(o.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n,i=t.shiftRight(r),s={nextBytes:function(e){for(var t=0;t=0);var c=n.modPow(i,this);if(0!=c.compareTo(o.ONE)&&0!=c.compareTo(t)){for(var u=1;u++>24},o.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},o.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},o.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},o.prototype.equals=function(e){return 0==this.compareTo(e)},o.prototype.min=function(e){return this.compareTo(e)<0?this:e},o.prototype.max=function(e){return this.compareTo(e)>0?this:e},o.prototype.and=function(e){var t=s();return this.bitwiseTo(e,m,t),t},o.prototype.or=function(e){var t=s();return this.bitwiseTo(e,v,t),t},o.prototype.xor=function(e){var t=s();return this.bitwiseTo(e,w,t),t},o.prototype.andNot=function(e){var t=s();return this.bitwiseTo(e,_,t),t},o.prototype.not=function(){for(var e=s(),t=0;t=this.t?0!=this.s:0!=(this.data[t]&1<1){var h=s();for(n.sqrTo(a[1],h);c<=l;)a[c]=s(),n.mulTo(h,a[c-2],a[c]),c+=2}var d,f,m=e.t-1,v=!0,w=s();for(i=g(e.data[m])-1;m>=0;){for(i>=u?d=e.data[m]>>i-u&l:(d=(e.data[m]&(1<0&&(d|=e.data[m-1]>>this.DB+i-u)),c=r;0==(1&d);)d>>=1,--c;if((i-=c)<0&&(i+=this.DB,--m),v)a[d].copyTo(o),v=!1;else{for(;c>1;)n.sqrTo(o,w),n.sqrTo(w,o),c-=2;c>0?n.sqrTo(o,w):(f=o,o=w,w=f),n.mulTo(w,a[d],o)}for(;m>=0&&0==(e.data[m]&1<=0?(r.subTo(n,r),t&&i.subTo(a,i),s.subTo(c,s)):(n.subTo(r,n),t&&a.subTo(i,a),c.subTo(s,c))}return 0!=n.compareTo(o.ONE)?o.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},o.prototype.pow=function(e){return this.exp(e,new A)},o.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),o=r.getLowestSetBit();if(o<0)return t;for(i0&&(t.rShiftTo(o,t),r.rShiftTo(o,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return o>0&&r.lShiftTo(o,r),r},o.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=I[I.length-1]){for(t=0;t{var n=r(45);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},3225:(e,t,r)=>{var n=r(45);n.pki=n.pki||{};var i=e.exports=n.pki.oids=n.oids=n.oids||{};function o(e,t){i[e]=t,i[t]=e}function s(e,t){i[e]=t}o("1.2.840.113549.1.1.1","rsaEncryption"),o("1.2.840.113549.1.1.4","md5WithRSAEncryption"),o("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),o("1.2.840.113549.1.1.7","RSAES-OAEP"),o("1.2.840.113549.1.1.8","mgf1"),o("1.2.840.113549.1.1.9","pSpecified"),o("1.2.840.113549.1.1.10","RSASSA-PSS"),o("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),o("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),o("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),o("1.3.101.112","EdDSA25519"),o("1.2.840.10040.4.3","dsa-with-sha1"),o("1.3.14.3.2.7","desCBC"),o("1.3.14.3.2.26","sha1"),o("1.3.14.3.2.29","sha1WithRSASignature"),o("2.16.840.1.101.3.4.2.1","sha256"),o("2.16.840.1.101.3.4.2.2","sha384"),o("2.16.840.1.101.3.4.2.3","sha512"),o("2.16.840.1.101.3.4.2.4","sha224"),o("2.16.840.1.101.3.4.2.5","sha512-224"),o("2.16.840.1.101.3.4.2.6","sha512-256"),o("1.2.840.113549.2.2","md2"),o("1.2.840.113549.2.5","md5"),o("1.2.840.113549.1.7.1","data"),o("1.2.840.113549.1.7.2","signedData"),o("1.2.840.113549.1.7.3","envelopedData"),o("1.2.840.113549.1.7.4","signedAndEnvelopedData"),o("1.2.840.113549.1.7.5","digestedData"),o("1.2.840.113549.1.7.6","encryptedData"),o("1.2.840.113549.1.9.1","emailAddress"),o("1.2.840.113549.1.9.2","unstructuredName"),o("1.2.840.113549.1.9.3","contentType"),o("1.2.840.113549.1.9.4","messageDigest"),o("1.2.840.113549.1.9.5","signingTime"),o("1.2.840.113549.1.9.6","counterSignature"),o("1.2.840.113549.1.9.7","challengePassword"),o("1.2.840.113549.1.9.8","unstructuredAddress"),o("1.2.840.113549.1.9.14","extensionRequest"),o("1.2.840.113549.1.9.20","friendlyName"),o("1.2.840.113549.1.9.21","localKeyId"),o("1.2.840.113549.1.9.22.1","x509Certificate"),o("1.2.840.113549.1.12.10.1.1","keyBag"),o("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),o("1.2.840.113549.1.12.10.1.3","certBag"),o("1.2.840.113549.1.12.10.1.4","crlBag"),o("1.2.840.113549.1.12.10.1.5","secretBag"),o("1.2.840.113549.1.12.10.1.6","safeContentsBag"),o("1.2.840.113549.1.5.13","pkcs5PBES2"),o("1.2.840.113549.1.5.12","pkcs5PBKDF2"),o("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),o("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),o("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),o("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),o("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),o("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),o("1.2.840.113549.2.7","hmacWithSHA1"),o("1.2.840.113549.2.8","hmacWithSHA224"),o("1.2.840.113549.2.9","hmacWithSHA256"),o("1.2.840.113549.2.10","hmacWithSHA384"),o("1.2.840.113549.2.11","hmacWithSHA512"),o("1.2.840.113549.3.7","des-EDE3-CBC"),o("2.16.840.1.101.3.4.1.2","aes128-CBC"),o("2.16.840.1.101.3.4.1.22","aes192-CBC"),o("2.16.840.1.101.3.4.1.42","aes256-CBC"),o("2.5.4.3","commonName"),o("2.5.4.4","surname"),o("2.5.4.5","serialNumber"),o("2.5.4.6","countryName"),o("2.5.4.7","localityName"),o("2.5.4.8","stateOrProvinceName"),o("2.5.4.9","streetAddress"),o("2.5.4.10","organizationName"),o("2.5.4.11","organizationalUnitName"),o("2.5.4.12","title"),o("2.5.4.13","description"),o("2.5.4.15","businessCategory"),o("2.5.4.17","postalCode"),o("2.5.4.42","givenName"),o("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),o("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),o("2.16.840.1.113730.1.1","nsCertType"),o("2.16.840.1.113730.1.13","nsComment"),s("2.5.29.1","authorityKeyIdentifier"),s("2.5.29.2","keyAttributes"),s("2.5.29.3","certificatePolicies"),s("2.5.29.4","keyUsageRestriction"),s("2.5.29.5","policyMapping"),s("2.5.29.6","subtreesConstraint"),s("2.5.29.7","subjectAltName"),s("2.5.29.8","issuerAltName"),s("2.5.29.9","subjectDirectoryAttributes"),s("2.5.29.10","basicConstraints"),s("2.5.29.11","nameConstraints"),s("2.5.29.12","policyConstraints"),s("2.5.29.13","basicConstraints"),o("2.5.29.14","subjectKeyIdentifier"),o("2.5.29.15","keyUsage"),s("2.5.29.16","privateKeyUsagePeriod"),o("2.5.29.17","subjectAltName"),o("2.5.29.18","issuerAltName"),o("2.5.29.19","basicConstraints"),s("2.5.29.20","cRLNumber"),s("2.5.29.21","cRLReason"),s("2.5.29.22","expirationDate"),s("2.5.29.23","instructionCode"),s("2.5.29.24","invalidityDate"),s("2.5.29.25","cRLDistributionPoints"),s("2.5.29.26","issuingDistributionPoint"),s("2.5.29.27","deltaCRLIndicator"),s("2.5.29.28","issuingDistributionPoint"),s("2.5.29.29","certificateIssuer"),s("2.5.29.30","nameConstraints"),o("2.5.29.31","cRLDistributionPoints"),o("2.5.29.32","certificatePolicies"),s("2.5.29.33","policyMappings"),s("2.5.29.34","policyConstraints"),o("2.5.29.35","authorityKeyIdentifier"),s("2.5.29.36","policyConstraints"),o("2.5.29.37","extKeyUsage"),s("2.5.29.46","freshestCRL"),s("2.5.29.54","inhibitAnyPolicy"),o("1.3.6.1.4.1.11129.2.4.2","timestampList"),o("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),o("1.3.6.1.5.5.7.3.1","serverAuth"),o("1.3.6.1.5.5.7.3.2","clientAuth"),o("1.3.6.1.5.5.7.3.3","codeSigning"),o("1.3.6.1.5.5.7.3.4","emailProtection"),o("1.3.6.1.5.5.7.3.8","timeStamping")},3555:(e,t,r)=>{var n=r(45);if(r(9353),r(5465),r(2986),r(5693),r(3225),r(8009),r(5224),r(2795),r(1577),r(9408),r(3900),"undefined"===typeof i)var i=n.jsbn.BigInteger;var o=n.asn1,s=n.pki=n.pki||{};e.exports=s.pbe=n.pbe=n.pbe||{};var a=s.oids,c={name:"EncryptedPrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},u={name:"PBES2Algorithms",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},l={name:"pkcs-12PbeParams",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"iterations"}]};function h(e,t){return e.start().update(t).digest().getBytes()}function d(e){var t;if(e){if(!(t=s.oids[o.derToOid(e)])){var r=new Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}}else t="hmacWithSHA1";return f(t)}function f(e){var t=n.md;switch(e){case"hmacWithSHA224":t=n.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}s.encryptPrivateKeyInfo=function(e,t,r){(r=r||{}).saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var i,c,u,l=n.random.getBytesSync(r.saltSize),h=r.count,d=o.integerToDer(h);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){var p,g,b;switch(r.algorithm){case"aes128":i=16,p=16,g=a["aes128-CBC"],b=n.aes.createEncryptionCipher;break;case"aes192":i=24,p=16,g=a["aes192-CBC"],b=n.aes.createEncryptionCipher;break;case"aes256":i=32,p=16,g=a["aes256-CBC"],b=n.aes.createEncryptionCipher;break;case"des":i=8,p=8,g=a.desCBC,b=n.des.createEncryptionCipher;break;default:throw(E=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,E}var y="hmacWith"+r.prfAlgorithm.toUpperCase(),m=f(y),v=n.pkcs5.pbkdf2(t,l,h,i,m),w=n.random.getBytesSync(p);(S=b(v)).start(w),S.update(o.toDer(e)),S.finish(),u=S.output.getBytes();var _=function(e,t,r,i){var a=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,e),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,t.getBytes())]);"hmacWithSHA1"!==i&&a.value.push(o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,n.util.hexToBytes(r.toString(16))),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(s.oids[i]).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]));return a}(l,d,i,y);c=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(a.pkcs5PBES2).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(a.pkcs5PBKDF2).getBytes()),_]),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(g).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,w)])])])}else{var E;if("3des"!==r.algorithm)throw(E=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,E;i=24;var S,A=new n.util.ByteBuffer(l);v=s.pbe.generatePkcs12Key(t,A,1,h,i),w=s.pbe.generatePkcs12Key(t,A,2,h,i);(S=n.des.createEncryptionCipher(v)).start(w),S.update(o.toDer(e)),S.finish(),u=S.output.getBytes(),c=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(a["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,l),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,d.getBytes())])])}return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[c,o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,u)])},s.decryptPrivateKeyInfo=function(e,t){var r=null,i={},a=[];if(!o.validate(e,c,i,a)){var u=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw u.errors=a,u}var l=o.derToOid(i.encryptionOid),h=s.pbe.getCipher(l,i.encryptionParams,t),d=n.util.createBuffer(i.encryptedData);return h.update(d),h.finish()&&(r=o.fromDer(h.output)),r},s.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:o.toDer(e).getBytes()};return n.pem.encode(r,{maxline:t})},s.encryptedPrivateKeyFromPem=function(e){var t=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==t.type){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return o.fromDer(t.body)},s.encryptRsaPrivateKey=function(e,t,r){if(!(r=r||{}).legacy){var i=s.wrapRsaPrivateKey(s.privateKeyToAsn1(e));return i=s.encryptPrivateKeyInfo(i,t,r),s.encryptedPrivateKeyToPem(i)}var a,c,u,l;switch(r.algorithm){case"aes128":a="AES-128-CBC",u=16,c=n.random.getBytesSync(16),l=n.aes.createEncryptionCipher;break;case"aes192":a="AES-192-CBC",u=24,c=n.random.getBytesSync(16),l=n.aes.createEncryptionCipher;break;case"aes256":a="AES-256-CBC",u=32,c=n.random.getBytesSync(16),l=n.aes.createEncryptionCipher;break;case"3des":a="DES-EDE3-CBC",u=24,c=n.random.getBytesSync(8),l=n.des.createEncryptionCipher;break;case"des":a="DES-CBC",u=8,c=n.random.getBytesSync(8),l=n.des.createEncryptionCipher;break;default:var h=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw h.algorithm=r.algorithm,h}var d=l(n.pbe.opensslDeriveBytes(t,c.substr(0,8),u));d.start(c),d.update(o.toDer(s.privateKeyToAsn1(e))),d.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:a,parameters:n.util.bytesToHex(c).toUpperCase()},body:d.output.getBytes()};return n.pem.encode(f)},s.decryptRsaPrivateKey=function(e,t){var r=null,i=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==i.type&&"PRIVATE KEY"!==i.type&&"RSA PRIVATE KEY"!==i.type)throw(u=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=u,u;if(i.procType&&"ENCRYPTED"===i.procType.type){var a,c;switch(i.dekInfo.algorithm){case"DES-CBC":a=8,c=n.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,c=n.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,c=n.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,c=n.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,c=n.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,c=function(e){return n.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":a=8,c=function(e){return n.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":a=16,c=function(e){return n.rc2.createDecryptionCipher(e,128)};break;default:var u;throw(u=new Error('Could not decrypt private key; unsupported encryption algorithm "'+i.dekInfo.algorithm+'".')).algorithm=i.dekInfo.algorithm,u}var l=n.util.hexToBytes(i.dekInfo.parameters),h=c(n.pbe.opensslDeriveBytes(t,l.substr(0,8),a));if(h.start(l),h.update(n.util.createBuffer(i.body)),!h.finish())return r;r=h.output.getBytes()}else r=i.body;return null!==(r="ENCRYPTED PRIVATE KEY"===i.type?s.decryptPrivateKeyInfo(o.fromDer(r),t):o.fromDer(r))&&(r=s.privateKeyFromAsn1(r)),r},s.pbe.generatePkcs12Key=function(e,t,r,i,o,s){var a,c;if("undefined"===typeof s||null===s){if(!("sha1"in n.md))throw new Error('"sha1" hash algorithm unavailable.');s=n.md.sha1.create()}var u=s.digestLength,l=s.blockLength,h=new n.util.ByteBuffer,d=new n.util.ByteBuffer;if(null!==e&&void 0!==e){for(c=0;c=0;c--)T>>=8,T+=k.at(c)+C.at(c),C.setAt(c,255&T);I.putBuffer(C)}w=I,h.putBuffer(S)}return h.truncate(h.length()-o),h},s.pbe.getCipher=function(e,t,r){switch(e){case s.oids.pkcs5PBES2:return s.pbe.getCipherForPBES2(e,t,r);case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case s.oids["pbewithSHAAnd40BitRC2-CBC"]:return s.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},s.pbe.getCipherForPBES2=function(e,t,r){var i,a={},c=[];if(!o.validate(t,u,a,c))throw(i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,i;if((e=o.derToOid(a.kdfOid))!==s.oids.pkcs5PBKDF2)throw(i=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,i.supportedOids=["pkcs5PBKDF2"],i;if((e=o.derToOid(a.encOid))!==s.oids["aes128-CBC"]&&e!==s.oids["aes192-CBC"]&&e!==s.oids["aes256-CBC"]&&e!==s.oids["des-EDE3-CBC"]&&e!==s.oids.desCBC)throw(i=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,i.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],i;var l,h,f=a.kdfSalt,p=n.util.createBuffer(a.kdfIterationCount);switch(p=p.getInt(p.length()<<3),s.oids[e]){case"aes128-CBC":l=16,h=n.aes.createDecryptionCipher;break;case"aes192-CBC":l=24,h=n.aes.createDecryptionCipher;break;case"aes256-CBC":l=32,h=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":l=24,h=n.des.createDecryptionCipher;break;case"desCBC":l=8,h=n.des.createDecryptionCipher}var g=d(a.prfOid),b=n.pkcs5.pbkdf2(r,f,p,l,g),y=a.encIv,m=h(b);return m.start(y),m},s.pbe.getCipherForPKCS12PBE=function(e,t,r){var i={},a=[];if(!o.validate(t,l,i,a))throw(g=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=a,g;var c,u,h,f=n.util.createBuffer(i.salt),p=n.util.createBuffer(i.iterations);switch(p=p.getInt(p.length()<<3),e){case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,h=n.des.startDecrypting;break;case s.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,h=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var g;throw(g=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,g}var b=d(i.prfOid),y=s.pbe.generatePkcs12Key(r,f,1,p,c,b);return b.start(),h(y,s.pbe.generatePkcs12Key(r,f,2,p,u,b))},s.pbe.opensslDeriveBytes=function(e,t,r,i){if("undefined"===typeof i||null===i){if(!("md5"in n.md))throw new Error('"md5" hash algorithm unavailable.');i=n.md.md5.create()}null===t&&(t="");for(var o=[h(i,e+t)],s=16,a=1;s{var n=r(45);r(8163),r(5693),r(3900);var i,o=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(i=r(310)),e.exports=n.pbkdf2=o.pbkdf2=function(e,t,r,o,s,a){if("function"===typeof s&&(a=s,s=null),n.util.isNodejs&&!n.options.usePureJavaScript&&i.pbkdf2&&(null===s||"object"!==typeof s)&&(i.pbkdf2Sync.length>4||!s||"sha1"===s))return"string"!==typeof s&&(s="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),a?4===i.pbkdf2Sync.length?i.pbkdf2(e,t,r,o,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):i.pbkdf2(e,t,r,o,s,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):4===i.pbkdf2Sync.length?i.pbkdf2Sync(e,t,r,o).toString("binary"):i.pbkdf2Sync(e,t,r,o,s).toString("binary");if("undefined"!==typeof s&&null!==s||(s="sha1"),"string"===typeof s){if(!(s in n.md.algorithms))throw new Error("Unknown hash algorithm: "+s);s=n.md[s].create()}var c=s.digestLength;if(o>4294967295*c){var u=new Error("Derived key is too long.");if(a)return a(u);throw u}var l=Math.ceil(o/c),h=o-(l-1)*c,d=n.hmac.create();d.start(s,e);var f,p,g,b="";if(!a){for(var y=1;y<=l;++y){d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(y)),f=g=d.digest().getBytes();for(var m=2;m<=r;++m)d.start(null,null),d.update(g),p=d.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p;b+=yl)return a(null,b);d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(y)),f=g=d.digest().getBytes(),m=2,w()}function w(){if(m<=r)return d.start(null,null),d.update(g),p=d.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p,++m,n.util.setImmediate(w);b+=y{var n=r(45);r(3900);var i=e.exports=n.pem=n.pem||{};function o(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},i=0;i65&&-1!==s){var a=t[s];","===a?(++s,t=t.substr(0,s)+"\r\n "+t.substr(s)):t=t.substr(0,s)+"\r\n"+a+t.substr(s+1),o=i-s-1,s=-1,++i}else" "!==t[i]&&"\t"!==t[i]&&","!==t[i]||(s=i);return t}function s(e){return e.replace(/^\s+/,"")}i.encode=function(e,t){t=t||{};var r,i="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(i+=o(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(i+=o(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),i+=o(r)),e.headers)for(var s=0;s{var n=r(45);r(3900),r(2795),r(3753);var i=e.exports=n.pkcs1=n.pkcs1||{};function o(e,t,r){r||(r=n.md.sha1.create());for(var i="",o=Math.ceil(t/r.digestLength),s=0;s>24&255,s>>16&255,s>>8&255,255&s);r.start(),r.update(e+a),i+=r.digest().getBytes()}return i.substring(0,t)}i.encode_rsa_oaep=function(e,t,r){var i,s,a,c;"string"===typeof r?(i=r,s=arguments[3]||void 0,a=arguments[4]||void 0):r&&(i=r.label||void 0,s=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),c||(c=a);var u=Math.ceil(e.n.bitLength()/8),l=u-2*a.digestLength-2;if(t.length>l)throw(b=new Error("RSAES-OAEP input message length is too long.")).length=t.length,b.maxLength=l,b;i||(i=""),a.update(i,"raw");for(var h=a.digest(),d="",f=l-t.length,p=0;p{var n=r(45);r(3900),r(9463),r(2795),function(){if(n.prime)e.exports=n.prime;else{var t=e.exports=n.prime=n.prime||{},r=n.jsbn.BigInteger,i=[6,4,2,4,2,4,6,2],o=new r(null);o.fromInt(30);var s=function(e,t){return e|t};t.generateProbablePrime=function(e,t,i){"function"===typeof t&&(i=t,t={});var o=(t=t||{}).algorithm||"PRIMEINC";"string"===typeof o&&(o={name:o}),o.options=o.options||{};var s=t.prng||n.random,c={nextBytes:function(e){for(var t=s.getBytesSync(e.length),r=0;re&&(s=u(e,t));var f=s.toString(16);i.target.postMessage({hex:f,workLoad:l}),s.dAddOffset(h,0)}}}f()}(e,t,i,o);return a(e,t,i,o)}(e,c,o.options,i);throw new Error("Invalid prime generation algorithm: "+o.name)}}function a(e,t,r,n){var i=u(e,t),o=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(i.bitLength());"millerRabinTests"in r&&(o=r.millerRabinTests);var s=10;"maxBlockTime"in r&&(s=r.maxBlockTime),c(i,e,t,0,o,s,n)}function c(e,t,r,o,s,a,l){var h=+new Date;do{if(e.bitLength()>t&&(e=u(t,r)),e.isProbablePrime(s))return l(null,e);e.dAddOffset(i[o++%8],0)}while(a<0||+new Date-h{var n=r(45);r(3900);var i=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(i=r(310)),(e.exports=n.prng=n.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,o=new Array(32),s=0;s<32;++s)o[s]=r.create();function a(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,n=0;n<32;++n)t.reseeds%r===0&&(e.update(t.pools[n].digest().getBytes()),t.pools[n].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var i=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(i),t.generated=0}function u(e){var t=null,r=n.util.globalScope,i=r.crypto||r.msCrypto;i&&i.getRandomValues&&(t=function(e){return i.getRandomValues(e)});var o=n.util.createBuffer();if(t)for(;o.length()>16)))<<16,d=4294967295&(l=(2147483647&(l+=u>>15))+(l>>31));for(c=0;c<3;++c)h=d>>>(c<<3),h^=Math.floor(256*Math.random()),o.putByte(255&h)}return o.getBytes(e)}return t.pools=o,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var i=t.plugin.cipher,o=t.plugin.increment,s=t.plugin.formatKey,a=t.plugin.formatSeed,u=n.util.createBuffer();t.key=null,function l(h){if(h)return r(h);if(u.length()>=e)return r(null,u.getBytes(e));t.generated>1048575&&(t.key=null);if(null===t.key)return n.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,n){if(r)return e(r);t.collect(n),c(),e()}))}(l)}));var d=i(t.key,t.seed);t.generated+=d.length,u.putBytes(d),t.key=s(i(t.key,o(t.seed))),t.seed=a(i(t.key,t.seed)),n.util.setImmediate(l)}()},t.generateSync=function(e){var r=t.plugin.cipher,i=t.plugin.increment,o=t.plugin.formatKey,s=t.plugin.formatSeed;t.key=null;for(var c=n.util.createBuffer();c.length()1048575&&(t.key=null),null===t.key&&a();var u=r(t.key,t.seed);t.generated+=u.length,c.putBytes(u),t.key=o(r(t.key,i(t.seed))),t.seed=s(r(t.key,t.seed))}return c.getBytes(e)},i?(t.seedFile=function(e,t){i.randomBytes(e,(function(e,r){if(e)return t(e);t(null,r.toString())}))},t.seedFileSync=function(e){return i.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,u(e))}catch(r){t(r)}},t.seedFileSync=u),t.collect=function(e){for(var r=e.length,n=0;n>i&255);t.collect(n)},t.registerWorker=function(e){if(e===self)t.seedFile=function(e,t){self.addEventListener("message",(function e(r){var n=r.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",e),t(n.forge.prng.err,n.forge.prng.bytes))})),self.postMessage({forge:{prng:{needed:e}}})};else{e.addEventListener("message",(function(r){var n=r.data;n.forge&&n.forge.prng&&t.seedFile(n.forge.prng.needed,(function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})}))}))}},t}},2795:(e,t,r)=>{var n=r(45);r(9353),r(3899),r(1513),r(3900),n.random&&n.random.getBytes?e.exports=n.random:function(t){var r={},i=new Array(4),o=n.util.createBuffer();function s(){var e=n.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),n.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return n.aes._updateBlock(e,t,i,!1),o.putInt32(i[0]),o.putInt32(i[1]),o.putInt32(i[2]),o.putInt32(i[3]),o.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=s(),c=null,u=n.util.globalScope,l=u.crypto||u.msCrypto;if(l&&l.getRandomValues&&(c=function(e){return l.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!c){if("undefined"===typeof window||window.document,a.collectInt(+new Date,32),"undefined"!==typeof navigator){var h="";for(var d in navigator)try{"string"==typeof navigator[d]&&(h+=navigator[d])}catch(f){}a.collect(h),h=null}t&&(t().mousemove((function(e){a.collectInt(e.clientX,16),a.collectInt(e.clientY,16)})),t().keypress((function(e){a.collectInt(e.charCode,8)})))}if(n.random)for(var d in a)n.random[d]=a[d];else n.random=a;n.random.createInstance=s,e.exports=n.random}("undefined"!==typeof jQuery?jQuery:null)},1577:(e,t,r)=>{var n=r(45);r(3900);var i=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],o=[1,2,3,5],s=function(e,t){return e<>16-t},a=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"===typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,o=e,s=e.length(),a=t,c=Math.ceil(a/8),u=255>>(7&a);for(r=s;r<128;r++)o.putByte(i[o.at(r-1)+o.at(r-s)&255]);for(o.setAt(128-c,i[o.at(128-c)&u]),r=127-c;r>=0;r--)o.setAt(r,i[o.at(r+1)^o.at(r+c)]);return o};var c=function(e,t,r){var i,c,u,l,h=!1,d=null,f=null,p=null,g=[];for(e=n.rc2.expandKey(e,t),u=0;u<64;u++)g.push(e.getInt16Le());r?(i=function(e){for(u=0;u<4;u++)e[u]+=g[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),e[u]=s(e[u],o[u]),l++},c=function(e){for(u=0;u<4;u++)e[u]+=g[63&e[(u+3)%4]]}):(i=function(e){for(u=3;u>=0;u--)e[u]=a(e[u],o[u]),e[u]-=g[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),l--},c=function(e){for(u=3;u>=0;u--)e[u]-=g[63&e[(u+3)%4]]});var b=function(e){var t=[];for(u=0;u<4;u++){var n=d.getInt16Le();null!==p&&(r?n^=p.getInt16Le():p.putInt16Le(n)),t.push(65535&n)}l=r?0:63;for(var i=0;i=8;)b([[5,i],[1,c],[6,i],[1,c],[5,i]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,d,!r);else{var n=8===d.length()?8:8-d.length();d.fillWithByte(n,n)}if(t&&(h=!0,y.update()),!r&&(t=0===d.length()))if(e)t=e(8,f,!r);else{var i=f.length(),o=f.at(i-1);o>i?t=!1:f.truncate(o)}return t}}};n.rc2.startEncrypting=function(e,t,r){var i=n.rc2.createEncryptionCipher(e,128);return i.start(t,r),i},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var i=n.rc2.createDecryptionCipher(e,128);return i.start(t,r),i},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},9408:(e,t,r)=>{var n=r(45);if(r(5465),r(9463),r(3225),r(7668),r(8353),r(2795),r(3900),"undefined"===typeof i)var i=n.jsbn.BigInteger;var o=n.util.isNodejs?r(310):null,s=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var c=n.pki,u=[6,4,2,4,2,4,6,2],l={name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},h={name:"RSAPrivateKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},d={name:"RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},f=n.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},p={name:"DigestInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:s.Class.UNIVERSAL,type:s.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},g=function(e){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var n=s.oidToDer(t).getBytes(),i=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]),o=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]);o.value.push(s.create(s.Class.UNIVERSAL,s.Type.OID,!1,n)),o.value.push(s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,""));var a=s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(o),i.value.push(a),s.toDer(i).getBytes()},b=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var o;t.dP||(t.dP=t.d.mod(t.p.subtract(i.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(i.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{o=new i(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16)}while(o.compareTo(t.n)>=0||!o.gcd(t.n).equals(i.ONE));for(var s=(e=e.multiply(o.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);s.compareTo(a)<0;)s=s.add(t.p);var c=s.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return c=c.multiply(o.modInverse(t.n)).mod(t.n)};function y(e,t,r){var i=n.util.createBuffer(),o=Math.ceil(t.n.bitLength()/8);if(e.length>o-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=e.length,s.max=o-11,s}i.putByte(0),i.putByte(r);var a,c=o-3-e.length;if(0===r||1===r){a=0===r?0:255;for(var u=0;u0;){var l=0,h=n.random.getBytes(c);for(u=0;u1;){if(255!==s.getByte()){--s.read;break}++u}else if(2===c)for(u=0;s.length()>1;){if(0===s.getByte()){--s.read;break}++u}if(0!==s.getByte()||u!==o-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function v(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=n.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&0===(128&r.charCodeAt(1))||255===r.charCodeAt(0)&&128===(128&r.charCodeAt(1)))?r.substr(1):r}function w(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function _(e){return n.util.isNodejs&&"function"===typeof o[e]}function E(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.crypto&&"object"===typeof a.globalScope.crypto.subtle&&"function"===typeof a.globalScope.crypto.subtle[e]}function S(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.msCrypto&&"object"===typeof a.globalScope.msCrypto.subtle&&"function"===typeof a.globalScope.msCrypto.subtle[e]}function A(e){for(var t=n.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),i=0;i0;)l.putByte(0),--h;return l.putBytes(n.util.hexToBytes(u)),l.getBytes()},c.rsa.decrypt=function(e,t,r,o){var s=Math.ceil(t.n.bitLength()/8);if(e.length!==s){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=s,a}var c=new i(n.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var u=b(c,t,r).toString(16),l=n.util.createBuffer(),h=s-Math.ceil(u.length/2);h>0;)l.putByte(0),--h;return l.putBytes(n.util.hexToBytes(u)),!1!==o?m(l.getBytes(),t,r):l.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"===typeof e&&(e=parseInt(e,10)),e=e||2048;var o,s=(r=r||{}).prng||n.random,a={nextBytes:function(e){for(var t=s.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(o.eInt),o},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new i(null);r.fromInt(30);for(var n,o=0,s=function(e,t){return e|t},a=+new Date,l=0;null===e.keys&&(t<=0||lh?e.pqState=0:e.num.isProbablePrime(w(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(u[o++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(i.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var f=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}l+=(n=+new Date)-a,a=n}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,u){if(1===arguments.length?"object"===typeof e?(r=e,e=void 0):"function"===typeof e&&(u=e,e=void 0):2===arguments.length?"number"===typeof e?"function"===typeof t?(u=t,t=void 0):"number"!==typeof t&&(r=t,t=void 0):(r=e,u=t,e=void 0,t=void 0):3===arguments.length&&("number"===typeof t?"function"===typeof r&&(u=r,r=void 0):(u=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!n.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(u){if(_("generateKeyPair"))return o.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return u(e);u(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(E("generateKey")&&E("exportKey"))return a.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then((function(e){return a.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)})).then(void 0,(function(e){u(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(s.fromDer(n.util.createBuffer(e)));u(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(S("generateKey")&&S("exportKey")){var l=a.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return l.oncomplete=function(e){var t=e.target.result,r=a.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=c.privateKeyFromAsn1(s.fromDer(n.util.createBuffer(t)));u(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){u(e)}},void(l.onerror=function(e){u(e)})}}else if(_("generateKeyPairSync")){var h=o.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(h.privateKey),publicKey:c.publicKeyFromPem(h.publicKey)}}var d=c.rsa.createKeyPairGenerationState(e,t,r);if(!u)return c.rsa.stepKeyPairGenerationState(d,0),d.keys;!function(e,t,r){"function"===typeof t&&(r=t,t={});t=t||{};var o={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(o.prng=t.prng);function s(){a(e.pBits,(function(t,n){return t?r(t):(e.p=n,null!==e.q?u(t,e.q):void a(e.qBits,u))}))}function a(e,t){n.prime.generateProbablePrime(e,o,t)}function u(t,n){if(t)return r(t);if(e.q=n,e.p.compareTo(e.q)<0){var o=e.p;e.p=e.q,e.q=o}if(0!==e.p.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.p=null,void s();if(0!==e.q.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.q=null,void a(e.qBits,u);if(e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(i.ONE))return e.p=e.q=null,void s();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void a(e.qBits,u);var l=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}s()}(d,r,u)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,i){if("string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return y(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,i)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"===typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var o=t.encode(e,r,!0);return c.rsa.encrypt(o,r,!0)},verify:function(e,t,i,o){"string"===typeof i?i=i.toUpperCase():void 0===i&&(i="RSASSA-PKCS1-V1_5"),void 0===o&&(o={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in o||(o._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===i?i={verify:function(e,t){t=m(t,r,!0);var i=s.fromDer(t,{parseAllBytes:o._parseAllDigestBytes}),a={},c=[];if(!s.validate(i,p,a,c))throw(u=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,u;var u,l=s.derToOid(a.algorithmIdentifier);if(l!==n.oids.md2&&l!==n.oids.md5&&l!==n.oids.sha1&&l!==n.oids.sha224&&l!==n.oids.sha256&&l!==n.oids.sha384&&l!==n.oids.sha512&&l!==n.oids["sha512-224"]&&l!==n.oids["sha512-256"])throw(u=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=l,u;if((l===n.oids.md2||l===n.oids.md5)&&!("parameters"in a))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return e===a.digest}}:"NONE"!==i&&"NULL"!==i&&null!==i||(i={verify:function(e,t){return e===(t=m(t,r,!0))}});var a=c.rsa.decrypt(t,r,!0,!1);return i.verify(e,a,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,i,o,s,a,u){var l={n:e,e:t,d:r,p:i,q:o,dP:s,dQ:a,qInv:u,decrypt:function(e,t,r){"string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var i=c.rsa.decrypt(e,l,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:m};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return n.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(i,l,!1)},sign:function(e,t){var r=!1;"string"===typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:g},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var n=t.encode(e,l.n.bitLength());return c.rsa.encrypt(n,l,r)}};return l},c.wrapRsaPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(c.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,s.toDer(e).getBytes())])},c.privateKeyFromAsn1=function(e){var t,r,o,a,u,d,f,p,g={},b=[];if(s.validate(e,l,g,b)&&(e=s.fromDer(n.util.createBuffer(g.privateKey))),g={},b=[],!s.validate(e,h,g,b)){var y=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw y.errors=b,y}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),o=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),u=n.util.createBuffer(g.privateKeyPrime2).toHex(),d=n.util.createBuffer(g.privateKeyExponent1).toHex(),f=n.util.createBuffer(g.privateKeyExponent2).toHex(),p=n.util.createBuffer(g.privateKeyCoefficient).toHex(),c.setRsaPrivateKey(new i(t,16),new i(r,16),new i(o,16),new i(a,16),new i(u,16),new i(d,16),new i(f,16),new i(p,16))},c.privateKeyToAsn1=c.privateKeyToRSAPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.e)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.d)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.p)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.q)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.dP)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.dQ)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.qInv))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(s.validate(e,f,t,r)){var o,a=s.derToOid(t.publicKeyOid);if(a!==c.oids.rsaEncryption)throw(o=new Error("Cannot read public key. Unknown OID.")).oid=a,o;e=t.rsaPublicKey}if(r=[],!s.validate(e,d,t,r))throw(o=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,o;var u=n.util.createBuffer(t.publicKeyModulus).toHex(),l=n.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new i(u,16),new i(l,16))},c.publicKeyToAsn1=c.publicKeyToSubjectPublicKeyInfo=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(c.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.publicKeyToRSAPublicKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,v(e.e))])}},3753:(e,t,r)=>{var n=r(45);r(5693),r(3900);var i=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=i,i.create=function(){s||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),64),s=!0);var e=null,t=n.util.createBuffer(),r=new Array(80),i={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,o=0;o>>0,c>>>0];for(var u=i.fullMessageLength.length-1;u>=0;--u)i.fullMessageLength[u]+=c[1],c[1]=c[0]+(i.fullMessageLength[u]/4294967296>>>0),i.fullMessageLength[u]=i.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(o),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var s=n.util.createBuffer();s.putBytes(t.bytes());var c,u=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;s.putBytes(o.substr(0,i.blockLength-u));for(var l=8*i.fullMessageLength[0],h=0;h>>0,s.putInt32(l>>>0),l=c>>>0;s.putInt32(l);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,s);var f=n.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f},i};var o=null,s=!1;function a(e,t,r){for(var n,i,o,s,a,c,u,l=r.length();l>=64;){for(i=e.h0,o=e.h1,s=e.h2,a=e.h3,c=e.h4,u=0;u<16;++u)n=r.getInt32(),t[u]=n,n=(i<<5|i>>>27)+(a^o&(s^a))+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;u<20;++u)n=(n=t[u-3]^t[u-8]^t[u-14]^t[u-16])<<1|n>>>31,t[u]=n,n=(i<<5|i>>>27)+(a^o&(s^a))+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;u<32;++u)n=(n=t[u-3]^t[u-8]^t[u-14]^t[u-16])<<1|n>>>31,t[u]=n,n=(i<<5|i>>>27)+(o^s^a)+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;u<40;++u)n=(n=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|n>>>30,t[u]=n,n=(i<<5|i>>>27)+(o^s^a)+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;u<60;++u)n=(n=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|n>>>30,t[u]=n,n=(i<<5|i>>>27)+(o&s|a&(o^s))+c+2400959708+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;u<80;++u)n=(n=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|n>>>30,t[u]=n,n=(i<<5|i>>>27)+(o^s^a)+c+3395469782+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;e.h0=e.h0+i|0,e.h1=e.h1+o|0,e.h2=e.h2+s|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,l-=64}}},3899:(e,t,r)=>{var n=r(45);r(5693),r(3900);var i=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=i,i.create=function(){s||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),64),a=[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],s=!0);var e=null,t=n.util.createBuffer(),r=new Array(64),i={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,o=0;o>>0,a>>>0];for(var u=i.fullMessageLength.length-1;u>=0;--u)i.fullMessageLength[u]+=a[1],a[1]=a[0]+(i.fullMessageLength[u]/4294967296>>>0),i.fullMessageLength[u]=i.fullMessageLength[u]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(o),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var s=n.util.createBuffer();s.putBytes(t.bytes());var a,u=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;s.putBytes(o.substr(0,i.blockLength-u));for(var l=8*i.fullMessageLength[0],h=0;h>>0,s.putInt32(l>>>0),l=a>>>0;s.putInt32(l);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};c(d,r,s);var f=n.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f.putInt32(d.h5),f.putInt32(d.h6),f.putInt32(d.h7),f},i};var o=null,s=!1,a=null;function c(e,t,r){for(var n,i,o,s,c,u,l,h,d,f,p,g,b,y=r.length();y>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=((n=t[c-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=((i=t[c-15])>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[c]=n+t[c-7]+i+t[c-16]|0;for(u=e.h0,l=e.h1,h=e.h2,d=e.h3,f=e.h4,p=e.h5,g=e.h6,b=e.h7,c=0;c<64;++c)o=(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),s=u&l|h&(u^l),n=b+((f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7))+(g^f&(p^g))+a[c]+t[c],b=g,g=p,p=f,f=d+n>>>0,d=h,h=l,l=u,u=n+(i=o+s)>>>0;e.h0=e.h0+u|0,e.h1=e.h1+l|0,e.h2=e.h2+h|0,e.h3=e.h3+d|0,e.h4=e.h4+f|0,e.h5=e.h5+p|0,e.h6=e.h6+g|0,e.h7=e.h7+b|0,y-=64}}},8138:(e,t,r)=>{var n=r(45);r(5693),r(3900);var i=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=i;var o=n.sha384=n.sha512.sha384=n.sha512.sha384||{};o.create=function(){return i.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=o,n.sha512.sha256=n.sha512.sha256||{create:function(){return i.create("SHA-512/256")}},n.md["sha512/256"]=n.md.algorithms["sha512/256"]=n.sha512.sha256,n.sha512.sha224=n.sha512.sha224||{create:function(){return i.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,i.create=function(e){if(a||(s=String.fromCharCode(128),s+=n.util.fillString(String.fromCharCode(0),128),c=[[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]],(u={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],u["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],u["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],u["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],a=!0),"undefined"===typeof e&&(e="SHA-512"),!(e in u))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=u[e],r=null,i=n.util.createBuffer(),o=new Array(80),h=0;h<80;++h)o[h]=new Array(2);var d=64;switch(e){case"SHA-384":d=48;break;case"SHA-512/256":d=32;break;case"SHA-512/224":d=28}var f={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:d,messageLength:0,fullMessageLength:null,messageLengthSize:16,start:function(){f.messageLength=0,f.fullMessageLength=f.messageLength128=[];for(var e=f.messageLengthSize/4,o=0;o>>0,s>>>0];for(var a=f.fullMessageLength.length-1;a>=0;--a)f.fullMessageLength[a]+=s[1],s[1]=s[0]+(f.fullMessageLength[a]/4294967296>>>0),f.fullMessageLength[a]=f.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;return i.putBytes(e),l(r,o,i),(i.read>2048||0===i.length())&&i.compact(),f},f.digest=function(){var t=n.util.createBuffer();t.putBytes(i.bytes());var a,c=f.fullMessageLength[f.fullMessageLength.length-1]+f.messageLengthSize&f.blockLength-1;t.putBytes(s.substr(0,f.blockLength-c));for(var u=8*f.fullMessageLength[0],h=0;h>>0,t.putInt32(u>>>0),u=a>>>0;t.putInt32(u);var d=new Array(r.length);for(h=0;h=128;){for(R=0;R<16;++R)t[R][0]=r.getInt32()>>>0,t[R][1]=r.getInt32()>>>0;for(;R<80;++R)n=(((P=(N=t[R-2])[0])>>>19|(D=N[1])<<13)^(D>>>29|P<<3)^P>>>6)>>>0,i=((P<<13|D>>>19)^(D<<3|P>>>29)^(P<<26|D>>>6))>>>0,o=(((P=(U=t[R-15])[0])>>>1|(D=U[1])<<31)^(P>>>8|D<<24)^P>>>7)>>>0,s=((P<<31|D>>>1)^(P<<24|D>>>8)^(P<<25|D>>>7))>>>0,B=t[R-7],L=t[R-16],D=i+B[1]+s+L[1],t[R][0]=n+B[0]+o+L[0]+(D/4294967296>>>0)>>>0,t[R][1]=D>>>0;for(p=e[0][0],g=e[0][1],b=e[1][0],y=e[1][1],m=e[2][0],v=e[2][1],w=e[3][0],_=e[3][1],E=e[4][0],S=e[4][1],A=e[5][0],k=e[5][1],x=e[6][0],I=e[6][1],C=e[7][0],T=e[7][1],R=0;R<80;++R)l=((E>>>14|S<<18)^(E>>>18|S<<14)^(S>>>9|E<<23))>>>0,h=(x^E&(A^x))>>>0,a=((p>>>28|g<<4)^(g>>>2|p<<30)^(g>>>7|p<<25))>>>0,u=((p<<4|g>>>28)^(g<<30|p>>>2)^(g<<25|p>>>7))>>>0,d=(p&b|m&(p^b))>>>0,f=(g&y|v&(g^y))>>>0,D=T+(((E<<18|S>>>14)^(E<<14|S>>>18)^(S<<23|E>>>9))>>>0)+((I^S&(k^I))>>>0)+c[R][1]+t[R][1],n=C+l+h+c[R][0]+t[R][0]+(D/4294967296>>>0)>>>0,i=D>>>0,o=a+d+((D=u+f)/4294967296>>>0)>>>0,s=D>>>0,C=x,T=I,x=A,I=k,A=E,k=S,E=w+n+((D=_+i)/4294967296>>>0)>>>0,S=D>>>0,w=m,_=v,m=b,v=y,b=p,y=g,p=n+o+((D=i+s)/4294967296>>>0)>>>0,g=D>>>0;D=e[0][1]+g,e[0][0]=e[0][0]+p+(D/4294967296>>>0)>>>0,e[0][1]=D>>>0,D=e[1][1]+y,e[1][0]=e[1][0]+b+(D/4294967296>>>0)>>>0,e[1][1]=D>>>0,D=e[2][1]+v,e[2][0]=e[2][0]+m+(D/4294967296>>>0)>>>0,e[2][1]=D>>>0,D=e[3][1]+_,e[3][0]=e[3][0]+w+(D/4294967296>>>0)>>>0,e[3][1]=D>>>0,D=e[4][1]+S,e[4][0]=e[4][0]+E+(D/4294967296>>>0)>>>0,e[4][1]=D>>>0,D=e[5][1]+k,e[5][0]=e[5][0]+A+(D/4294967296>>>0)>>>0,e[5][1]=D>>>0,D=e[6][1]+I,e[6][0]=e[6][0]+x+(D/4294967296>>>0)>>>0,e[6][1]=D>>>0,D=e[7][1]+T,e[7][0]=e[7][0]+C+(D/4294967296>>>0)>>>0,e[7][1]=D>>>0,M-=128}}},3900:(e,t,r)=>{var n=r(45),i=r(6407),o=e.exports=n.util=n.util||{};function s(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function a(e){if(this.data="",this.read=0,"string"===typeof e)this.data=e;else if(o.isArrayBuffer(e)||o.isArrayBufferView(e))if("undefined"!==typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(n){for(var r=0;r15?(r=Date.now(),s(e)):(t.push(e),1===t.length&&i.setAttribute("a",n=!n))}}o.nextTick=o.setImmediate}(),o.isNodejs="undefined"!==typeof process&&process.versions&&process.versions.node,o.globalScope=o.isNodejs?r.g:"undefined"===typeof self?window:self,o.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},o.isArrayBuffer=function(e){return"undefined"!==typeof ArrayBuffer&&e instanceof ArrayBuffer},o.isArrayBufferView=function(e){return e&&o.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},o.ByteBuffer=a,o.ByteStringBuffer=a;o.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},o.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},o.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},o.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},o.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},o.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},o.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(o.encodeUtf8(e))},o.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},o.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},o.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},o.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},o.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},o.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},o.ByteStringBuffer.prototype.putInt=function(e,t){s(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},o.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},o.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},o.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},o.ByteStringBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},o.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},o.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},o.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},o.ByteStringBuffer.prototype.copy=function(){var e=o.createBuffer(this.data);return e.read=this.read,e},o.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},o.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},o.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},o.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},o.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},o.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},o.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},o.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},o.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},o.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},o.DataBuffer.prototype.putInt=function(e,t){s(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},o.DataBuffer.prototype.putSignedInt=function(e,t){return s(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},o.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},o.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},o.DataBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},o.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},o.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},o.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},o.DataBuffer.prototype.copy=function(){return new o.DataBuffer(this)},o.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},o.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},o.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},o.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},o.xorBytes=function(e,t,r){for(var n="",i="",o="",s=0,a=0;r>0;--r,++s)i=e.charCodeAt(s)^t.charCodeAt(s),a>=10&&(n+=o,o="",a=0),o+=String.fromCharCode(i),++a;return n+=o},o.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],l="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";o.encode64=function(e,t){for(var r,n,i,o="",s="",a=0;a>2),o+=c.charAt((3&r)<<4|n>>4),isNaN(n)?o+="==":(o+=c.charAt((15&n)<<2|i>>6),o+=isNaN(i)?"=":c.charAt(63&i)),t&&o.length>t&&(s+=o.substr(0,t)+"\r\n",o=o.substr(t));return s+=o},o.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,i,o="",s=0;s>4),64!==n&&(o+=String.fromCharCode((15&r)<<4|n>>2),64!==i&&(o+=String.fromCharCode((3&n)<<6|i)));return o},o.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},o.decodeUtf8=function(e){return decodeURIComponent(escape(e))},o.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:i.encode,decode:i.decode}},o.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},o.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,o=0;o>2),o+=c.charAt((3&r)<<4|n>>4),isNaN(n)?o+="==":(o+=c.charAt((15&n)<<2|i>>6),o+=isNaN(i)?"=":c.charAt(63&i)),t&&o.length>t&&(s+=o.substr(0,t)+"\r\n",o=o.substr(t));return s+=o},o.binary.base64.decode=function(e,t,r){var n,i,o,s,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,l=r=r||0;c>4,64!==o&&(a[l++]=(15&i)<<4|o>>2,64!==s&&(a[l++]=(3&o)<<6|s));return t?l-r:a.subarray(0,l)},o.binary.base58.encode=function(e,t){return o.binary.baseN.encode(e,l,t)},o.binary.base58.decode=function(e,t){return o.binary.baseN.decode(e,l,t)},o.text={utf8:{},utf16:{}},o.text.utf8.encode=function(e,t,r){e=o.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,s=0;s0&&o.push(r),s=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i");break;case"%":o.push("%");break;default:o.push("<%"+a+"?>")}}return o.push(e.substring(s)),o.join("")},o.formatNumber=function(e,t,r,n){var i=e,o=isNaN(t=Math.abs(t))?2:t,s=void 0===r?",":r,a=void 0===n?".":n,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(o),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+a:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+a)+(o?s+Math.abs(i-u).toFixed(o).slice(2):"")},o.formatSize=function(e){return e=e>=1073741824?o.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?o.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?o.formatNumber(e/1024,0)+" KiB":o.formatNumber(e,0)+" bytes"},o.bytesFromIP=function(e){return-1!==e.indexOf(".")?o.bytesFromIPv4(e):-1!==e.indexOf(":")?o.bytesFromIPv6(e):null},o.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=o.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(s)}if(r.length>0){var u=r[n];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),0===u.start&&t.unshift(""),7===u.end&&t.push(""))}return t.join(":")},o.estimateCores=function(e,t){if("function"===typeof e&&(t=e,e={}),e=e||{},"cores"in o&&!e.update)return t(null,o.cores);if("undefined"!==typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return o.cores=navigator.hardwareConcurrency,t(null,o.cores);if("undefined"===typeof Worker)return o.cores=1,t(null,o.cores);if("undefined"===typeof Blob)return o.cores=2,t(null,o.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()a.st&&i.sti.st&&a.st{"use strict";var t=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach((function(e){n[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(i){return!1}}()?Object.assign:function(e,i){for(var o,s,a=function(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),c=1;c{"use strict";e.exports=c;var n,i=r(1509),o=i.LongBits,s=i.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var u="undefined"!==typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},l=function(){return i.Buffer?function(e){return(c.create=function(e){return i.Buffer.isBuffer(e)?new n(e):u(e)})(e)}:u};function h(){var e=new o(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new o(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}c.create=l(),c.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,c.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return e}}(),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return d(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|d(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,r);if(t===r){var n=i.Buffer;return n?n.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},c.prototype.skip=function(e){if("number"===typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!==(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=l(),n._configure();var t=i.Long?"toLong":"toNumber";i.merge(c.prototype,{int64:function(){return h.call(this)[t](!1)},uint64:function(){return h.call(this)[t](!0)},sint64:function(){return h.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},7707:(e,t,r)=>{"use strict";e.exports=o;var n=r(3338);(o.prototype=Object.create(n.prototype)).constructor=o;var i=r(1509);function o(e){n.call(this,e)}o._configure=function(){i.Buffer&&(o.prototype._slice=i.Buffer.prototype.slice)},o.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},o._configure()},6350:(e,t,r)=>{"use strict";e.exports=i;var n=r(1509);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var s=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(e){if(0===e)return o;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new i(r,n)},i.from=function(e){if("number"===typeof e)return i.fromNumber(e);if(n.isString(e)){if(!n.Long)return i.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):o},i.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;i.fromHash=function(e){return e===s?o:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},1509:function(e,t,r){"use strict";var n=t;function i(e,t,r){for(var n=Object.keys(t),i=0;i0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"===typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"===typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!==typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=i,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=o,n.ProtocolError=o("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r{"use strict";e.exports=h;var n,i=r(1509),o=i.LongBits,s=i.base64,a=i.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function u(){}function l(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(u,0,0),this.tail=this.head,this.states=null}var d=function(){return i.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function f(e,t,r){t[r]=255&e}function p(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function b(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(h.alloc=i.pool(h.alloc,i.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},p.prototype=Object.create(c.prototype),p.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new p((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,o.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=o.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=o.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(f,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(b,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=o.from(e);return this._push(b,4,t.lo)._push(b,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(i.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(i.float.writeDoubleLE,8,e)};var y=i.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(f,1,0);if(i.isString(e)){var r=h.alloc(t=s.length(e));s.decode(e,r,0),e=r}return this.uint32(t)._push(y,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(f,1,0)},h.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new c(u,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(u,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},3931:(e,t,r)=>{"use strict";e.exports=o;var n=r(5850);(o.prototype=Object.create(n.prototype)).constructor=o;var i=r(1509);function o(){n.call(this)}function s(e,t,r){e.length<40?i.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}o._configure=function(){o.alloc=i._Buffer_allocUnsafe,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(o.writeBytesBuffer,t,e),this},o.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this._push(s,t,e),this},o._configure()},8275:(e,t)=>{"use strict";class r{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const n=r.toUint8Array(e),i=r.toUint8Array(t);if(n.length!==i.byteLength)return!1;for(let r=0;r1&&void 0!==arguments[1]&&arguments[1];const n=r.toArrayBuffer(e),i=new DataView(n);let o="";for(let r=0;r1&&void 0!==arguments[1]&&arguments[1];const r=new ArrayBuffer(2*e.length),n=new DataView(r);for(let i=0;i1&&void 0!==arguments[1]?arguments[1]:"utf8";const n=r.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return c.toString(n,!0);case"utf16":case"utf16be":return c.toString(n);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static FromString(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8";if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return c.fromString(e,!0);case"utf16":case"utf16be":return c.fromString(e);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static ToBase64(e){const t=r.toUint8Array(e);if("undefined"!==typeof btoa){const e=this.ToString(t,"binary");return btoa(e)}return Buffer.from(t).toString("base64")}static FromBase64(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!u.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!==typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!u.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.FromBinary(e);case"utf8":return a.fromString(e);case"utf16":case"utf16be":return c.fromString(e);case"utf16le":case"usc2":return c.fromString(e,!0);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static ToUtf8String(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.ToBinary(e);case"utf8":return a.toString(e);case"utf16":case"utf16be":return c.toString(e);case"utf16le":case"usc2":return c.toString(e,!0);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static FromBinary(e){const t=e.length,r=new Uint8Array(t);for(let n=0;n1&&void 0!==arguments[1]&&arguments[1];return c.toString(e,t)}static FromUtf16String(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return c.fromString(e,t)}static Base64Padding(e){const t=4-e.length%4;if(t<4)for(let r=0;r{"use strict";var n=r(5043),i=r(2123),o=r(8853);function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r
\n ));\n\n return (\n
\n {renderedMessages}\n \n
\n );\n}\n\nfunction formatDisplayDate(message: Message): string {\n return message.timestamp.toLocaleString([], {\n month: \"short\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n hour12: false,\n });\n}\n\nconst AlwaysScrollToBottom = (props: { messages: Message[] }) => {\n const elementRef = useRef(null);\n\n useEffect(() => {\n if (elementRef.current) {\n elementRef.current.scrollIntoView();\n }\n }, [props.messages]);\n\n return
;\n};\n","import { ChangeEvent, KeyboardEvent, useEffect, useState } from \"react\";\nimport { useWaku } from \"@waku/react\";\nimport { LightNode } from \"@waku/interfaces\";\nimport { MessageInputProps } from \"./types\";\n\nexport default function MessageInput(props: MessageInputProps) {\n const { hasLightPushPeers } = props;\n const { node } = useWaku();\n\n const [inputText, setInputText] = useState(\"\");\n const [isActive, setActiveButton] = useState(false);\n\n const onMessage = async () => {\n if (props.sendMessage && inputText) {\n try {\n await props.sendMessage(inputText);\n } catch (e) {\n console.error(`Failed to send message: ${e}`);\n }\n setInputText(\"\");\n }\n };\n\n const onChange = (event: ChangeEvent) => {\n event.preventDefault();\n setInputText(event.target.value);\n };\n\n const onKeyDown = async (event: KeyboardEvent) => {\n if (\n isActive &&\n event.key === \"Enter\" &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n await onMessage();\n }\n };\n\n // Enable the button if there are peers available or the user is sending a command\n useEffect(() => {\n if (inputText.startsWith(\"/\") || hasLightPushPeers) {\n setActiveButton(true);\n } else if (node) {\n setActiveButton(false);\n }\n }, [node, inputText, hasLightPushPeers]);\n\n return (\n
\n \n \n Send\n \n
\n );\n}\n","// @ts-expect-error no types\nimport ReaderClass from 'protobufjs/src/reader.js'\n// @ts-expect-error no types\nimport ReaderBufferClass from 'protobufjs/src/reader_buffer.js'\n// @ts-expect-error no types\nimport WriterClass from 'protobufjs/src/writer.js'\n// @ts-expect-error no types\nimport WriterBufferClass from 'protobufjs/src/writer_buffer.js'\n// @ts-expect-error no types\nimport util from 'protobufjs/src/util/minimal.js'\nimport type { Reader, Writer } from './index.js'\n\nfunction configure (): void {\n util._configure()\n ReaderClass._configure(ReaderBufferClass)\n WriterClass._configure(WriterBufferClass)\n}\n\n// Set up buffer utility according to the environment\nconfigure()\n\n// monkey patch the reader to add native bigint support\nconst methods = [\n 'uint64', 'int64', 'sint64', 'fixed64', 'sfixed64'\n]\n\nfunction patchReader (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (): bigint {\n return BigInt(original.call(this).toString())\n }\n }\n\n return obj\n}\n\nexport function reader (buf: Uint8Array): Reader {\n return patchReader(new ReaderClass(buf))\n}\n\nfunction patchWriter (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (val: bigint) {\n return original.call(this, val.toString())\n }\n }\n\n return obj\n}\n\nexport function writer (): Writer {\n return patchWriter(WriterClass.create())\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: T, writer: Writer, opts?: EncodeOptions): void\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from \"protons-runtime\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface ChatMessage {\n timestamp: bigint;\n nick: string;\n payload: Uint8Array;\n}\n\nexport namespace ChatMessage {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.timestamp != null) {\n writer.uint32(8);\n writer.uint64(obj.timestamp);\n } else {\n throw new Error(\n 'Protocol error: required field \"timestamp\" was not found in object'\n );\n }\n\n if (obj.nick != null) {\n writer.uint32(18);\n writer.string(obj.nick);\n } else {\n throw new Error(\n 'Protocol error: required field \"nick\" was not found in object'\n );\n }\n\n if (obj.payload != null) {\n writer.uint32(26);\n writer.bytes(obj.payload);\n } else {\n throw new Error(\n 'Protocol error: required field \"payload\" was not found in object'\n );\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {\n timestamp: 0n,\n nick: \"\",\n payload: new Uint8Array(0),\n };\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.timestamp = reader.uint64();\n break;\n case 2:\n obj.nick = reader.string();\n break;\n case 3:\n obj.payload = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n if (obj.timestamp == null) {\n throw new Error(\n 'Protocol error: value for required field \"timestamp\" was not found in protobuf'\n );\n }\n\n if (obj.nick == null) {\n throw new Error(\n 'Protocol error: value for required field \"nick\" was not found in protobuf'\n );\n }\n\n if (obj.payload == null) {\n throw new Error(\n 'Protocol error: value for required field \"payload\" was not found in protobuf'\n );\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: ChatMessage): Uint8Array => {\n return encodeMessage(obj, ChatMessage.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): ChatMessage => {\n return decodeMessage(buf, ChatMessage.codec());\n };\n}\n","import { createCodec, CODEC_TYPES, EncodeOptions } from '../codec.js'\nimport type { Codec } from '../codec.js'\nimport type { Reader, Writer } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: (obj: T, writer: Writer, opts?: EncodeOptions) => void, decode: (reader: Reader, length?: number) => T): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","import type { Codec } from './codec.js'\nimport { writer } from './utils.js'\n\nexport function encodeMessage (message: T, codec: Codec): Uint8Array {\n const w = writer()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from './codec.js'\nimport { reader } from './utils.js'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Codec): T {\n const r = reader(buf instanceof Uint8Array ? buf : buf.subarray())\n\n return codec.decode(r)\n}\n","import { utf8ToBytes, bytesToUtf8 } from \"@waku/sdk\";\nimport * as proto from \"./proto/chat_message\";\n\n/**\n * ChatMessage is used by the various show case waku apps that demonstrates\n * waku used as the network layer for chat group applications.\n *\n * This is included to help building PoC and MVPs. Apps that aim to be\n * production ready should use a more appropriate data structure.\n */\nexport class ChatMessage {\n public constructor(public proto: proto.ChatMessage) {}\n\n /**\n * Create Chat Message with a utf-8 string as payload.\n */\n static fromUtf8String(\n timestamp: Date,\n nick: string,\n text: string\n ): ChatMessage {\n const timestampNumber = BigInt(Math.floor(timestamp.valueOf() / 1000));\n const payload = utf8ToBytes(text);\n\n return new ChatMessage({\n timestamp: timestampNumber,\n nick,\n payload,\n });\n }\n\n /**\n * Decode a protobuf payload to a ChatMessage.\n * @param bytes The payload to decode.\n */\n static decode(bytes: Uint8Array): ChatMessage {\n const protoMsg = proto.ChatMessage.decode(bytes);\n return new ChatMessage(protoMsg);\n }\n\n /**\n * Encode this ChatMessage to a byte array, to be used as a protobuf payload.\n * @returns The encoded payload.\n */\n encode(): Uint8Array {\n return proto.ChatMessage.encode(this.proto);\n }\n\n get timestamp(): Date {\n return new Date(Number(BigInt(this.proto.timestamp) * BigInt(1000)));\n }\n\n get nick(): string {\n return this.proto.nick;\n }\n\n get payloadAsUtf8(): string {\n if (!this.proto.payload) {\n return \"\";\n }\n\n return bytesToUtf8(this.proto.payload);\n }\n}\n","import { IDecodedMessage } from \"@waku/interfaces\";\nimport { ChatMessage } from \"./chat_message\";\n\nexport class Message {\n public chatMessage: ChatMessage;\n // WakuMessage timestamp\n public sentTimestamp: Date | undefined;\n\n constructor(chatMessage: ChatMessage, sentTimestamp: Date | undefined) {\n this.chatMessage = chatMessage;\n this.sentTimestamp = sentTimestamp;\n }\n\n static cmp(left: Message, right: Message): boolean {\n return left.timestamp.getTime() < right.timestamp.getTime();\n }\n\n static isEqual(left: Message, right: Message): boolean {\n return (\n left.timestamp.valueOf() === right.timestamp.valueOf() &&\n left.chatMessage.nick === right.chatMessage.nick &&\n left.chatMessage.payloadAsUtf8 === right.chatMessage.payloadAsUtf8\n );\n }\n\n static fromWakuMessage(wakuMsg: IDecodedMessage): Message | undefined {\n if (wakuMsg.payload) {\n try {\n const chatMsg = ChatMessage.decode(wakuMsg.payload);\n if (chatMsg) {\n return new Message(chatMsg, wakuMsg.timestamp);\n }\n } catch (e) {\n console.error(\"Failed to decode chat message\", e);\n }\n }\n return;\n }\n\n static fromUtf8String(nick: string, text: string): Message {\n const now = new Date();\n return new Message(ChatMessage.fromUtf8String(now, nick, text), now);\n }\n\n get nick() {\n return this.chatMessage.nick;\n }\n\n get timestamp() {\n return this.chatMessage.timestamp;\n }\n\n get payloadAsUtf8() {\n return this.chatMessage.payloadAsUtf8;\n }\n}\n","export class OrderedSet {\n array: Array;\n\n constructor(\n public orderCmp: (a: T, b: T) => boolean,\n public isEqual: (a: T, b: T) => boolean\n ) {\n this.array = [];\n }\n\n push(...items: T[]): void {\n for (const item of items) {\n this.insertInOrder(this.array, item);\n }\n }\n\n insertInOrder(array: T[], item: T): T[] {\n let i = 0;\n while (i < array.length) {\n if (this.isEqual(item, array[i])) {\n continue;\n }\n if (this.orderCmp(item, array[i])) {\n break;\n }\n i++;\n }\n\n array.splice(i, 0, item);\n return array;\n }\n}\n","import type { Peer } from \"@libp2p/interface\";\nimport type { IFilter, ILightPushSDK, IStoreSDK } from \"@waku/interfaces\";\n\nexport async function handleCatch(\n promise?: Promise\n): Promise {\n if (!promise) {\n return Promise.resolve(undefined);\n }\n\n try {\n return await promise;\n } catch (_) {\n return undefined;\n }\n}\n\nexport function getPeerIdsForProtocol(\n protocol: IStoreSDK | ILightPushSDK | IFilter | undefined,\n peers: Peer[]\n) {\n if (!protocol) {\n return [];\n }\n const multicodec =\n \"multicodec\" in protocol\n ? protocol.multicodec\n : protocol.protocol.multicodec;\n return peers.filter((p) => p.protocols.includes(multicodec)).map((p) => p.id);\n}\n","import React, { useEffect, useState } from \"react\";\nimport { generate } from \"server-name-generator\";\nimport { Message } from \"./Message\";\nimport { EPeersByDiscoveryEvents, LightNode, Tags } from \"@waku/interfaces\";\nimport type { PeerId } from \"@libp2p/interface\";\n\nimport { useFilterMessages, useStoreMessages } from \"@waku/react\";\nimport type {\n UseMessagesParams,\n UseMessagesResult,\n UsePeersParams,\n UsePeersResults,\n} from \"./types\";\nimport { OrderedSet } from \"./ordered_array\";\nimport { getPeerIdsForProtocol } from \"./utils\";\n\nexport const usePersistentNick = (): [\n string,\n React.Dispatch>\n] => {\n const [nick, setNick] = useState(() => {\n const persistedNick = window.localStorage.getItem(\"nick\");\n return persistedNick !== null ? persistedNick : generate();\n });\n useEffect(() => {\n localStorage.setItem(\"nick\", nick);\n }, [nick]);\n\n return [nick, setNick];\n};\n\nexport const useMessages = (params: UseMessagesParams): UseMessagesResult => {\n const { messages: newMessages } = useFilterMessages(params);\n const { messages: storedMessages } = useStoreMessages(params);\n const [localMessages, setLocalMessages] = useState([]);\n\n const pushMessages = (msgs: Message[]) => {\n if (!msgs || !msgs.length) {\n return;\n }\n setLocalMessages((prev) => [...prev, ...msgs]);\n };\n\n const allMessages = React.useMemo((): OrderedSet => {\n const allMessages = new OrderedSet(Message.cmp, Message.isEqual);\n\n const tomorrow = new Date();\n tomorrow.setDate(tomorrow.getDate() + 1);\n\n const _msgs = [...storedMessages, ...newMessages]\n .map(Message.fromWakuMessage)\n .filter((v): v is Message => !!v)\n .filter((v) => v.payloadAsUtf8 !== \"\")\n // Filter out messages that are \"sent\" tomorrow are they are likely to be flukes\n .filter((m) => m.timestamp.valueOf() < tomorrow.valueOf());\n allMessages.push(..._msgs);\n allMessages.push(...localMessages);\n\n return allMessages;\n }, [storedMessages, newMessages, localMessages]);\n\n return [allMessages, pushMessages];\n};\n\n// can be safely ignored\n// this is for experiments on waku side around new discovery options\nexport const useNodePeers = (node: undefined | LightNode) => {\n const [discoveredBootstrapPeers, setBootstrapPeers] = useState>(\n new Set()\n );\n const [connectedBootstrapPeers, setConnectedBootstrapPeers] = useState<\n Set\n >(new Set());\n const [discoveredPeerExchangePeers, setPeerExchangePeers] = useState<\n Set\n >(new Set());\n const [connectedPeerExchangePeers, setConnectedPeerExchangePeers] = useState<\n Set\n >(new Set());\n\n useEffect(() => {\n if (!node) return;\n\n const handleDiscoveryBootstrap = async (event: CustomEvent) => {\n (async () => {\n if (!(await isPeerDialable(event.detail, node))) return;\n\n setBootstrapPeers((peers) => new Set([...peers, event.detail]));\n })().catch((error) => console.error(error));\n };\n\n const handleConnectBootstrap = (event: CustomEvent) => {\n setConnectedBootstrapPeers((peers) => new Set([...peers, event.detail]));\n };\n\n const handleDiscoveryPeerExchange = (event: CustomEvent) => {\n (async () => {\n if (!(await isPeerDialable(event.detail, node))) return;\n\n setPeerExchangePeers((peers) => new Set([...peers, event.detail]));\n })().catch((error) => console.error(error));\n };\n\n const handleConnectPeerExchange = (event: CustomEvent) => {\n setConnectedPeerExchangePeers(\n (peers) => new Set([...peers, event.detail])\n );\n };\n\n const initHookData = async () => {\n const { CONNECTED, DISCOVERED } =\n await node.connectionManager.getPeersByDiscovery();\n\n setConnectedBootstrapPeers(\n new Set(CONNECTED[Tags.BOOTSTRAP].map((p) => p.id))\n );\n setConnectedPeerExchangePeers(\n new Set(CONNECTED[Tags.PEER_EXCHANGE].map((p) => p.id))\n );\n setBootstrapPeers(new Set(DISCOVERED[Tags.BOOTSTRAP].map((p) => p.id)));\n setPeerExchangePeers(\n new Set(DISCOVERED[Tags.PEER_EXCHANGE].map((p) => p.id))\n );\n\n node.libp2p.addEventListener(\"peer:disconnect\", (evt) => {\n const peerId = evt.detail;\n setConnectedBootstrapPeers((peers) => {\n peers.delete(peerId);\n return peers;\n });\n });\n node.connectionManager.addEventListener(\n EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP,\n handleDiscoveryBootstrap\n );\n node.connectionManager.addEventListener(\n EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP,\n handleConnectBootstrap\n );\n node.connectionManager.addEventListener(\n EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE,\n handleDiscoveryPeerExchange\n );\n node.connectionManager.addEventListener(\n EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE,\n handleConnectPeerExchange\n );\n };\n\n initHookData();\n\n return () => {\n node.connectionManager.removeEventListener(\n EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP,\n handleDiscoveryBootstrap\n );\n node.connectionManager.removeEventListener(\n EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP,\n handleConnectBootstrap\n );\n node.connectionManager.removeEventListener(\n EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE,\n handleDiscoveryPeerExchange\n );\n node.connectionManager.removeEventListener(\n EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE,\n handleConnectPeerExchange\n );\n };\n }, [node]);\n\n return {\n discoveredBootstrapPeers,\n connectedBootstrapPeers,\n discoveredPeerExchangePeers,\n connectedPeerExchangePeers,\n };\n};\n\n/**\n * Hook returns map of peers for different protocols.\n * If protocol is not implemented on the node peers are undefined.\n * @example\n * const { storePeers } = usePeers({ node });\n * @param {Waku} params.node - Waku node, if not set then no peers will be returned\n * @returns {Object} map of peers, if some of the protocols is not implemented then undefined\n */\nexport const usePeers = (params: UsePeersParams): UsePeersResults => {\n const { node } = params;\n const [peers, setPeers] = React.useState({});\n\n useEffect(() => {\n if (!node) {\n return;\n }\n\n const listener = async () => {\n // find all the peers that are connected for diff protocols\n const peerIds = node.libp2p.getPeers();\n const peers = await Promise.all(\n peerIds.map((id) => node.libp2p.peerStore.get(id))\n );\n\n setPeers({\n allConnected: peers.map((p) => p.id),\n storePeers: getPeerIdsForProtocol(node.store, peers),\n filterPeers: getPeerIdsForProtocol(node.filter, peers),\n lightPushPeers: getPeerIdsForProtocol(node.lightPush, peers),\n });\n };\n\n listener(); // populate peers before event is invoked\n node.libp2p.addEventListener(\"peer:identify\", listener);\n return () => {\n node.libp2p.removeEventListener(\"peer:identify\", listener);\n };\n }, [node, setPeers]);\n\n return peers;\n};\n\n// we only support websocket connections for now\nconst isPeerDialable = async (peerId: PeerId, node: LightNode) => {\n const peer = await node.libp2p.peerStore.get(peerId);\n if (!peer) return false;\n if (peer.addresses.length === 0) return false;\n const connectableMultiaddrs = peer.addresses.filter(({ multiaddr }) =>\n isMultiaddrConnectable(multiaddr.toString())\n );\n if (connectableMultiaddrs.length === 0) return false;\n\n return true;\n};\n\nconst isMultiaddrConnectable = (multiaddr: string) => {\n return multiaddr.includes(\"wss\") || multiaddr.includes(\"/tls/ws\");\n};\n","import React from \"react\";\nimport type {\n IDecodedMessage,\n IDecoder,\n IFilter,\n Unsubscribe,\n Waku,\n} from \"@waku/interfaces\";\n\nimport type { HookState } from \"./types\";\n\ntype AbstractFilterNode = Waku & {\n filter: IFilter;\n};\n\ntype UseFilterMessagesParams = {\n node: undefined | AbstractFilterNode;\n decoder: undefined | IDecoder;\n};\n\ntype UseFilterMessagesResult = HookState & {\n messages: IDecodedMessage[];\n};\n\n/**\n * Returns messages from Filter subscription and keeps them up to date\n * @example\n * const { isLoading, error, message } = useFilterMessages({node, decoder});\n * @param {Object} node - node that implements Filter, hook does nothing if undefined\n * @param {Object} decoder - decoder to use for subscribing, hook does nothing if undefined\n * @returns {Object} hook state (isLoading, error) and messages array\n */\nexport const useFilterMessages = (\n params: UseFilterMessagesParams,\n): UseFilterMessagesResult => {\n const { node, decoder } = params;\n\n const [error, setError] = React.useState(undefined);\n const [isLoading, setLoading] = React.useState(false);\n const [messages, setMessage] = React.useState([]);\n\n const pushMessage = React.useCallback(\n (message: IDecodedMessage): void => {\n if (!message) {\n return;\n }\n\n setMessage((prev) => [...prev, message]);\n },\n [setMessage],\n );\n\n React.useEffect(() => {\n if (!node || !decoder) {\n return;\n }\n\n let unsubscribe: null | Unsubscribe = null;\n setLoading(true);\n\n (node.filter.subscribe([decoder], pushMessage) as Promise)\n .then((unsubscribeFn) => {\n setLoading(false);\n unsubscribe = unsubscribeFn;\n })\n .catch((err) => {\n setLoading(false);\n setError(\n `Failed to subscribe to filer: ${err?.message || \"no message\"}`,\n );\n });\n\n return () => {\n unsubscribe?.();\n };\n }, [node, decoder, pushMessage, setError, setLoading]);\n\n return {\n error,\n messages,\n isLoading,\n };\n};\n","import React from \"react\";\nimport type {\n IDecodedMessage,\n IDecoder,\n IStoreSDK,\n StoreQueryOptions,\n Waku,\n} from \"@waku/interfaces\";\n\nimport type { HookState } from \"./types\";\n\ntype AbstractStoreNode = Waku & {\n store: IStoreSDK;\n};\n\ntype UseStoreMessagesParams = {\n node: undefined | AbstractStoreNode;\n decoder: undefined | IDecoder;\n options: StoreQueryOptions;\n};\n\ntype UseStoreMessagesResult = HookState & {\n messages: IDecodedMessage[];\n};\n\n/**\n * Hook for retrieving messages from Store protocol based on options\n * @example\n * const { isLoading, error, messages } = useStoreMessages({node, decoder, options});\n * @param {Object} node - node that implement Store, hook does nothing if undefined\n * @param {Object} decoder - decoder to use for getting messages, hook does nothing if undefined\n * @param {StoreQueryOptions} options - options to initiate query to get messages\n * @returns {Object} hook state (isLoading, error) and messages array\n */\nexport const useStoreMessages = (\n params: UseStoreMessagesParams,\n): UseStoreMessagesResult => {\n const { node, decoder, options } = params;\n\n const [error, setError] = React.useState(undefined);\n const [isLoading, setLoading] = React.useState(false);\n const [messages, setMessage] = React.useState([]);\n\n const pushMessage = React.useCallback(\n (newMessages: IDecodedMessage[]): void => {\n if (!newMessages || !newMessages.length) {\n return;\n }\n\n setMessage((prev) => [...prev, ...newMessages]);\n },\n [setMessage],\n );\n\n React.useEffect(() => {\n if (!node || !decoder) {\n return;\n }\n\n let cancelled = false;\n setLoading(true);\n\n Promise.resolve()\n .then(async () => {\n for await (const promises of node.store.queryGenerator(\n [decoder],\n options,\n )) {\n if (cancelled) {\n return;\n }\n\n const messagesRaw = await Promise.all(promises);\n const filteredMessages = messagesRaw.filter(\n (v): v is IDecodedMessage => !!v,\n );\n\n pushMessage(filteredMessages);\n }\n\n setLoading(false);\n })\n .catch((err) => {\n setLoading(false);\n setError(\n `Failed to query messages from store: ${\n err?.message || \"no message\"\n }`,\n );\n });\n\n return () => {\n cancelled = true;\n };\n // TODO: missing dependency on options, it will prevent consecutive update if options change\n }, [node, decoder, pushMessage, setError, setLoading]);\n\n return {\n error,\n isLoading,\n messages,\n };\n};\n","import type { LightNode } from \"@waku/interfaces\";\nimport ChatList from \"./ChatList\";\nimport MessageInput from \"./MessageInput\";\nimport { useWaku, useContentPair, useLightPush } from \"@waku/react\";\nimport { ChatMessage } from \"./chat_message\";\nimport { useNodePeers, usePeers } from \"./hooks\";\nimport type { RoomProps } from \"./types\";\n\nexport default function Room(props: RoomProps) {\n const { node } = useWaku();\n const { encoder } = useContentPair();\n const { push: onPush } = useLightPush({ node, encoder });\n\n const {\n connectedBootstrapPeers,\n connectedPeerExchangePeers,\n discoveredBootstrapPeers,\n discoveredPeerExchangePeers,\n } = useNodePeers(node);\n const { allConnected, storePeers, filterPeers, lightPushPeers } = usePeers({\n node,\n });\n\n const onSend = async (text: string) => {\n if (!onPush || !text) {\n return;\n }\n\n if (text.startsWith(\"/\")) {\n props.commandHandler(text);\n } else {\n const timestamp = new Date();\n const chatMessage = ChatMessage.fromUtf8String(\n timestamp,\n props.nick,\n text\n );\n const payload = chatMessage.encode();\n\n await onPush({ payload, timestamp });\n }\n };\n\n const allConnectedLength = orZero(allConnected?.length);\n const lightPushPeersLength = orZero(lightPushPeers?.length);\n const filterPeersLength = orZero(filterPeers?.length);\n const storePeersLength = orZero(storePeers?.length);\n\n return (\n
\n
\n
\n
Peers Connected: {allConnectedLength}
\n
Store: {storePeersLength}
\n
Filter: {filterPeersLength}
\n
Light Push: {lightPushPeersLength}
\n
\n
Waku v2 Web Chat
\n
\n
\n Peers Discovered:{\" \"}\n {discoveredBootstrapPeers.size + discoveredPeerExchangePeers.size}\n
\n
\n Bootstrap: {discoveredBootstrapPeers.size} Peer Exchange:{\" \"}\n {discoveredPeerExchangePeers.size}\n
\n
\n Peers Connected:{\" \"}\n {connectedBootstrapPeers.size + connectedPeerExchangePeers.size}\n
\n
\n Bootstrap: {connectedBootstrapPeers.size} Peer Exchange:{\" \"}\n {connectedPeerExchangePeers.size}\n
\n
\n
\n \n \n
\n );\n}\n\nfunction orZero(value: undefined | number): number {\n return value || 0;\n}\n","import handleCommand from \"./command\";\nimport Room from \"./Room\";\nimport { Message } from \"./Message\";\nimport { PageDirection, LightNode } from \"@waku/interfaces\";\n\nimport { useWaku, useContentPair } from \"@waku/react\";\n\nimport { useMessages, usePersistentNick } from \"./hooks\";\n\nconst startTime = new Date();\n// Only retrieve a week of history\nstartTime.setTime(Date.now() - 1000 * 60 * 60 * 24 * 7);\nconst endTime = new Date();\n\nexport default function App() {\n const { node } = useWaku();\n const { decoder } = useContentPair();\n const [messages, pushLocalMessages] = useMessages({\n node,\n decoder,\n options: {\n pageSize: 5,\n pageDirection: PageDirection.FORWARD,\n timeFilter: {\n startTime,\n endTime,\n },\n },\n });\n\n const [nick, setNick] = usePersistentNick();\n\n const onCommand = (text: string): void => {\n handleCommand(text, node, setNick).then(({ command, response }) => {\n const commandMessages = response.map((msg) => {\n return Message.fromUtf8String(command, msg);\n });\n pushLocalMessages(commandMessages);\n });\n };\n\n return (\n \n \n
\n );\n}\n","import React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport { LightNodeProvider, ContentPairProvider } from \"@waku/react\";\nimport \"./index.css\";\n\nimport App from \"./App\";\nimport { CONTENT_TOPIC } from \"./config\";\nimport { Protocols } from \"@waku/interfaces\";\n\nReactDOM.render(\n \n \n \n \n \n \n ,\n document.getElementById(\"root\")\n);\n","export const CONTENT_TOPIC = \"/toy-chat/2/huilong/proto\";\n"],"names":["module","exports","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","charAt","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","undefined","Error","test","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","factory","Float32Array","f32","f8b","Uint8Array","le","writeFloat_f32_cpy","val","buf","pos","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","writeFloat_ieee754","writeUint","sign","isNaN","round","exponent","floor","log","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","f64","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","inquire","moduleName","mod","eval","replace","Object","keys","e","alloc","size","SIZE","MAX","slab","call","utf8","len","read","write","c1","c2","formatArgs","useColors","namespace","humanize","diff","color","lastC","match","save","namespaces","storage","setItem","removeItem","error","load","r","getItem","process","DEBUG","window","type","__nwjs","navigator","userAgent","toLowerCase","document","documentElement","style","WebkitAppearance","console","firebug","exception","table","parseInt","RegExp","$1","localStorage","localstorage","destroy","warned","warn","colors","debug","require","formatters","v","JSON","stringify","message","env","createDebug","prevTime","namespacesCache","enabledCache","enableOverride","_len","_key","enabled","self","curr","Number","Date","ms","prev","coerce","unshift","format","formatter","selectColor","extend","defineProperty","enumerable","configurable","get","set","init","delimiter","newDebug","toNamespace","regexp","toString","substring","default","stack","disable","names","map","skips","enable","split","name","forEach","key","hash","abs","Denque","array","options","_capacity","capacity","_head","_tail","isArray","_fromArray","_capacityMask","_list","peekAt","peek","peekFront","peekBack","item","_growArray","pop","shift","head","_shrinkArray","tail","removeOne","k","remove","count","removed","del_count","toArray","clear","temp","arg_len","arguments_index","leng","isEmpty","_copyArray","_nextPowerOf2","fullCopy","src","dest","newList","num","nextPow2","max","assign","obj","props","value","code","TypeError","_","ErrClass","create","getPrototypeOf","event_iterator_1","EventIterator","EventQueue","constructor","pullQueue","pushQueue","eventHandlers","isPaused","isStopped","resolution","done","placeholder","highWaterMark","highWater","concat","stop","fail","rejection","catch","then","removeCallback","Symbol","asyncIterator","next","result","lowWaterMark","lowWater","return","listen","queue","event","freeze","has","hasOwnProperty","prefix","Events","EE","context","once","addListener","emitter","listener","_events","_eventsCount","clearEvent","__proto__","eventNames","events","getOwnPropertySymbols","handlers","l","ee","listenerCount","a1","a2","a3","a4","a5","removeListener","removeAllListeners","prefixed","cache","_cache","update","root","HI_BASE32_NO_NODE_JS","versions","node","global","COMMON_JS","HI_BASE32_NO_COMMON_JS","AMD","define","BASE32_ENCODE_CHAR","BASE32_DECODE_CHAR","blocks","throwInvalidUtf8","position","partial","substr","decodeAsBytes","base32Str","v1","v2","v3","v4","v5","v6","v7","v8","bytes","remain","asciiOnly","str","followingChars","toUtf8String","indexOf","input","notString","ArrayBuffer","encodeBytes","encodeAscii","encodeUtf8","asBytes","base32","electron","INPUT_ERROR","WINDOW","JS_SHA3_NO_WINDOW","WEB_WORKER","JS_SHA3_NO_NODE_JS","JS_SHA3_NO_COMMON_JS","ARRAY_BUFFER","JS_SHA3_NO_ARRAY_BUFFER","HEX_CHARS","CSHAKE_PADDING","SHIFT","RC","BITS","SHAKE_BITS","OUTPUT_TYPES","CSHAKE_BYTEPAD","isView","JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW","formatMessage","empty","cloneArray","newArray","createOutputMethod","bits","padding","outputType","Keccak","createShakeOutputMethod","outputBits","createCshakeOutputMethod","s","methods","createKmacOutputMethod","createOutputMethods","method","createMethod","algorithms","w","bytepad","Kmac","methodNames","algorithm","methodName","newMethodName","reset","finalized","block","blockCount","byteCount","outputBlocks","extraBytes","isString","lastByteIndex","f","x","right","o","encodeString","strs","paddingBytes","zeros","finalize","hex","arrayBuffer","Uint32Array","digest","h","c0","c3","c4","c5","c6","c7","c8","c9","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","b16","b17","b18","b19","b20","b21","b22","b23","b24","b25","b26","b27","b28","b29","b30","b31","b32","b33","b34","b35","b36","b37","b38","b39","b40","b41","b42","b43","b44","b45","b46","b47","b48","b49","isOptionObject","propertyIsEnumerable","object","writable","globalThis","defaultMergeOptions","concatArrays","ignoreUndefined","getEnumerableOwnPropertyKeys","symbols","symbol","clone","cloneOptionObject","mergeKeys","merged","source","config","merge","resultIndex","indices","filter","includes","option","m","d","y","plural","msAbs","isPlural","exec","parseFloat","parse","isFinite","long","fmtLong","fmtShort","Netmask","atob","chr","chr0","chrA","chra","ip2long","long2ip","ip","ref","base","dmax","net","mask","maskLong","error1","bitmask","netLong","hostmask","first","last","broadcast","contains","lastLong","forge","registerAlgorithm","mode","cipher","aes","Algorithm","startEncrypting","iv","output","_createCipher","decrypt","createEncryptionCipher","startDecrypting","createDecryptionCipher","initialize","blockSize","encrypt","inBlock","outBlock","_updateBlock","_w","_init","tmp","util","createBuffer","putByte","getInt32","encryptOp","_expandKey","modes","ecb","cbc","cfb","ofb","ctr","gcm","sbox","isbox","rcon","mix","imix","Nb","xtime","e2","e4","e8","sx","sx2","me","ime","ei","iNk","Nk","m0","m1","m2","m3","wnew","wi","sub","a","Nr","toUpperCase","createDecipher","createCipher","ByteBuffer","asn1","_checkBufferLength","remaining","available","requested","Class","UNIVERSAL","APPLICATION","CONTEXT_SPECIFIC","PRIVATE","Type","NONE","BOOLEAN","INTEGER","BITSTRING","OCTETSTRING","NULL","OID","ODESC","EXTERNAL","REAL","ENUMERATED","EMBEDDED","UTF8","ROID","SEQUENCE","SET","PRINTABLESTRING","IA5STRING","UTCTIME","GENERALIZEDTIME","BMPSTRING","tagClass","constructed","composed","bitStringContents","original","copy","excludeBitStringContents","equals","obj1","obj2","equal","includeBitStringContents","getBerValueLength","getByte","getInt","_fromDer","depth","longFormBytes","_getValueLength","strict","getBytes","decodeBitStrings","savedRead","savedRemaining","unused","used","tc","ex","getInt16","asn1Options","fromDer","parseAllBytes","toDer","useBitStringContents","putBytes","putBuffer","putInt16","lenBytes","oidToDer","oid","valueBytes","values","derToOid","utcTimeToDate","utc","date","year","MM","DD","hh","mm","ss","setUTCFullYear","setUTCHours","setTime","generalizedTimeToDate","gentime","YYYY","fff","isUTC","setFullYear","setHours","dateToUtcTime","rval","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","dateToGeneralizedTime","integerToDer","putSignedInt","integer","derToInteger","getSignedInt","validate","capture","errors","optional","captureAsn1","captureBitStringContents","captureBitStringValue","_nonLatinRegex","prettyPrint","level","indentation","indent","IA5String","subvalues","pki","oids","bytesToHex","decodeUtf8","api","_reverseAlphabets","alphabet","maxline","digits","carry","at","_encodeWithByteBuffer","regex","Buffer","from","reverse","getAlgorithm","BlockCipher","_finish","_input","_op","_decrypt","opts","compact","finish","pad","unpad","overflow","afterFinish","transformIV","ints","inc32","from64To32","_ints","_inBlock","_outBlock","putInt32","fillWithByte","truncate","_prev","_iv","_partialBlock","_partialOutput","_partialBytes","inputLength","partialBytes","_R","additionalData","_cipherLength","_tagLength","tagLength","_tag","tag","_hashBlock","_hashSubkey","componentBits","_m","generateHashTable","ivLength","_j0","ghash","_aDataLength","_s","lengths","multiply","z_i","v_i","out","lsb","tableMultiply","z","x_i","ah","multiplier","perInt","shft","generateSubHashTable","mid","half","m_i","m_j","des","_keys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","iterations","shifts","left","lefttmp","righttmp","_createKeys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","looping","endloop","loopinc","right1","right2","usePureJavaScript","hmac","_md","_ipadding","_opadding","md","keylen","blockLength","inner","getMac","dbits","jsbn","BigInteger","data","fromNumber","fromString","nbi","am3","xl","xh","am","appName","DB","DM","DV","FV","F1","F2","rr","vv","BI_RM","BI_RC","int2char","intAt","nbv","fromInt","nbits","Classic","Montgomery","mp","invDigit","mpl","mph","um","mt2","op_and","op_or","op_xor","op_andnot","lbit","cbit","NullExp","nNop","Barrett","r2","q3","ONE","dlShiftTo","mu","divide","convert","compareTo","revert","reduce","divRemTo","mulTo","multiplyTo","sqrTo","squareTo","ZERO","subTo","copyTo","u0","clamp","drShiftTo","fromRadix","mi","sh","lShiftTo","bs","cbs","bm","ds","rShiftTo","min","q","pm","pt","ts","nsh","ys","y0","yt","d1","d2","qd","isEven","exp","g","negate","toRadix","km","bitLength","modPowInt","multiplyUpperTo","multiplyLowerTo","dAddOffset","lowprimes","lplim","chunkSize","signum","cs","intValue","dMultiply","testBit","bitwiseTo","shiftLeft","isProbablePrime","nextBytes","op","changeBit","addTo","modInt","millerRabin","n1","subtract","getLowestSetBit","shiftRight","prng","random","modPow","byteValue","shortValue","toByteArray","and","or","xor","andNot","not","bitCount","setBit","clearBit","flipBit","add","remainder","divideAndRemainder","k1","g2","is1","modInverse","ac","u","gcd","_IN","id","_I_","pbe","encryptedPrivateKeyValidator","PBES2AlgorithmsValidator","pkcs12PbeParamsValidator","prfOidToMessageDigest","prfOid","prfAlgorithm","supported","prfAlgorithmToMessageDigest","sha512","encryptPrivateKeyInfo","password","saltSize","dkLen","encryptionAlgorithm","encryptedData","salt","getBytesSync","countBytes","ivLen","encOid","cipherFn","dk","pkcs5","pbkdf2","hexToBytes","createPbkdf2Params","saltBytes","generatePkcs12Key","decryptPrivateKeyInfo","encryptionOid","getCipher","encryptionParams","encrypted","encryptedPrivateKeyToPem","epki","msg","body","pem","encryptedPrivateKeyFromPem","headerType","procType","encryptRsaPrivateKey","rsaKey","legacy","wrapRsaPrivateKey","privateKeyToAsn1","opensslDeriveBytes","version","dekInfo","parameters","decryptRsaPrivateKey","rc2","privateKeyFromAsn1","iter","sha1","digestLength","passBuf","D","Slen","S","Plen","P","I","B","Inew","setAt","getCipherForPBES2","getCipherForPKCS12PBE","supportedOids","kdfOid","kdfSalt","kdfIterationCount","encIv","dIvLen","md5","digests","crypto","isNodejs","callback","pbkdf2Sync","hLen","prf","u_c","u_c1","int32ToBytes","xorBytes","outer","setImmediate","foldHeader","header","insertSpace","candidate","insert","ltrim","contentDomain","headers","encode64","rMessage","rHeader","rCRLF","decode64","lines","li","line","nl","vi","pkcs1","rsa_mgf1","seed","maskLength","encode_rsa_oaep","label","mgf1Md","mgf1","keyLength","maxLength","lHash","PS","PS_length","seedLength","dbMask","maskedDB","seedMask","decode_rsa_oaep","em","expectedLength","maskedSeed","db","lHashPrime","in_ps","prime","GCD_30_DELTA","THIRTY","generateProbablePrime","rng","Worker","primeincFindPrimeWithoutWorkers","generateRandom","numWorkers","workers","workLoad","range","workerScript","estimateCores","cores","generate","addEventListener","workerMessage","found","terminate","target","postMessage","primeincFindPrimeWithWorkers","primeincFindPrime","mrTests","getMillerRabinTests","millerRabinTests","maxBlockTime","_primeinc","deltaIdx","bits1","_crypto","plugin","time","reseeds","generated","keyBytes","pools","_reseedSync","messageLength","_seed","needed","collect","seedFileSync","_2powK","seedBytes","formatKey","formatSeed","defaultSeedFile","getRandomValues","globalScope","msCrypto","arr","entropy","QuotaExceededError","pool","generateSync","increment","nextTick","seedFile","_reseed","randomBytes","collectInt","registerWorker","worker","removeEventListener","jQuery","prng_aes","_prng_aes_output","_prng_aes_buffer","spawnPrng","sha256","_ctx","_navBytes","mousemove","clientX","clientY","keypress","charCode","createInstance","piTable","rol","word","ror","expandKey","effKeyBits","L","T","T1","T8","TM","mixRound","mashRound","_output","K","getInt16Le","R","runPlan","plan","putInt16Le","ptr","rsa","privateKeyValidator","rsaPrivateKeyValidator","rsaPublicKeyValidator","publicKeyValidator","digestInfoValidator","emsaPkcs1v15encode","oidBytes","digestInfo","digestAlgorithm","_modPow","pub","dP","dQ","qInv","xp","xq","_encodePkcs1_v1_5","bt","eb","padByte","padNum","numZeros","padBytes","_decodePkcs1_v1_5","ml","_bnToBytes","_getMillerRabinTests","_detectNodeCrypto","_detectSubtleCrypto","subtle","_detectSubtleMsCrypto","_intToUint8Array","toHex","yhex","ed","expected","xhex","createKeyPairGenerationState","state","eInt","qBits","pBits","pqState","stepKeyPairGenerationState","t2","t1","total","p1","q1","phi","privateKey","setPrivateKey","publicKey","setPublicKey","generateKeyPair","modulusLength","publicExponent","publicKeyEncoding","privateKeyEncoding","priv","privateKeyFromPem","publicKeyFromPem","generateKey","pair","exportKey","pkcs8","setRsaPublicKey","genOp","oncomplete","exportOp","onerror","keypair","generateKeyPairSync","getPrime","_generateKeyPair","scheme","schemeOptions","signature","_parseAllDigestBytes","verify","algorithmIdentifier","md2","sha224","sha384","setRsaPrivateKey","rsaEncryption","privateKeyModulus","privateKeyPublicExponent","privateKeyPrivateExponent","privateKeyPrime1","privateKeyPrime2","privateKeyExponent1","privateKeyExponent2","privateKeyCoefficient","privateKeyToRSAPrivateKey","publicKeyFromAsn1","publicKeyOid","rsaPublicKey","publicKeyModulus","publicKeyExponent","publicKeyToAsn1","publicKeyToSubjectPublicKeyInfo","publicKeyToRSAPublicKey","_initialized","_padding","fillString","_state","fullMessageLength","messageLengthSize","messageLength64","int32s","h0","h1","h2","h3","h4","encoding","_update","finalBlock","s2","_k","h5","h6","h7","s0","maj","_states","_h","messageLength128","hlen","t1_hi","t1_lo","t2_hi","t2_lo","s0_hi","s0_lo","s1_hi","ch_hi","maj_hi","maj_lo","a_hi","a_lo","b_hi","b_lo","c_hi","c_lo","d_hi","d_lo","e_hi","e_lo","f_hi","f_lo","g_hi","g_lo","h_hi","h_lo","w2","w7","w15","w16","baseN","_checkBitsParam","ByteStringBuffer","isArrayBuffer","isArrayBufferView","_constructedStringLength","browser","setTimeout","callbacks","stopPropagation","MutationObserver","now","attr","div","createElement","observe","attributes","oldSetImmediate","setAttribute","byteLength","_optimizeConstructedString","putString","putInt24","putInt24Le","putInt32Le","putInt","getInt24","getInt24Le","getInt32Le","DataBuffer","readOffset","growSize","DataView","byteOffset","writeOffset","accommodate","amount","dst","setUint8","view","binary","raw","Uint16Array","text","utf16","setInt16","setInt8","setInt32","getInt8","getUint8","s1","s3","_base64","_base64Idx","_base58","chr1","chr2","chr3","enc1","enc2","enc3","enc4","unescape","encodeURIComponent","decodeURIComponent","escape","base58","subarray","deflate","inflate","_setStorageObject","_getStorageObject","_setItem","_getItem","_removeItem","prop","_clearItems","_callStorageFunction","func","location","idx","clearItems","part","re","argi","lastIndex","formatNumber","number","decimals","dec_point","thousands_sep","toFixed","formatSize","bytesFromIP","bytesFromIPv4","bytesFromIPv6","blanks","bytesToIP","bytesToIPv4","bytesToIPv6","zeroGroups","zeroMaxGroup","group","hardwareConcurrency","Blob","blobUrl","URL","createObjectURL","st","et","sample","samples","avg","revokeObjectURL","results","overlaps","r1","overlap","propIsEnumerable","test1","getOwnPropertyNames","test2","test3","letter","shouldUseNative","to","toObject","Reader","BufferReader","LongBits","indexOutOfRange","reader","writeLength","RangeError","create_array","isBuffer","readLongVarint","readFixed32_end","readFixed64","_slice","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","nativeBuffer","skip","skipType","wireType","_configure","BufferReader_","Long","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","zero","toNumber","zzEncode","zeroHash","low","high","unsigned","toLong","Boolean","fromHash","toHash","part0","part1","part2","ifNotSet","newError","CustomError","properties","captureStackTrace","asPromise","isNode","emptyArray","emptyObject","isInteger","isObject","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","newBuffer","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","lcFirst","ProtocolError","oneOfGetter","fieldNames","fieldMap","oneOfSetter","toJSONOptions","longs","enums","json","allocUnsafe","Writer","BufferWriter","Op","noop","State","writer","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","fork","ldelim","BufferWriter_","writeStringBuffer","writeBytesBuffer","BufferSourceConverter","toArrayBuffer","toUint8Array","toView","isBufferSource","isEqual","aView","bView","buffers","Function","res","STRING_TYPE","HEX_REGEX","BASE64_REGEX","BASE64URL_REGEX","Utf8Converter","uintArray","encodedString","Utf16Converter","littleEndian","dataView","getUint16","setUint16","Convert","isHex","isBase64","isBase64Url","ToString","enc","ToUtf8String","ToBinary","ToHex","ToBase64","ToBase64Url","FromString","FromUtf8String","FromBinary","FromHex","FromBase64","FromBase64Url","btoa","formatted","formatString","base64url","Base64Padding","DEFAULT_UTF8_ENCODING","stringLength","resultView","byte","hexString","ToUtf16String","FromUtf16String","padCount","aa","ba","Set","ca","da","ea","fa","ha","ia","ja","ka","acceptsBooleans","attributeName","attributeNamespace","mustUseProperty","propertyName","sanitizeURL","removeEmptyString","oa","pa","qa","ma","na","la","removeAttribute","setAttributeNS","xlinkHref","ra","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","sa","ta","ua","wa","xa","ya","za","Aa","Ba","Ca","Da","Ea","Fa","Ga","Ha","Ia","Ja","for","E","Ma","Ka","iterator","La","Na","trim","Oa","Pa","prepareStackTrace","Reflect","construct","displayName","Qa","render","_render","Ra","$$typeof","_context","_payload","Sa","Ta","nodeName","Va","_valueTracker","getOwnPropertyDescriptor","getValue","setValue","stopTracking","Ua","Wa","checked","Xa","activeElement","Ya","defaultChecked","defaultValue","_wrapperState","initialChecked","Za","initialValue","controlled","$a","ab","bb","cb","ownerDocument","children","Children","fb","selected","defaultSelected","disabled","gb","dangerouslySetInnerHTML","hb","ib","jb","textContent","kb","html","mathml","svg","lb","mb","nb","ob","namespaceURI","innerHTML","valueOf","firstChild","removeChild","appendChild","MSApp","execUnsafeLocalFunction","pb","lastChild","nodeType","nodeValue","qb","animationIterationCount","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth","rb","sb","tb","setProperty","ub","menuitem","area","br","col","embed","hr","img","keygen","link","meta","param","track","wbr","vb","wb","is","xb","srcElement","correspondingUseElement","parentNode","yb","zb","Ab","Bb","Cb","stateNode","Db","Eb","Fb","Gb","Hb","Ib","Jb","Kb","Lb","Mb","Ob","Pb","Qb","Rb","onError","Sb","Tb","Ub","Vb","Wb","Xb","Zb","alternate","flags","$b","memoizedState","dehydrated","cc","child","sibling","current","bc","dc","ec","fc","gc","hc","ic","jc","kc","lc","mc","nc","Map","oc","pc","qc","rc","blockedOn","domEventName","eventSystemFlags","nativeEvent","targetContainers","sc","delete","pointerId","vc","wc","lanePriority","unstable_runWithPriority","priority","hydrate","containerInfo","xc","yc","zc","Ac","Bc","unstable_scheduleCallback","unstable_NormalPriority","Cc","Dc","Ec","animationend","animationiteration","animationstart","transitionend","Fc","Gc","Hc","animation","transition","Ic","Jc","Kc","Lc","Mc","Nc","Oc","Pc","Qc","unstable_now","F","Rc","Uc","pendingLanes","expiredLanes","suspendedLanes","pingedLanes","Vc","entangledLanes","entanglements","Wc","Xc","Yc","Zc","$c","eventTimes","clz32","bd","cd","dd","unstable_UserBlockingPriority","fd","gd","hd","uc","jd","kd","ld","nd","od","keyCode","pd","rd","_reactName","_targetInst","currentTarget","isDefaultPrevented","defaultPrevented","returnValue","isPropagationStopped","preventDefault","cancelBubble","persist","isPersistent","wd","xd","yd","sd","eventPhase","bubbles","cancelable","timeStamp","isTrusted","td","ud","detail","vd","Ad","screenX","screenY","pageX","pageY","ctrlKey","shiftKey","altKey","metaKey","getModifierState","zd","button","buttons","relatedTarget","fromElement","toElement","movementX","movementY","Bd","Dd","dataTransfer","Fd","Hd","animationName","elapsedTime","pseudoElement","Id","clipboardData","Jd","Ld","Md","Esc","Spacebar","Left","Up","Right","Down","Del","Win","Menu","Apps","Scroll","MozPrintableKey","Nd","Od","Alt","Control","Meta","Shift","Pd","Qd","repeat","locale","which","Rd","Td","width","height","pressure","tangentialPressure","tiltX","tiltY","twist","pointerType","isPrimary","Vd","touches","targetTouches","changedTouches","Xd","Yd","deltaX","wheelDeltaX","deltaY","wheelDeltaY","wheelDelta","deltaZ","deltaMode","Zd","$d","ae","be","documentMode","ce","de","fe","ge","he","ie","datetime","email","month","search","tel","url","week","ne","oe","pe","qe","se","te","ue","ve","we","xe","ye","ze","oninput","Ae","detachEvent","Be","Ce","attachEvent","De","Ee","Fe","He","Ie","Je","Ke","Le","nextSibling","Me","compareDocumentPosition","Ne","HTMLIFrameElement","contentWindow","href","Oe","contentEditable","Pe","Qe","Re","Se","Te","Ue","selectionStart","selectionEnd","anchorNode","defaultView","getSelection","anchorOffset","focusNode","focusOffset","Ve","We","Xe","Ye","Ze","Yb","instance","G","$e","af","bf","cf","df","passive","ef","ff","parentWindow","gf","hf","J","Q","je","char","ke","jf","kf","lf","mf","autoFocus","nf","__html","of","pf","clearTimeout","qf","rf","sf","previousSibling","tf","vf","wf","xf","yf","zf","Af","Bf","H","Cf","M","N","Df","Ef","contextTypes","__reactInternalMemoizedUnmaskedChildContext","__reactInternalMemoizedMaskedChildContext","Ff","childContextTypes","Gf","Hf","If","getChildContext","Jf","__reactInternalMemoizedMergedChildContext","Kf","Lf","Mf","Nf","Of","Pf","unstable_cancelCallback","Qf","unstable_shouldYield","Rf","unstable_requestPaint","Sf","Tf","unstable_getCurrentPriorityLevel","Uf","unstable_ImmediatePriority","Vf","Wf","Xf","unstable_LowPriority","Yf","unstable_IdlePriority","Zf","$f","ag","bg","cg","dg","O","eg","fg","gg","hg","ig","jg","kg","ReactCurrentBatchConfig","lg","defaultProps","mg","ng","og","pg","qg","rg","_currentValue","sg","childLanes","tg","dependencies","firstContext","lanes","ug","vg","observedBits","responders","wg","xg","updateQueue","baseState","firstBaseUpdate","lastBaseUpdate","shared","effects","yg","zg","eventTime","lane","payload","Ag","Bg","Cg","A","C","Dg","Eg","Fg","Component","refs","Gg","Kg","isMounted","_reactInternals","enqueueSetState","Hg","Ig","Jg","enqueueReplaceState","enqueueForceUpdate","Lg","shouldComponentUpdate","isPureReactComponent","Mg","contextType","updater","Ng","componentWillReceiveProps","UNSAFE_componentWillReceiveProps","Og","getDerivedStateFromProps","getSnapshotBeforeUpdate","UNSAFE_componentWillMount","componentWillMount","componentDidMount","Pg","Qg","_owner","_stringRef","Rg","Sg","lastEffect","nextEffect","firstEffect","Tg","Ug","elementType","Vg","implementation","Wg","Xg","Yg","Zg","$g","bh","ch","dh","eh","tagName","fh","gh","ih","memoizedProps","revealOrder","jh","kh","lh","mh","nh","oh","pendingProps","ph","qh","rh","th","uh","_workInProgressVersionPrimary","vh","ReactCurrentDispatcher","wh","yh","zh","Ah","Bh","Ch","Dh","Eh","Fh","Gh","Hh","baseQueue","Ih","Jh","Kh","lastRenderedReducer","action","eagerReducer","eagerState","lastRenderedState","dispatch","Lh","Mh","_getVersion","_source","mutableReadLanes","Nh","U","useState","getSnapshot","subscribe","useEffect","setSnapshot","Oh","Ph","Qh","Rh","deps","Sh","Th","Uh","Vh","Wh","Xh","Yh","Zh","$h","ai","bi","ci","di","readContext","useCallback","useContext","useImperativeHandle","useLayoutEffect","useMemo","useReducer","useRef","useDebugValue","useDeferredValue","useTransition","useMutableSource","useOpaqueIdentifier","unstable_isNewReconciler","uf","ReactCurrentOwner","fi","gi","ii","ji","compare","ki","baseLanes","ni","oi","pi","UNSAFE_componentWillUpdate","componentWillUpdate","componentDidUpdate","qi","getDerivedStateFromError","ri","pendingContext","Bi","Ci","Di","Ei","si","retryLane","ti","fallback","unstable_avoidThisFallback","ui","unstable_expectedLoadTime","xi","yi","zi","isBackwards","rendering","renderingStartTime","tailMode","Ai","Fi","Gi","wasMultiple","multiple","onClick","onclick","createElementNS","createTextNode","V","Hi","Ii","W","Ji","Ki","Li","Mi","Ni","Oi","WeakMap","Pi","element","Qi","Ri","Si","componentDidCatch","Ti","componentStack","Ui","WeakSet","Vi","Wi","Xi","__reactInternalSnapshotBeforeUpdate","Yi","Zi","$i","focus","aj","display","bj","onCommitFiberUnmount","componentWillUnmount","cj","dj","ej","fj","gj","hj","insertBefore","_reactRootContainer","ij","jj","kj","lj","mj","nj","oj","pj","X","Y","qj","rj","sj","tj","uj","vj","wj","ck","Z","xj","yj","zj","Aj","Bj","Cj","Dj","Ej","Fj","Gj","Hj","Ij","Jj","Sc","Kj","Lj","Mj","callbackNode","expirationTimes","callbackPriority","Tc","Nj","Oj","Pj","Qj","Rj","Sj","Tj","finishedWork","finishedLanes","Uj","timeoutHandle","Wj","Xj","pingCache","Yj","Zj","va","ak","bk","rangeCount","focusedElem","selectionRange","ek","createRange","setStart","removeAllRanges","addRange","setEnd","scrollLeft","top","scrollTop","onCommitFiberRoot","fk","gk","ik","isReactComponent","pendingChildren","jk","mutableSourceEagerHydrationData","lk","mk","nk","ok","qk","hydrationOptions","mutableSources","_internalRoot","rk","tk","hasAttribute","sk","uk","kk","hk","_calculateChangedBits","unstable_observedBits","unmount","querySelectorAll","form","Vj","vk","wk","findFiberByHostInstance","bundleType","rendererPackageName","xk","rendererConfig","overrideHookState","overrideHookStateDeletePath","overrideHookStateRenamePath","overrideProps","overridePropsDeletePath","overridePropsRenamePath","setSuspenseHandler","scheduleUpdate","currentDispatcherRef","findHostInstanceByFiber","findHostInstancesForRefresh","scheduleRefresh","scheduleRoot","setRefreshHandler","getCurrentFiber","__REACT_DEVTOOLS_GLOBAL_HOOK__","yk","isDisabled","supportsFiber","inject","createPortal","findDOMNode","flushSync","unmountComponentAtNode","unstable_batchedUpdates","unstable_createPortal","unstable_renderSubtreeIntoContainer","checkDCE","__self","__source","jsx","jsxs","Fragment","StrictMode","Profiler","Suspense","setState","forceUpdate","_status","_result","IsSomeRendererActing","only","PureComponent","cloneElement","createContext","_currentValue2","_threadCount","Provider","Consumer","createFactory","createRef","forwardRef","isValidElement","lazy","memo","performance","MessageChannel","unstable_forceFrameRate","cancelAnimationFrame","requestAnimationFrame","port2","port1","onmessage","sortIndex","startTime","expirationTime","priorityLevel","unstable_Profiling","unstable_continueExecution","unstable_getFirstCallbackNode","unstable_next","unstable_pauseExecution","delay","unstable_wrapCallback","Nouns","Adjectives","data_1","generator_1","counter","REST","MSB","MAX_SAFE_INTEGER","oldOffset","INT","MSBALL","encodingLength","N1","N2","N3","N4","N5","N6","N7","N8","N9","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","leafPrototypes","getProto","__esModule","ns","def","definition","toStringTag","_typeof","toPropertyKey","toPrimitive","encodeUint8Array","decodeUint8Array","encodeUint8ArrayList","decodeUint8ArrayList","d8b","MAX_SAFE_NUMBER_INTEGER","BigInt","MIN_SAFE_NUMBER_INTEGER","MIN_SAFE_INTEGER","_defineProperty","toBigInt","fromBigInt","negative","TWO_32","readFixed32End","Uint8ArrayReader","_parts","int64Number","int64String","uint64Number","uint64String","sint64Number","sint64String","fixed64Number","fixed64String","sfixed64Number","sfixed64String","decodeMessage","codec","createReader","ALPHABET","BASE_MAP","BASE","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","it3","it4","vch","pbegin","pend","b58","it1","it2","Encoder","baseEncode","Decoder","baseDecode","codePointAt","prefixCodePoint","decoder","ComposedDecoder","decoders","_left$decoders","_right$decoders","Codec","encoder","_ref","baseX","_ref2","basex","rfc4648","_ref3","bitsPerChar","codes","written","SyntaxError","base10","base16","base16upper","base2","alphabetBytesToChars","alphabetCharsToBytes","base256emoji","byts","byt","base32upper","base32pad","base32padupper","base32hex","base32hexupper","base32hexpad","base32hexpadupper","base32z","base36","base36upper","base58btc","base58flickr","base64pad","base64urlpad","base8","identity","TextDecoder","TextEncoder","textEncoder","textDecoder","encode_1","REST$1","MSB$1","encodeTo","int","varint","sizeOffset","digestOffset","Digest","Hasher","sha","async","bases","identityBase","createCodec","ascii","latin1","bufferPool","Uint8ArrayWriter","writeVarint32","super","uint8ArrayFromString","encodeMessage","lengthDelimited","CODEC_TYPES","RateLimitProof","WakuMessage","FilterRequest","MessagePush","FilterRpc","TopicOnlyMessage","FilterSubscribeRequest","FilterSubscribeResponse","PushRequest","PushResponse","PushRpc","Index","PagingInfo","ContentFilter","HistoryQuery","HistoryResponse","HistoryRpc","PeerInfo","PeerExchangeQuery","PeerExchangeResponse","PeerExchangeRPC","WakuMetadataRequest","WakuMetadataResponse","enumeration","findValue","VARINT","enumValue","LENGTH_DELIMITED","isDefined","groupByContentTopic","groupedDecoders","decs","contentTopic","_codec","proof","merkleRoot","epoch","shareX","shareY","nullifier","rlnIdentifier","timestamp","rateLimitProof","ephemeral","topic","contentFilters","messages","requestId","request","FilterSubscribeType","__FilterSubscribeTypeValues","filterSubscribeType","pubsubTopic","contentTopics","SUBSCRIBER_PING","statusCode","statusDesc","wakuMessage","isSuccess","info","response","receiverTime","senderTime","Direction","__DirectionValues","pageSize","cursor","direction","pagingInfo","endTime","HistoryError","__HistoryErrorValues","query","enr","numPeers","peerInfos","clusterId","shards","toAsyncIterator","receiver","iteratorOptions","_iteratorOptions$iter","_iteratorOptions$time","iteratorDelay","unsubscribe","isWithTimeout","timeoutMs","wait","isWireSizeUnderCap","isSafeInteger","outputLen","blockLen","exists","checkFinished","destroyed","finished","createView","rotr","asyncLoop","iters","tick","utf8ToBytes","toBytes","abytes","concatBytes","sum","Hash","_cloneInto","toStr","wrapConstructor","hashCons","hashC","bytesLength","Maj","HashMD","padOffset","isLE","take","roundClean","digestInto","fill","setBigUint64","_32n","_u32_max","wl","setUint32","oview","outLen","SHA256_K","SHA256_IV","SHA256_W","SHA256","getUint32","W15","W2","T2","Chi","Protocols","PageDirection","Tags","EPeersByDiscoveryEvents","EConnectionStateEvents","DefaultPubsubTopic","DEFAULT_CLUSTER_ID","bytesToUtf8","byteArrays","totalLength","acc","singleShardInfoToPubsubTopic","shardInfo","shard","shardInfoToPubsubTopics","contentTopicToPubsubTopic","_shardInfo$clusterId","application","pubsubTopicToSingleShardInfo","pubsubTopics","ensurePubsubTopicIsConfigured","configuredTopics","contentTopicToShardIndex","networkShards","generation","fields","topicName","ensureValidContentTopic","dataview","getBigUint64","shardIndex","determinePubsubTopic","pubsubTopicShardInfo","ensureShardingConfigured","_shardInfo$clusterId2","isShardsConfigured","isContentTopicsConfigured","isApplicationVersionConfigured","shardingParams","pushOrInitMapSet","newValue","decodeRelayShard","byteIndex","bitIndex","numIndices","encodeRelayShard","APP_NAME","Logger","createDebugNamespace","_info","_warn","_error","logger","OneMillion","DecodedMessage","proto","_rawTimestamp","_this$proto$version","metaSetter","toWire","toProtoObj","_message$timestamp","protoMessage","createEncoder","fromWireToProtoObj","_protoMessage$version","_protoMessage$timesta","_protoMessage$meta","_protoMessage$rateLim","_protoMessage$ephemer","fromProtoObj","_proto$version","createDecoder","messageHashStr","pubsubTopicBytes","contentTopicBytes","messageHash","entry","arrays","findBufAndOffset","bufs","bufEnd","isUint8ArrayList","Uint8ArrayList","appendAll","append","_len2","_key2","prepend","_len3","_key3","prependAll","consume","trunc","beginInclusive","endExclusive","_subList","sublist","list","_beginInclusive","_endExclusive","bufStart","sliceStartInBuf","sliceEndsInBuf","_offset","needle","rightmostPositions","Int32Array","lastPatIndex","getBigInt64","setBigInt64","getFloat32","setFloat32","getFloat64","setFloat64","other","fromUint8Arrays","isAsyncIterable","thing","defaultEncoder","lengthLength","lengthBuf","_options","_options$lengthEncode","encodeLength","lengthEncoder","maybeYield","single","_options2","_options$lengthEncode2","ReadMode","defaultDecoder","_options$lengthDecode","_options$maxLengthLen","_options$maxDataLengt","LENGTH","dataLength","lengthDecoder","maxLengthLength","maxDataLength","errCode","dataLengthLength","onLength","DATA","onData","pDefer","deferred","promise","fromReader","FixedFIFO","hwm","btm","FIFO","_options$splitLimit","splitLimit","calculateSize","_val","AbortError","pushable","_pushable","getNext","onNext","ended","onEnd","drain","bufferNext","objectMode","bufferError","queueMicrotask","_return","throw","readableLength","onEmpty","signal","throwIfAborted","cancel","race","sources","syncSources","all","pipe","isDuplex","duplex","isIterable","rest","fns","sink","duplexPipelineFn","rawPipe","stream","sourceWrap","StreamManager","multicodec","getConnections","peer","protocols","prepareNewStream","handlePeerUpdateStreamPool","getStream","streamPool","peerIdStr","streamPromise","newStream","status","connection","connections","latestConnection","timeline","open","selectConnection","BaseProtocol","components","addLibp2pEventListener","removeLibp2pEventListener","streamManager","connectionManager","peerStore","allPeers","peers","getPeersForProtocol","connectedPeers","getPeers","_this$options","maxBootstrapPeers","connectedPeersForProtocolAndShard","peerPromises","remotePeer","some","protocol","encodedPeerShardInfo","metadata","peerShardInfo","getConnectedPeersForProtocolAndShard","filteredPeers","bootstrapPeers","tags","BOOTSTRAP","nonBootstrapPeers","selectedPeers","randomIndex","randomPeer","filterPeersByDiscovery","sortedFilteredPeers","pingBytes","ping","sort","sortPeersByLatency","randomUUID","rnds8","byteToHex","unsafeStringify","native","rnds","FilterPushRpc","FilterSubscribeRpc","createSubscribeRequest","uuid","SUBSCRIBE","createUnsubscribeRequest","UNSUBSCRIBE","createUnsubscribeAllRequest","UNSUBSCRIBE_ALL","createSubscriberPingRequest","FilterCodecs","Subscription","remotePeers","subscriptionCallbacks","decodersArray","decodersGroupedByCT","promises","lp","allSettled","handleErrors","subscriptionCallback","unsubscribeRequest","unsubscribeAll","processMessage","hashedMessageStr","receivedMessagesHashStr","decodePromises","dec","decoded","decodedMessage","any","pushMessage","rejectedResult","reason","errorCounts","uniqueErrorMessages","Filter","getActiveSubscription","activeSubscriptions","setActiveSubscription","subscription","libp2p","_options$numPeersToUs","numPeersToUse","handle","onRequest","createSubscription","_this$getActiveSubscr","toSubscriptionIterator","streamData","createRequest","LightPushCore","preparePushMessage","EMPTY_PAYLOAD","isMessageSizeUnderCap","SIZE_TOO_BIG","ENCODE_FAILED","GENERIC_FAIL","send","preparationError","success","failure","peerId","REMOTE_PEER_FAULT","DECODE_FAILED","REMOTE_PEER_REJECTED","EmptyMessage","createQuery","pageDirection","BACKWARD","FORWARD","directionToProto","StoreCore","queryPerPage","queryOpts","currentCursor","_response$pagingInfo","_response$pagingInfo2","_historyRpcQuery$quer","historyRpcQuery","reply","protoMsg","wire","nextCursor","responsePageSize","queryPageSize","TimeoutError","getDOMException","errorMessage","DOMException","getAbortedReason","pTimeout","milliseconds","customTimers","timer","cancelablePromise","aborted","POSITIVE_INFINITY","timeoutError","finally","normalizeEmitter","pEvent","arrayPromise","_options$signal","rejectionEvents","multiArgs","resolveImmediately","flat","items","onItem","arguments_","rejectHandler","rejectionEvent","timeout","pEventMultiple","waitForRemotePeer","waku","_protocols","relay","Relay","store","Store","lightPush","LightPush","getEnabledProtocols","isStarted","getMeshPeers","gossipSub","waitForGossipSubPeerInMesh","waitForConnectedPeer","services","rejectReason","awaitTimeout","rejectOnTimeout","metadataService","confirmOrAttemptHandshake","_evt$detail","_resolve","_checkPrivateRedeclaration","privateCollection","_classPrivateFieldInitSpec","privateMap","_assertClassBrand","_classPrivateFieldGet2","setMaxListeners","eventTargets","TypedEventEmitter","EventTarget","_classPrivateFieldGet","dispatchEvent","safeDispatchEvent","CustomEvent","CustomEventPolyfill","Event","_globalThis$CustomEve","KeepAliveManager","pingKeepAliveTimers","relayKeepAliveTimers","libp2pPing","pingKeepAlive","pingPeriodSecs","relayKeepAlive","relayPeriodSecs","interval","setInterval","patch","intervals","scheduleRelayPings","_this$relayKeepAliveT","clearInterval","stopAll","connectionsExist","ConnectionManager","isConnected","online","toggleOnline","CONNECTION_STATUS","toggleOffline","keepAliveOptions","instances","getPeersByDiscovery","peersDiscovered","peersConnected","conn","peersDiscoveredByBootstrap","peersDiscoveredByPeerExchange","peersDiscoveredByLocal","peersConnectedByBootstrap","peersConnectedByPeerExchange","peersConnectedByLocal","getTagNamesForPeer","PEER_EXCHANGE","LOCAL","DISCOVERED","CONNECTED","configuredPubsubTopics","dispatchDiscoveryEvent","attemptDial","keepAliveManager","maxBootstrapPeersAllowed","dropConnection","PEER_CONNECT_BOOTSTRAP","PEER_CONNECT_PEER_EXCHANGE","maxDialAttemptsForPeer","maxParallelDials","run","dialPeerStorePeers","dialPromises","peerInfo","find","startPeerDiscoveryListener","startPeerConnectionListener","startPeerDisconnectionListener","onEventHandlers","dialPeer","currentActiveParallelDialCount","dialAttempt","dial","dialAttemptsForPeer","AggregateError","dialErrorsForPeer","processDialQueue","hangUp","pendingPeerDialQueue","shouldDialPeer","isPeerTopicConfigured","getPeerShardInfo","isPeerDialableBasedOnBootstrapStatus","isBootstrap","PEER_DISCOVERY_BOOTSTRAP","PEER_DISCOVERY_PEER_EXCHANGE","shardInfoBytes","MetadataCodec","Metadata","libp2pComponents","registrar","encodedShardInfo","proto_metadata","encodedResponse","decodeMetadataResponse","savePeerShardInfo","NO_PEER_AVAILABLE","handshakesConfirmed","wakuMetadata","raceSignal","errorCode","QueuelessPushable","readNext","haveNext","nextResult","CodeError","byteStream","readBuffer","abortPromise","_options$signal2","_options$signal3","_options$signal4","unwrap","originalStream","yieldBytes","lpStream","_opts$lengthDecoder","_opts$lengthEncoder","decodeLength","lengthBuffer","writeV","flatMap","defer","piped","NOISE_MSG_MAX_LENGTH_BYTES","DUMP_SESSION_KEYS","_globalThis$process","u32","isBytes","isPlainObject","ensureBytes","wrapCipher","u8to16","Poly1305","t0","t3","t4","t5","t6","t7","hibit","r0","r3","r4","r5","r6","r7","r8","r9","h8","h9","d0","d3","d4","d5","d6","d7","d8","d9","aexists","aoutput","opos","poly1305","wrapConstructorWithKey","sigma16","sigma32","sigma16_32","sigma32_32","rotl","isAligned32","BLOCK_LEN","BLOCK_LEN32","MAX_COUNTER","U32_EMPTY","core","allowShortKeys","extendNonceFn","counterLength","counterRight","rounds","defaults","checkOpts","anumber","abool","nonce","toClean","sigma","k32","nonceNcLen","n32","isAligned","d32","o32","pos32","posj","runCipher","chachaCore","cnt","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","chacha20","xchacha20","ZEROS16","updatePadded","ZEROS32","computeTag","AAD","authKey","_poly1305_aead","xorStream","plaintext","plength","clength","ciphertext","equalBytes","chacha20poly1305","nonceLength","U32_MASK64","fromBig","lst","Al","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","rotr32L","rotlSH","rotlSL","rotlBH","rotlBL","Bl","add3L","Cl","add3H","add4L","Dl","add4H","add5H","add5L","El","SHA512_Kh","SHA512_Kl","u64","SHA512_W_H","SHA512_W_L","SHA512","Fl","Gl","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","_1n","_2n","hexes","padStart","hexToNumber","asciis","_0","_9","_A","_F","_a","_f","asciiToBase16","hl","al","n2","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","title","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reseed","gen","sl","genUntil","pred","validatorFns","bigint","function","boolean","stringOrUint8Array","field","Fp","isValid","validateObject","validators","optValidators","checkField","fieldName","isOptional","checkVal","entries","_0n","_3n","_4n","_5n","_8n","power","modulo","pow2","invert","FpSqrt","p1div4","eql","sqr","mul","nv","legendreC","Q1div2","neg","tonelliShanks","isNegativeLE","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","Field","ORDER","bitLen","redef","BYTES","sqrtP","MASK","is0","isOdd","lhs","rhs","FpPow","sqrN","addN","subN","mulN","inv","sqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","fromBytes","getFieldBytesLength","fieldOrder","getMinHashLength","wNAF","constTimeNegate","condition","windows","windowSize","unsafeLadder","elm","precomputeWindow","points","precomputes","maxNumber","shiftBy","wbits","offset1","offset2","cond1","cond2","wNAFCached","precomputesMap","transform","_WINDOW_SIZE","comp","validateBasic","curve","validateField","Gx","Gy","VERIFY_DEFAULT","zip215","twistedEdwards","curveDef","CURVE","ut","adjustScalarBytes","domain","uvRatio","mapToCurve","validateOpts","CURVE_ORDER","prehash","cHash","cofactor","modP","phflag","inBig","inRange","in0MaskRange","assertInRange","assertGE0","pointPrecomputes","isPoint","Point","ey","ez","toAffine","fromAffine","normalizeZ","toInv","_setWindowSize","assertValidity","X2","Y2","Z2","Z4","aX2","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","X3","Y3","T3","Z3","wnaf","scalar","multiplyUnsafe","isSmallOrder","isTorsionFree","iz","ax","ay","zz","clearCofactor","fromHex","normed","lastByte","y2","isXOdd","isLastByteOdd","fromPrivateKey","privKey","getExtendedPublicKey","point","toRawBytes","modN","modN_LE","hashed","pointBytes","hashDomainToScalar","msgs","verifyOpts","utils","randomPrivateKey","precompute","getPublicKey","sig","SB","ExtendedPoint","montgomery","montgomeryBits","powPminus2","Gu","montgomeryBytes","fieldLen","cswap","swap","x_2","x_3","dummy","assertFieldElement","a24","encodeUCoordinate","scalarMult","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","getSharedSecret","ED25519_P","ED25519_SQRT_M1","_10n","_20n","_40n","_80n","ed25519_pow_2_252_3","b80","b160","b240","b250","pow_p_5_8","vx2","root1","root2","useRoot1","useRoot2","noRoot","ed25519Defaults","ed25519","ed25519_domain","x25519","ELL2_C1","FpSqrtEven","HMAC","assertHash","iHash","oHash","assertExists","assertBytes","extract","ikm","HKDF_COUNTER","EMPTY_BUFFER","expand","prk","assertNumber","okm","HMACTmp","defaultCrypto","hashSHA256","getHKDF","generateX25519KeyPair","secretKey","generateX25519KeyPairFromSeed","generateX25519SharedKey","chaCha20Poly1305Encrypt","ad","chaCha20Poly1305Decrypt","uint16BEEncode","uint8ArrayAllocUnsafe","uint16BEDecode","UnexpectedPeerError","InvalidCryptoExchangeError","_props$name","AggregateCodeError","_props$name2","InvalidCryptoTransmissionError","ERR_TIMEOUT","bigIntegerToUintBase64url","uint8ArrayConcat","uint8ArrayToString","base64urlToBigInteger","base64urlToBuffer","isPromise","PUBLIC_KEY_BYTE_LENGTH","PRIVATE_KEY_BYTE_LENGTH","KEYS_BYTE_LENGTH","concatKeys","privateKeyRaw","nativeCrypto","derivedEmptyPasswordKey","alg","ext","key_ops","kty","exporter","_opts$algorithm","_opts$keyLength","_opts$nonceLength","_opts$digest","_opts$saltLength","_opts$iterations","saltLength","webcrypto","aesGcm","cryptoKey","importKey","deriveParams","runtimeDerivedEmptyPassword","deriveKey","rawKey","ciphers","encryptedKey","KeyType","__KeyTypeValues","PublicKey","PrivateKey","Data","Ed25519PublicKey","ensureKey","marshal","pbm","Ed25519","uint8ArrayEquals","Ed25519PrivateKey","_publicKey","public","export","unmarshalEd25519PrivateKey","privateKeyBytes","publicKeyBytes","unmarshalEd25519PublicKey","generateKeyPairFromSeed","types","unmarshalPrivateKey","derivePublicFromPrivate","jwKey","convertKey","fkey","jwk2pub","jwk2priv","keySize","jwk","MAX_KEY_SIZE","RsaPublicKey","RSA","RsaPrivateKey","genSecret","randB","dp","dq","unmarshalRsaPrivateKey","unmarshalRsaPublicKey","fromJwk","b2n","h2b","DER","Err","_parseInt","toSig","sBytes","rBytesLeft","hexFromSig","shl","rhl","rl","weierstrassPoints","allowedPrivateKeyLengths","wrapPrivateKey","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","_c","_isCompressed","weierstrassEquation","x2","x3","isWithinCurveOrder","assertGE","normPrivateKeyToScalar","assertPrjPoint","px","py","pz","hasEvenY","U1","U2","k1neg","k2neg","k2","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","isCompressed","_bits","ProjectivePoint","weierstrass","bits2int","bits2int_modN","lowS","compressedLen","uncompressedLen","invN","cat","sqrtError","suffix","numToNByteStr","isBiggerThanHalfOrder","slcNum","Signature","recovery","fromCompact","fromDER","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","ir","u1","u2","hasHighS","normalizeS","toDERRawBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","minLen","reduced","isProbPub","delta","ORDER_MASK","int2octets","prepSig","defaultSigOpts","extraEntropy","ent","h1int","seedArgs","k2sig","kBytes","normS","defaultVerOpts","privateA","publicB","drbg","_Point$BASE$multiplyA","_sig","derError","getHash","secp256k1P","secp256k1N","divNearest","sqrtMod","_6n","_11n","_22n","_23n","_44n","_88n","b88","b176","b220","b223","secp256k1","defHash","createCurve","POW_2_128","validatePublicKey","secp","Secp256k1PublicKey","keysProtobuf","Secp256k1","Secp256k1PrivateKey","unmarshalSecp256k1PrivateKey","unmarshalSecp256k1PublicKey","supportedKeys","unsupportedKey","_decoded$Data2","_decoded$Type2","keysPBM","peerIdSymbol","isPeerId","multihash","cid","toStringV0","baseCache","toStringV1","CID","asCID","toV0","DAG_PB_CODE","SHA_256_CODE","createV0","toV1","createV1","unknown","toJSON","encodeCID","cidSymbol","decodeFirst","specs","inspectBytes","prefixSize","multihashSize","multihashBytes","digestBytes","digestSize","multihashCode","initialBytes","parseCIDtoBytes","codeOffset","hashOffset","inspect","baseDecoder","LIBP2P_KEY_CODE","MARSHALLED_ED225519_PUBLIC_KEY_LENGTH","MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH","PeerIdImpl","toCID","_id$multihash","_decoder","startsWith","Ed25519PeerIdImpl","Secp256k1PeerIdImpl","RSAPeerIdImpl","peerIdFromCID","peerIdFromBytes","peerIdFromString","peerIdFromKeys","NoiseExtensions","NoiseHandshakePayload","getPayload","localPeer","staticPublicKey","extensions","signedPayload","signPayload","getHandshakePayload","libp2pPublicKey","identityKey","identitySig","webtransportCerthashes","createHandshakePayload","getPeerIdFromPayload","decodePayload","verifySignedPayload","noiseStaticKey","payloadPeerId","generatedPayload","_decoded$Data","_decoded$Type","unmarshalPublicKey","isValidPublicKey","pk","uint8ArrayAlloc","Nonce","getUint64","assertValue","AbstractHandshake","forComponent","encryptWithAd","decryptWithAd","valid","hasKey","isEmptyKey","createEmptyKey","encryptAndHash","mixHash","encryptedMessage","decryptAndHash","derivedU8","mixKey","tempK","initializeKey","initializeSymmetric","protocolName","protocolNameBytes","hashProtocolName","tempk1","tempk2","cs1","cs2","writeMessageRegular","readMessageRegular","XX","initializeInitiator","prologue","rs","psk","initializeResponder","writeMessageA","hs","writeMessageB","spk","writeMessageC","messageBuffer","readMessageA","readMessageB","valid1","valid2","readMessageC","initSession","initiator","sendMessage","session","resultingBuffer","recvMessage","resultingPlaintext","resultingValid","logLocalEphemeralKeys","keyLogger","logRemoteEphemeralKey","XXHandshake","isInitiator","staticKeypair","handshake","xx","propose","trace","encode0","receivedMessageBuffer","decode0","exchange","decode1","decodedPayload","setRemoteNoiseExtension","encode1","encode2","decode2","getCS","getRemoteStaticKey","encryption","remoteExtensions","Noise","staticNoiseKey","prologueBytes","metrics","xxHandshakeSuccesses","registerCounter","help","xxHandshakeErrors","encryptedPackets","decryptedPackets","decryptErrors","registerMetrics","staticKeys","secureOutbound","wrappedConnection","performHandshake","createSecureConnection","secureInbound","performXXHandshake","_this$metrics","_this$metrics2","secure","user","duplexPair","network","encryptStream","decrypted","decryptStream","noise","peerDiscoverySymbol","_classPrivateFieldSet2","asUint8Array","_globalThis$Buffer2","MAX_IPV6_LENGTH","MAX_IPV4_LENGTH","parser","new","readAtomically","parseWith","peekChar","readChar","readGivenChar","readSeparator","sep","readNumber","radix","maxDigits","allowZeroPrefix","maxBytes","digitCount","leadingChar","hasLeadingZero","maxValue","digit","readIPv4Addr","ix","readIPv6Addr","readGroups","groups","ipv4","headSize","headIp4","limit","tailSize","readIPAddr","_this$readIPv4Addr","isIPv4","parseIPv4","isIPv6","parseIPv6","isIP","parseIP","isV4","isV6","sections","v4Buffer","argv","_length","getProtocol","row","resolvable","path","createProtocol","convertToString","ipBuff","ipString","bytes2ip","bytes2str","bytes2port","address","bytes2mh","bytes2onion","bytes2mb","convertToBytes","ip2bytes","str2bytes","port2bytes","mh2bytes","addr","port","portBuf","onion2bytes","onion32bytes","mbstr","anybaseDecoder","mb2bytes","addrBytes","portBytes","bytesToMultiaddrParts","tuples","stringTuples","_varint$decode$bytes","sizeForAddr","ParseError","stringAddr","stringTuplesToString","tup","cleanPath","tuplesToBytes","_varint$decode$bytes2","DNS_CODES","resolvers","isMultiaddr","_string","_tuples","_stringTuples","_path","DefaultMultiaddr","stringToMultiaddrParts","_classPrivateFieldSet","toOptions","family","transport","host","zone","tcp","udp","ip4","ip6","dns6","ip6zone","protos","protoCodes","protoNames","encapsulate","decapsulate","addrString","lastIndexOf","decapsulateCode","getPeerId","_ref4","p2p","tuple","getPath","resolvableProto","resolver","nodeAddress","isThinWaistAddress","multiaddr","DNS4","DNS6","DNSADDR","DNS","IP","TCP","UDP","UTP","QUIC","QUICV1","_WebSockets","WebSockets","_WebSocketsSecure","WebSocketsSecure","HTTP","HTTPS","_WebRTCDirect","WebRTCDirect","_WebTransport","WebTransport","P2PWebRTCStar","P2PWebRTCDirect","Reliable","_P2P","_Circuit","CircuitRecursive","Circuit","P2P","makeMatchesFunction","partialMatch","arg","matches","pnames","Multiaddr","MultiaddrClass","Bootstrap","_options$timeout","peerData","multiaddrs","_discoverBootstrapPeers","_this$_init$tagName","_this$_init$tagValue","_this$_init$tagTTL","tagValue","ttl","tagTTL","_classPrivateMethodInitSpec","privateSet","ENVELOPE_PAYLOAD_TYPE_PEER_RECORD","PeerRecord","AddressInfo","seq","addresses","DOMAIN","CODEC","seqNumber","marshaled","Protobuf","localeCompare","every","arrayEquals","_peerRecord$addresses","peerRecord","pbkdf2Init","_password","_salt","_opts","asyncTick","DK","PRF","PRFSalt","pbkdf2Output","prfW","pbkdf2Async","utilFromBase","inputBuffer","inputBase","utilToBase","internalReserved","internalValue","biggest","retBuf","retView","basis","utilConcatView","outputLength","prevLength","views","utilDecodeTC","valueHex","condition1","condition2","warnings","bigIntBuffer","bigIntView","bigInt","smallIntBuffer","smallIntView","padNumber","inputNumber","fullLength","dif","assertBigInt","checkBufferParams","baseBlock","inputOffset","ViewWriter","final","powers2","digitsString","EMPTY_STRING","EMPTY_VIEW","END_OF_CONTENT_NAME","OCTET_STRING_NAME","BIT_STRING_NAME","HexBlock","BaseClass","isHexOnly","valueHexView","pvtsutils","fromBER","endLength","toBER","sizeOnly","NAME","LocalBaseBlock","valueBeforeDecode","valueBeforeDecodeView","blockName","ValueBlock","LocalIdentificationBlock","idBlock","_b","_d","tagNumber","isConstructed","firstOctet","encodedBuf","pvutils","encodedView","curView","inputView","intBuffer","tagNumberMask","intTagNumberBuffer","tagNumberBufferMaxLength","tempBufferView","LocalLengthBlock","lenBlock","isIndefiniteForm","longFormUsed","lenOffset","lengthBufferView","typeStore","BaseBlock","primitiveSchema","valueBlockType","valueBlock","resultOffset","_writer","prepareIndefiniteForm","idBlockBuf","valueBlockBuf","lenBlockBuf","onAsciiEncoding","inputBuffer1","inputBuffer2","view1","view2","Constructed","BaseStringBlock","fromBuffer","LocalPrimitiveValueBlock","_a$w","_a$v","_a$u","_a$t","_a$s","_a$r","_a$q","_a$p","_a$o","_a$n","_a$m","_a$l","_a$k","_a$j","_a$i","_a$h","_a$g","_a$f","_a$e","_a$d","_a$c","_a$b","_a$a","_a$9","_a$8","_a$7","_a$6","_a$5","_a$4","_a$3","_a$2","_a$1","Primitive","localFromBER","incomingOffset","returnObject","newASN1Type","EndOfContent","Integer","BitString","OctetString","Null","ObjectIdentifier","Enumerated","Utf8String","RelativeObjectIdentifier","TIME","Sequence","NumericString","PrintableString","TeletexString","VideotexString","UTCTime","GeneralizedTime","GraphicString","VisibleString","GeneralString","UniversalString","CharacterString","BmpString","DATE","TimeOfDay","DateTime","Duration","newObject","inputObject","newType","localChangeType","LocalConstructedValueBlock","currentOffset","indefiniteLength","LocalEndOfContentValueBlock","override","LocalBooleanValueBlock","octet","LocalOctetStringValueBlock","currentBlockName","asn","content","LocalBitStringValueBlock","unusedBits","bitsStr","viewAdd","second","firstView","secondView","firstViewCopy","firstViewCopyLength","secondViewCopy","secondViewCopyLength","power2","viewSub","LocalIntegerValueBlock","_valueDec","setValueHex","valueDec","modValue","tempBuf","tempView","toDER","updatedView","firstBit","currentByte","bitNumber","asn1View","flag","byteNumber","bigIntValue","secondInt","convertToDER","convertFromDER","LocalSidValueBlock","isFirstSid","valueBigInt","sidValue","LocalObjectIdentifierValueBlock","sidBlock","retBuffers","valueBuf","pos1","pos2","sid","plus","parsedSID","sidStr","sidArray","LocalRelativeSidValueBlock","LocalRelativeObjectIdentifierValueBlock","LocalStringValueBlock","LocalSimpleStringValueBlock","LocalSimpleStringBlock","inputString","strLen","LocalUtf8StringValueBlock","LocalBmpStringValueBlock","LocalUniversalStringValueBlock","copyBuffer","valueView","strLength","codeBuf","codeView","valueDate","day","hour","minute","fromDate","toBuffer","inputDate","toDate","UTC","parserArray","outputArray","toISOString","millisecond","getUTCMilliseconds","timeString","dateTimeString","fractionPart","hourDifference","minuteDifference","differencePosition","differenceString","fractionPointPosition","fractionPartCheck","fractionResult","tempDate","getUTCDay","bnToBuf","bn","u8","bufToBn","KEY_SIZE","ITERATIONS","MAX_RSA_KEY_SIZE","der","asn1js","keyBuf","keyArr","encryptionKey","pbkdf2Params","finalWrapperBuf","Envelope","payloadType","RecordEnvelope","signData","formatSignaturePayload","_RecordEnvelope","envelopeData","record","envelope","createFromProtobuf","domainUint8Array","uint8arraysFromString","domainLength","payloadTypeLength","payloadLength","vals","pattern","literal","certhash","matcher","matchers","fmt","toParts","exactMatch","_DNS4","_DNS6","_DNSADDR","_DNS","_IP4","_IP6","_IP","_IP_OR_DOMAIN","IP_OR_DOMAIN","_TCP","_UDP","TCP_OR_UDP","_QUIC","_QUICV1","QUIC_V0_OR_V1","_WEB","pbStream","isEnvWithDom","isElectron","detectElectron","isBrowser","isElectronMain","isElectronRenderer","release","isWebWorker","importScripts","WorkerGlobalScope","isReactNative","product","Identify","protocolVersion","agentVersion","listenAddrs","observedAddr","signedPeerRecord","MAX_IDENTIFY_MESSAGE_SIZE","defaultValues","_Identify_brand","_init$protocolPrefix","_init$protocolPrefix2","_init$timeout","_init$maxInboundStrea","_init$maxOutboundStre","_init$maxPushIncoming","_init$maxPushOutgoing","_init$maxIdentifyMess","_init$maxObservedAddr","_init$runOnTransientC","_init$protocolPrefix3","_init$agentVersion","_init$runOnConnection","started","addressManager","identifyProtocolStr","protocolPrefix","identifyPushProtocolStr","maxInboundStreams","maxOutboundStreams","maxPushIncomingStreams","maxPushOutgoingStreams","maxIdentifyMessageSize","maxObservedAddresses","runOnTransientConnection","nodeInfo","runOnConnectionOpen","identify","AgentVersion","ProtocolVersion","_handleIdentify","_handlePush","unhandle","pushToConnections","_peer$metadata$get","_peer$metadata$get2","listenAddresses","getAddresses","seal","supportedProtocols","getProtocols","pushes","AbortSignal","_this$maxIdentifyMess","IdentifyMessage","close","_stream","abort","_identify","_this$maxIdentifyMess2","_stream2","_this$maxObservedAddr","cleanObservedAddr","getCleanMultiaddr","getObservedAddrs","addObservedAddr","_consumeIdentifyMessage","_this$peerId$publicKe","peerRecordEnvelope","remoteAddr","_this$maxIdentifyMess3","isCertified","openAndCertify","existingPeer","storedEnvelope","storedRecord","IdentifyClass","closeSource","_getIterator$return","_getIterator","getIterator","createAbortError","clearMethods","defaultClear","defaultSet","timeoutId","settle","rejectFunction","signalListener","delayPromise","createDelay","RateLimiter","_opts$points","_opts$duration","_opts$blockDuration","_opts$execEvenly","_opts$execEvenlyMinDe","_opts$keyPrefix","duration","blockDuration","execEvenly","execEvenlyMinDelayMs","keyPrefix","memoryStorage","MemoryStorage","pointsToConsume","rlKey","getKey","secDuration","_getKeySecDuration","incrby","remainingPoints","consumedPoints","msBeforeNext","isFirstInDuration","delayMs","penalty","reward","msDuration","initPoints","customDuration","parseKey","durationSec","existing","msBeforeExpires","expiresAt","getTime","durationMs","unref","MessageTypes","MessageTypeNames","InitiatorMessageTypes","NEW_STREAM","MESSAGE","MESSAGE_INITIATOR","CLOSE","CLOSE_INITIATOR","RESET","RESET_INITIATOR","ReceiverMessageTypes","MESSAGE_RECEIVER","CLOSE_RECEIVER","RESET_RECEIVER","MAX_MSG_SIZE","maxMessageSize","maxUnprocessedMessageQueueSize","_buffer","_headerInfo","_maxMessageSize","_maxUnprocessedMessageQueueSize","_decodeHeader","readVarInt","POOL_SIZE","_pool","_poolOffset","AbstractStream","_init$metadata","_init$sendCloseWriteT","sinkController","AbortController","sinkEnd","closed","readStatus","writeStatus","sendCloseWriteTimeout","onCloseRead","onCloseWrite","onReset","onAbort","streamSource","onSourceEnd","sendNewStream","abortListener","sendData","sendingData","sendCloseWrite","onSinkEnd","_this$onCloseRead","closeRead","endErr","closeWrite","_this$onCloseWrite","sendCloseRead","_this$onAbort","sendReset","_closeSinkAndSource","_this$onReset","_closeSink","_closeSource","remoteCloseWrite","remoteCloseRead","sourcePush","sourceReadableLength","MplexStream","streamId","maxDataSize","toSend","printMessage","MplexStreamMuxer","_init$closeTimeout","_init$disconnectThres","_streamId","_streams","initiators","receivers","closeTimeout","_createSink","closeController","rateLimiter","disconnectThreshold","streams","registry","_newStream","_newReceiverStream","_this$_init$maxOutbou","maxMsgSize","createStream","onStreamEnd","_handleIncoming","_this$_init$maxStream","_this$_init$maxInboun","onIncomingStream","maxBufferSize","maxStreamBufferSize","Mplex","createStreamMuxer","mplex","ERR_WRONG_PING_ACK","PingService","handleMessage","openConnection","PingServiceClass","transportSymbol","FaultTolerance","ASSUME_HTTP_CODES","extractSNI","sniProtoCode","hasTLS","interpretNext","headProtoCode","headProtoVal","restMa","interpreter","interpreters","restVal","_tailProto$","tailProto","_tailProto$2","dnsaddr","dns4","dns","ipfs","_tailProto$3","_tailProto$4","http","_tailProto$5","maHasTLS","sni","baseVal","tls","_tailProto$6","_tailProto$7","https","_tailProto$8","ws","_tailProto$9","wss","_tailProto$10","p2p-websocket-star","_tailProto$11","p2p-webrtc-star","_tailProto$12","p2p-webrtc-direct","_tailProto$13","socket","readyState","cleanup","handleOpen","handleErr","_event$error","closeOnEnd","ready","CLOSING","CLOSED","wasClean","_obj$constructor","binaryType","connected","connError","cleanUp","cont","onOpen","onMessage","_event$error2","_event$error3","connect","_location$protocol","_location$protocol2","endsWith","wsUrl","httpProto","wsProto","wsurl","connectedSource","remoteAddress","remotePort","hostname","CONNECTING","OPEN","WebSocket","websocket","CODE_P2P","CODE_CIRCUIT","testMa","mafmt","maConn","socketToMaConn","_connect","upgrader","upgradeOutbound","cOpts","errorPromise","rawSocket","_head$","uri","assumeHttp","toUri","createListener","_this$init","_this$init2","filters","webSockets","StrictSign","StrictNoSign","TopicValidatorResult","FloodsubID","GossipsubIDv10","GossipsubIDv11","GossipsubMaxIHaveLength","defaultDecodeRpcLimits","maxSubscriptions","maxMessages","maxIhaveMessageIDs","maxIwantMessageIDs","maxControlMessages","maxPeerInfos","RPC","SignaturePolicy","PublishConfigType","RejectReason","ValidateError","MessageStatus","MessageSource","InclusionReason","ChurnReason","ScorePenalty","IHaveIgnoreReason","ScoreThreshold","SubOpts","Message","ControlMessage","ControlIHave","ControlIWant","ControlGraft","ControlPrune","seqno","ihave","iwant","graft","prune","_opts$limits","limits","_opts$limits2","_opts$limits3","_opts$limits4","topicID","messageIDs","_opts$limits5","_opts$limits6","backoff","_opts$limits7","peerID","subscriptions","control","_opts$limits8","_opts$limits9","MessageCache","gossip","historyCapacity","msgIdToStrFn","history","put","messageId","validated","msgIdStr","originatingPeers","iwantCounts","notValidatedCount","observeDuplicate","msgId","fromPeerIdStr","_this$msgs$get","getWithIWantCount","_msg$iwantCounts$get","getGossipIDs","topics","msgIdsByTopic","_msg$validated","msgIds","cacheEntry","rejectReasonFromAcceptance","acceptance","Ignore","Reject","ERR_INVALID_PEER_SCORE_PARAMS","defaultPeerScoreParams","topicScoreCap","appSpecificScore","appSpecificWeight","IPColocationFactorWeight","IPColocationFactorThreshold","IPColocationFactorWhitelist","behaviourPenaltyWeight","behaviourPenaltyThreshold","behaviourPenaltyDecay","decayInterval","decayToZero","retainScore","defaultTopicScoreParams","topicWeight","timeInMeshWeight","timeInMeshQuantum","timeInMeshCap","firstMessageDeliveriesWeight","firstMessageDeliveriesDecay","firstMessageDeliveriesCap","meshMessageDeliveriesWeight","meshMessageDeliveriesDecay","meshMessageDeliveriesCap","meshMessageDeliveriesThreshold","meshMessageDeliveriesWindow","meshMessageDeliveriesActivation","meshFailurePenaltyWeight","meshFailurePenaltyDecay","invalidMessageDeliveriesWeight","invalidMessageDeliveriesDecay","createPeerScoreParams","topicScoreParams","createTopicScoreParams","validateTopicScoreParams","defaultPeerScoreThresholds","gossipThreshold","publishThreshold","graylistThreshold","acceptPXThreshold","opportunisticGraftThreshold","createPeerScoreThresholds","removeItemsFromSet","superSet","ineed","cond","subset","MapDef","getDefault","getOrDefault","computeScore","pstats","peerIPs","score","tstats","topicParams","topicScore","inMesh","meshTime","p2","firstMessageDeliveries","meshMessageDeliveriesActive","meshMessageDeliveries","deficit","meshFailurePenalty","invalidMessageDeliveries","p5","knownIPs","peersInIP","numPeersInIP","surplus","behaviourPenalty","excess","DeliveryRecordStatus","MessageDeliveries","records","getRecord","ensureRecord","drec","firstSeenTsMs","expire","PeerScore","componentLogger","_opts$computeScore","validatePeerScoreParams","scoreCacheValidityMs","peerStats","_backgroundInterval","background","deliveryRecords","refreshScores","dumpPeerScoreStats","fromEntries","stats","messageFirstSeenTimestampMs","tparams","graftTime","removeIPsForPeer","scoreCache","scoreFnCalls","inc","cacheUntil","scoreFnRuns","_this$metrics3","scoreCachedDelta","addPenalty","penaltyLabel","_this$metrics4","onScorePenalty","addPeer","addIP","removeIP","peersWithIP","removePeer","threshold","getPtopicStats","validateMessage","deliverMessage","markFirstMessageDelivery","markDuplicateMessageDelivery","rejectInvalidMessage","markInvalidMessageDelivery","rejectMessage","Blacklisted","ignored","invalid","duplicateMessage","cap","validatedTime","_this$metrics5","deliveryDelayMs","isLateDelivery","onDuplicateMsgDelivery","ipsToRemove","ipToRemove","peerSet","topicStats","computeScoreWeights","topicStrToLabel","byTopic","_topicStrToLabel$get","topicLabel","topicScores","p1w","p2w","p3w","p3bw","p4w","capF","p5w","p6w","p7w","OutboundStream","rawStream","errCallback","_opts$maxBufferSize","pushPrefixed","InboundStream","IWantTracer","gossipsubIWantFollowupMs","requestMsByMsgExpire","requestMsByMsgSize","requestMsByMsg","addPromise","expireByPeer","iwantPromiseStarted","getBrokenPromises","brokenPromises","_result$get","iwantPromiseBroken","isDuplicate","trackMessage","iwantPromiseResolved","iwantPromiseResolvedFromDuplicate","iwantPromiseResolvedPeers","maxMs","iwantMessagePruned","requestMs","iwantPromiseDeliveryTime","typeToKey","marshalPublicKey","_type","SignPrefix","createGossipRpc","_control$graft","_control$prune","_control$ihave","_control$iwant","ensureControl","rpc","messageIdToString","shuffle","seqnoBytes","msgIdFnStrictSign","sequenceNumber","msgIdFnStrictNoSign","Protocol","SimpleTimeCache","validityMs","validUntilMs","GossipStatusCode","GossipSub","_opts$decodeRpcLimits","_opts$globalSignature","_opts$debugName","_options$msgIdToStrFn","_options$messageCache","constants","stopped","heartbeatDuration","startTimer","heartbeat","heartbeatTimeout","msToNextHeartbeat","heartbeatInterval","hearbeatStartMs","heartbeatSkipped","runHeartbeat","fallbackToFloodsub","floodPublish","batchPublish","doPX","directPeers","Dlo","Dhi","Dscore","Dout","Dlazy","fanoutTTL","mcacheLength","mcacheGossip","seenTTL","prunePeers","pruneBackoff","unsubcribeBackoff","graftFloodThreshold","opportunisticGraftPeers","opportunisticGraftTicks","directConnectTicks","scoreParams","scoreThresholds","decodeRpcLimits","globalSignaturePolicy","multicodecs","debugName","direct","seenCache","publishedMessageIds","msgIdFn","fastMsgIdFn","fastMsgIdCache","mcache","messageCache","dataTransform","metricsRegister","metricsTopicStrToLabel","maxMeshMessageDeliveriesWindowMs","topicParam","register","protocolsEnabled","gauge","labelNames","topicSubscriptionStatus","topicPeersCount","meshPeerCounts","meshPeerInclusionEventsFanout","meshPeerInclusionEventsRandom","meshPeerInclusionEventsSubscribed","meshPeerInclusionEventsOutbound","meshPeerInclusionEventsNotEnough","meshPeerInclusionEventsOpportunistic","meshPeerInclusionEventsUnknown","meshPeerChurnEventsDisconnected","meshPeerChurnEventsBadScore","meshPeerChurnEventsPrune","meshPeerChurnEventsExcess","meshPeerChurnEventsUnknown","peersPerProtocol","histogram","buckets","acceptedMessagesTotal","ignoredMessagesTotal","rejectedMessagesTotal","unknownValidationResultsTotal","asyncValidationMcacheHit","asyncValidationDelayFromFirstSeenSec","asyncValidationUnknownFirstSeen","peerReadStreamError","rpcRecvBytes","rpcRecvCount","rpcRecvSubscription","rpcRecvMessage","rpcRecvControl","rpcRecvIHave","rpcRecvIWant","rpcRecvGraft","rpcRecvPrune","rpcDataError","rpcRecvError","rpcRecvNotAccepted","rpcSentBytes","rpcSentCount","rpcSentSubscription","rpcSentMessage","rpcSentControl","rpcSentIHave","rpcSentIWant","rpcSentGraft","rpcSentPrune","msgPublishCount","msgPublishPeersByTopic","directPeersPublishedTotal","floodsubPeersPublishedTotal","meshPeersPublishedTotal","fanoutPeersPublishedTotal","msgPublishBytes","msgPublishTime","msgForwardCount","msgForwardPeers","msgReceivedPreValidation","msgReceivedError","prevalidationInvalidTotal","prevalidationValidTotal","prevalidationDuplicateTotal","prevalidationUnknownTotal","msgReceivedInvalid","msgReceivedInvalidByTopic","duplicateMsgDeliveryDelay","maxMeshMessageDeliveriesWindowSec","duplicateMsgLateDelivery","duplicateMsgIgnored","peersByScoreThreshold","avgMinMax","scoreWeights","scorePerMesh","scoringPenalties","ihaveRcvIgnored","ihaveRcvMsgids","ihaveRcvNotSeenMsgids","iwantRcvMsgids","iwantRcvDonthaveMsgids","gossipPromiseExpireSec","iwantPromiseUntracked","connectedPeersBackoffSec","cacheSize","mcacheSize","mcacheNotValidatedCount","fastMsgIdCacheCollision","newConnectionCount","toTopic","topicStr","_this$topicStrToLabel","onJoin","onLeave","onAddToMesh","Fanout","Random","Subscribed","Outbound","NotEnough","Opportunistic","onRemoveFromMesh","BadScore","Prune","Excess","onReportValidation","messageRecord","firstSeenTimestampMs","hit","Accept","onIhaveRcv","idonthave","onIwantRcv","iwantByTopic","iwantDonthave","onForwardMsg","tosendCount","onPublishMsg","tosendGroupCount","dataLen","floodsub","mesh","fanout","onMsgRecvPreValidation","onMsgRecvError","onPrevalidationResult","duplicate","onMsgRecvInvalid","onPublishDuplicateMsg","onPeerReadStreamError","onRpcRecvError","onRpcDataError","onRpcRecv","rpcBytes","onRpcSent","_rpc$control$ihave$le","_rpc$control$ihave","_rpc$control$iwant$le","_rpc$control$iwant","_rpc$control$graft$le","_rpc$control$graft","_rpc$control$prune$le","_rpc$control$prune","registerScores","scores","graylist","publish","registerScoreWeights","wsTopic","registerScorePerMesh","scoreByPeer","peersPerTopicLabel","_this$topicStrToLabel2","peersInMesh","_peersInMesh","meshScores","_scoreByPeer$get","getMetrics","addCollect","onScrapeMetrics","gossipTracer","allowedTopics","publishConfig","signaturePolicy","Signing","author","Anonymous","getPublishConfigFromPeerId","outboundInflightQueue","createOutboundStream","addrs","topology","onConnect","onPeerConnected","onDisconnect","onPeerDisconnected","notifyOnTransient","registrarTopologyIds","directPeerInitial","unregister","closePromises","outboundStream","streamsOutbound","inboundStream","streamsInbound","heartbeatTimer","fanoutLastpub","peerhave","iasked","outbound","createInboundStream","maxOutboundBufferSize","floodsubPeers","sendSubscriptions","priorInboundStream","maxInboundDataLength","pipePeerReadStream","currentIP","multiaddrToIPStr","_this$metrics6","acceptFromWhitelist","peersInTopic","getSubscribers","getTopics","_this$metrics7","control$","prune$","awaitRpcHandler","handleReceivedRpc","_this$metrics8","_this$metrics9","_this$metrics10","_this$metrics11","handlePeerReadStreamError","_this$metrics12","acceptFrom","subOpt","handleReceivedSubscription","handleReceivedMessagePromise","handleReceivedMessage","_this$metrics13","awaitRpcMessageHandler","handleControlMessage","topicSet","rpcMsg","_this$metrics14","_this$metrics15","_this$metrics16","validationResult","validateReceivedMessage","validationCode","asyncValidation","emitSelf","propagationSource","forwardMessage","_this$fastMsgIdFn","_this$fastMsgIdCache","fastMsgIdStr","msgIdCached","_msg$data","SignaturePresent","SeqnoPresent","FromPresent","_msg$data2","_msg$key","InvalidSeqno","InvalidSignature","InvalidPeerId","fromPeerId","rpcMsgPreSign","validateToRawMessage","inboundTransform","TransformFailed","_this$metrics17","topicValidator","topicValidators","getScore","toPeer","sendRpc","controlMsg","_iwant$","handleIHave","handleIWant","handleGraft","handlePrune","sent","iwantMessageIds","_this$metrics18","messagesAccepted","acceptUntil","_this$peerhave$get","_this$iasked$get","_this$metrics19","LowScore","_this$metrics20","MaxIhave","_this$metrics21","MaxIasked","_this$metrics22","iask","iwantList","_this$metrics23","_iwantByTopic$get","_this$backoff$get","_this$outbound$get","_this$metrics24","GraftBackoff","floodCutoff","addBackoff","makePrune","_this$metrics25","doAddBackoff","pxConnect","intervalMs","_backoff$get","applyIwantPenalties","BrokenPromise","clearBackoff","heartbeatTicks","directConnect","toconnect","consumePeerRecord","getTopologies","_topology$onConnect","wasSubscribed","leave","_this$metrics26","toAdd","fanoutPeers","_this$metrics27","_this$metrics28","fanoutCount","getRandomGossipPeers","sendGraft","_this$metrics29","meshPeers","sendPrune","selectPeersToForward","excludePeers","tosend","_excludePeers$has","_excludePeers$has2","_excludePeers$has3","selectPeersToPublish","newFanoutPeers","rawMsg","_this$metrics30","_opts$ignoreDuplicate","_opts$allowPublishToZ","_opts$batchPublish","_this$metrics32","startMs","transformedData","outboundTransform","originalData","buildRawMessage","ignoreDuplicatePublishError","_this$metrics31","recipients","willSendToSelf","allowPublishToZeroPeers","sendRpcInBatch","prefixedData","_this$metrics33","reportMessageValidationResult","_this$metrics34","_this$metrics35","ctrl","piggybackControl","piggybackGossip","outRpc","_this$mesh$get$has","_this$mesh$get","_this$mesh$get$has2","_this$mesh$get2","sendGraftPrune","tograft","toprune","noPX","onUnsubscribe","pruning","_noPX$get","_noPX$get2","emitGossip","peersToGossipByTopic","gossipIDsByTopic","peersToGossip","_gossipIDsByTopic$get","doEmitGossip","candidateToGossip","factor","peerMessageIDs","pushGossip","flush","controlIHaveMsgs","_this$gossip$get","_this$streamsOutbound","backoffMs","xid","_peerInfo","_this$metrics36","_this$fastMsgIdCache2","candidateMeshPeers","shuffledPeers","peerStreams","prunePeer","_this$metrics37","graftPeer","_this$metrics38","newMeshPeers","removeFirstNItemsFromSet","peersArray","_this$outbound$get2","rotate","_this$outbound$get3","_this$outbound$get4","_this$outbound$get5","peersList","medianIndex","medianScore","lastpb","topicPeers","_topicPeers$has","candidateFanoutPeers","_this$fastMsgIdCache$","_this$fastMsgIdCache3","backoffSize","expiredMs","_this$score$peerStats","_this$score$peerStats2","peerIdStrs","swPeer","swPeerTopic","swTopic","computeAllPeersScoreWeights","RelayCodecs","messageValidator","timeTakenMs","TopicOnlyDecoder","ProtoTopicOnlyMessage","isRelayPubsub","pubsub","subscribeToAllTopics","observers","successes","failures","TOPIC_NOT_CONFIGURED","_this$observers$get","ctObs","observer","removeObservers","_obs","getActiveSubscriptions","gossipSubSubscribe","processIncomingMessage","topicOnlyMsg","contentTopicMap","_pubsub$multicodecs$i","_pubsub$multicodecs","contentRoutingSymbol","peerRoutingSymbol","defaultLogger","createDisabledLogger","mapIterable","PeerSet","predicate","intersection","difference","union","createEd25519PeerId","createFromPrivKey","_type2","marshalPrivateKey","createFromJSON","createFromParts","pubKey","createFromPubKey","PeerMap","_classPrivateGetter","_queue","PriorityQueue","enqueue","comparator","step","it","lowerBound","dequeue","_carryoverConcurrencyCount","_isIntervalIgnored","_intervalCount","_intervalCap","_interval","_intervalEnd","_intervalId","_timeoutId","_queueClass","_pending","_concurrency","_isPaused","_throwOnTimeout","_PQueue_brand","PQueue","_options$intervalCap$","_options$intervalCap","_options$interval$toS","_options$interval","carryoverConcurrencyCount","intervalCap","concurrency","autoStart","queueClass","throwOnTimeout","newConcurrency","_processQueue","function_","_this$pending3","_this$intervalCount","operation","_throwOnAbort","_next","_tryToStartAnother","addAll","functions","pause","_onEvent","onSizeLessThan","onIdle","sizeBy","_get_doesIntervalAllowAnother","_this","_get_doesConcurrentAllowAnother","_this2","_this$pending","_onResumeInterval","_onInterval","_initializeIntervalIfNeeded","_get_isIntervalPaused","_this3","canInitializeInterval","job","observable","WORKER_REQUEST_READ_LOCK","WORKER_RELEASE_READ_LOCK","MASTER_GRANT_READ_LOCK","WORKER_REQUEST_WRITE_LOCK","WORKER_RELEASE_WRITE_LOCK","MASTER_GRANT_WRITE_LOCK","handleWorkerLockRequest","masterEvent","requestType","releaseType","grantType","requestEvent","identifier","MessageEvent","handler","releaseEventListener","releaseEvent","makeWorkerLockRequest","responseEvent","defaultOptions","singleProcess","mutexes","createReleaseable","createMortice","isWorker","readLock","writeLock","impl","createMutex","masterQueue","readQueue","localReadQueue","readPromise","ERR_INVALID_PARAMETERS","Peer","Address","Tag","Peer$metadataEntry","Peer$tagsEntry","expiry","bytesToPeer","_peer$peerRecordEnvel","PeerPB","peerIdFromPeerId","pathSepS","pathSepB","pathSep","Key","clean","_buf","uint8Array","withNamespaces","asKey","less","list1","list2","baseNamespace","namespaceType","namespaceValue","parent","isAncestorOf","isDecendantOf","isTopLevel","NAMESPACE_COMMON","peerIdToDatastoreKey","b32key","dedupeFilterAndSortAddresses","addressMap","_addr$isCertified","maStr","existingAddr","toPeerPB","strategy","_existingPeer$address","_existingPeer$protoco","_existingPeer$metadat","_existingPeer$tags","_options$addressFilte","_existingPeer$id$publ","uint8arrayEquals","createSortedMap","validateMetadata","validateTag","mapTag","metadataEntries","tagsEntries","mergedTags","addressFilter","_options$map","_options$map2","_tag$value","decodePeer","cached","_PersistentStore_brand","PersistentStore","datastore","lock","mortice","existingBuf","_findExistingPeer","peerPb","_saveIfDifferent","peerCache","_query$filters","_query$orders","orders","mapQuery","previous","updated","_PersistentPeerStore_brand","PersistentPeerStore","_emitIfUpdated","expectedPeer","_peer","iterable","peekable","sorter","BaseDatastore","putMany","getMany","deleteMany","batch","puts","dels","commit","_all","_allKeys","queryKeys","MemoryDatastore","_err5","Errors","defaultAddressFilter","stripPeerId","observedPeerIdStr","DefaultAddressManager","_init$announceFilter","announce","observed","announceFilter","_updatePeerStoreAddresses","debounce","getAnnounceAddrs","transportManager","getAddrs","confident","getListenAddrs","confirmObservedAddr","_this$observed$get","startingConfidence","removeObservedAddr","_ref5","addrSet","_ma$protos$pop","isStartable","DefaultComponents","_started","_invokeStartableMethod","_startable$methodName","startable","beforeStart","afterStart","beforeStop","afterStop","OPTIONAL_SERVICES","NON_SERVICE_PROPERTIES","NETMASK_RANGES","ipRange","isPrivateIp","ipAddr","ipv4Check","connectionGater","denyDialPeer","denyDialMultiaddr","denyInboundConnection","denyOutboundConnection","denyInboundEncryptedConnection","denyOutboundEncryptedConnection","denyInboundUpgradedConnection","denyOutboundUpgradedConnection","filterMultiaddrForPeer","isPrivate","defaultAddressSort","publicResult","isAPrivate","isBPrivate","publicAddressesFirst","relayResult","isACircuit","isBCircuit","circuitRelayAddressesLast","certifiedResult","certifiedAddressesFirst","CustomProgressEvent","getTypes","DEFAULT_TYPES","RecordType","DEFAULT_TTL","toDNSResponse","_obj$Status","_obj$TC","_obj$RD","_obj$RA","_obj$AD","_obj$CD","_ref6","_obj$Question","_ref7","_obj$Answer","Status","TC","flag_tc","RD","flag_rd","RA","flag_ra","AD","flag_ad","CD","flag_cd","Question","questions","question","Answer","answers","answer","_ref8","_answer$TTL","TTL","DEFAULT_QUERY_CONCURRENCY","dnsJsonOverHttps","_init$queryConcurrenc","httpQueue","queryConcurrency","fqdn","_options$onProgress","searchParams","URLSearchParams","onProgress","_options$onProgress2","fetch","accept","statusText","CachedAnswers","maxSize","lru","hashlru","foundAllAnswers","getAnswers","cachedAnswers","expires","_this$lru$get","_init$cacheSize","_init$resolvers","tld","_this$resolvers$tld","dnsaddrCode","dnsaddrResolver","_options$maxRecursive","_ma$stringTuples$find","_options$dns","recursionLimit","maxRecursiveDepth","DNSClass","TXT","resolved","DefaultConfig","noAnnounce","addressSorter","faultTolerance","FATAL_ALL","validateConfig","resultingOptions","mergeOptions","connectionProtector","LIBP2P_FORCE_PNET","ERR_PROTECTOR_REQUIRED","ERR_INVALID_KEY","getPeerAddress","ERR_INVALID_MULTIADDR","maPeerIdStr","maPeerId","raceEvent","eventName","eventListener","_opts$filter","JobRecipient","where","_this$signal","_this$signal2","Job","created","controller","_curr$signal","recipient","_recipient$signal","Queue","_init$concurrency","_init$metrics","metricName","registerMetricGroup","calculate","running","queued","tryToStartAnother","_this$queue","toGenerator","onQueueJobComplete","onQueueError","onQueueIdle","onSignalAbort","PeerQueue","LAST_DIAL_FAILURE_KEY","minConnections","maxQueueLength","autoDialConcurrency","autoDialPriority","autoDialInterval","autoDialPeerRetryThreshold","autoDialDiscoveredPeersDebounce","AutoDial","_init$minConnections","_init$autoDialPriorit","_init$autoDialInterva","_init$maxQueueLength","_init$autoDialPeerRet","_init$autoDialDiscove","_init$autoDialConcurr","autoDialIntervalMs","autoDialMaxQueueLength","autoDialPeerRetryThresholdMs","autoDial","getConnectionsMap","numConnections","sheduleNextAutodial","dialQueue","getDialQueue","peerValues","peersThatHaveNotFailed","_peerValues$get","_peerValues$get2","peerAValue","peerBValue","lastDialFailure","lastDialFailureTimestamp","maxConnections","allow","ConnectionPruner","_init$maxConnections","_init$allow","maybePruneConnections","toPrune","sortedConnections","connectionALifespan","connectionBLifespan","toClose","maxDialQueueLength","maxPeerAddrsToDial","dialTimeout","DialQueue","_init$addressSorter","_init$maxPeerAddrsToD","_init$maxDialQueueLen","_init$dialTimeout","_init$connections","_init$maxParallelDial","shutDownController","peerIdOrMultiaddr","existingConnection","force","existingDial","createDialAbortController","addrsToDial","calculateMultiaddrs","dialed","ERR_TOO_MANY_ADDRESSES","ERR_TRANSPORT_DIAL_FAILED","userSignal","signals","anySignal","_this$components$conn","_this$components$conn2","ERR_DIALED_SELF","ERR_PEER_DIAL_INTERCEPTED","ERR_NOT_FOUND","peerRouting","findPeer","ERR_NO_ROUTERS_AVAILABLE","resolvedAddresses","resolveMultiaddrs","peerIdMultiaddr","lastProto","filteredAddrs","transportForMultiaddr","addrPeerId","dedupedAddrs","dedupedMultiaddrs","ERR_NO_VALID_ADDRESSES","gatedAdrs","sortedGatedAddrs","DefaultConnectionManager","_init$deny","_init$maxIncomingPend","_init$inboundConnecti","_init$autoDialMaxQueu","deny","incomingPendingConnections","maxIncomingPendingConnections","inboundConnectionRateLimiter","inboundConnectionThreshold","connectionPruner","metric","inbound","conns","_stream$protocol","_metric$key","allStreams","_stream$protocol2","_streams$key","_allStreams$protocol","counts","keepAlivePeers","tasks","connectionList","_onConnect","storedConns","isNewPeer","storedConn","_this$connections$get","_options$priority","ERR_NODE_NOT_STARTED","transient","peerConnections","trackedConnection","closeConnections","_this$connections$get2","acceptIncomingConnection","afterUpgradeInbound","statusMap","errored","complete","CompoundContentRouting","_init$routers","routers","findProviders","seen","router","provide","NOT_STARTED_YET","DefaultPeerRouting","ERR_FIND_SELF","NOT_FOUND","getClosestPeers","_options$concurrency","ordered","ops","sourceErr","slotAvailable","resultAvailable","sourceFinished","opErred","valuesAvailable","_ops$","yieldOrderedValues","yieldUnOrderedValues","task","parallel","useCache","DefaultRegistrar","topologies","_onDisconnect","_onPeerUpdate","_onPeerIdentify","getHandler","ERR_NO_HANDLER_FOR_PROTOCOL","ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED","_topology$onDisconnec","_previous$protocols","_topology$onDisconnec2","TrackedMap","registerMetric","updateComponentMetric","deleted","DefaultTransportManager","_init$faultTolerance","transports","trackedMap","ERR_DUPLICATE_TRANSPORT","ERR_TRANSPORT_UNAVAILABLE","getTransports","getListeners","couldNotListen","supportedAddrs","_this$listeners$get","findIndex","NO_FATAL","_this$listeners$get2","removeAll","PROTOCOL_ID","MAX_PROTOCOL_LENGTH","NewLine","readString","multistream","select","negotiateFully","originalSink","originalSource","negotiated","negotiating","doneNegotiating","sentProtocol","sendingProtocol","doneSendingProtocol","readProtocol","readingProtocol","doneReadingProtocol","negotiate","doSendProtocol","doReadProtocol","sentData","protocolString","originalCloseRead","originalCloseWrite","originalClose","optimisticSelect","connectionSymbol","ConnectionImpl","_init$transient","getStreams","multiplexer","_close","_abort","_getStreams","countStreams","streamCount","DefaultUpgrader","_init$inboundUpgradeT","connectionEncryption","encrypter","muxers","muxer","inboundUpgradeTimeout","shouldBlockConnection","connectionType","ERR_CONNECTION_INTERCEPTED","upgradeInbound","ERR_CONNECTION_DENIED","encryptedConn","upgradedConn","muxerFactory","cryptoProtocol","_this$components$metr","trackMultiaddrConnection","protectedConn","skipProtection","protector","protect","skipEncryption","_encryptInbound","idStr","remotePeerId","multiplexed","_multiplexInbound","_createConnection","_this$components$metr2","_encryptOutbound","ERR_INVALID_PEER","_multiplexOutbound","_muxer","muxedStream","_this$components$metr3","mss","incomingLimit","findIncomingStreamLimit","ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS","trackProtocolStream","_onStream","ERR_MUXER_UNAVAILABLE","_this$components$metr4","outgoingLimit","_options$maxOutboundS","findOutgoingStreamLimit","ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS","ERR_UNSUPPORTED_PROTOCOL","_timeline","Proxy","upgraded","errConnectionNotMultiplexed","ERR_CONNECTION_NOT_MULTIPLEXED","ERR_ENCRYPTION_FAILED","_Libp2pNode_brand","Libp2pNode","_init$logger","_init$nodeInfo","_init$datastore","_init$connectionEncry","_init$streamMuxers","_init$peerRouters","_init$contentRouters","_init$peerDiscovery","_init$transports","originalDispatch","internalResult","externalResult","service","defaultComponents","configureComponent","streamMuxers","peerRouters","contentRouters","contentRouting","peerDiscovery","_onDiscoveryPeer","createService","_service$peerDiscover","_service$peerDiscover2","component","_this$components$befo","_this$components","_this$components$afte","_this$components2","_this$components$befo2","_this$components3","_this$components$afte2","_this$components4","dialProtocol","ERR_INVALID_PROTOCOLS_FOR_STREAM","getMultiaddrs","_peer$getPeerId","peerKey","ERR_DISCOVERED_SELF","createLibp2p","_options$peerId","_options$privateKey","createLibp2pNode","BaseProtocolSDK","LightPushSDK","sendPromises","StoreSDK","queryGenerator","decodersAsMap","validateDecodersAndPubsubTopic","constructOptions","responseGenerator","queryWithOrderedCallback","processMessages","queryWithPromiseCallback","page","_promises","msgPromise","createCursor","messageTime","_options$cursor","uniquePubsubTopicsInQuery","pubsubTopicForQuery","_options$cursor2","timeFilter","processedMessages","shouldReverseOrder","createLightNode","_shardInfo$pubsubTopi","_options$libp2p","_libp2pOptions$peerDi","libp2pOptions","defaultBootstrap","wakuDnsDiscovery","enrTree","DEFAULT_NODE_REQUIREMENTS","wakuLocalPeerCacheDiscovery","wakuPeerExchangeDiscovery","wakuGossipSub","_process","hideWebSocketInfo","NODE_ENV","pubsubService","filterAll","DefaultUserAgent","defaultLibp2p","createLibp2pAndUpdateOptions","wakuStore","wakuLightPush","wakuFilter","WakuNode","prepareSubscription","mapToPeerIdOrMultiaddr","codecs","subscribeToContentTopic","_opts$waku2","getLocalMultiaddrWithID","localMultiaddr","TEST","SANDBOX","DEFAULT_BOOTSTRAP_TAG_NAME","groupLen","USE_ENDOMORPHISM","ShaError","assertJacPoint","JacobianPoint","toAffineBatch","scratch","Z1Z1","Z2Z2","S1","S2","x1b","HH","HHH","P0","normalizeScalar","affinePoint","invZ","iz1","iz2","iz3","fromCompressedHex","isShort","bytesToNumber","isValidFieldElement","rt","isYOdd","fromUncompressedHex","normalizePrivateKey","fromSignature","normalizeSignature","truncateHash","rinv","numTo32bStr","toHexX","toRawX","aP","bQ","sliceDER","parseDERInt","parseDERSignature","HALF","sHex","numberToHexUnpadded","rHex","sHexL","rHexL","sLen","rLen","uint8a","POW_2_256","numTo32b","hexByte","truncateOnly","bits2int_2","_sha256Sync","_hmacSha256Sync","HmacDrbg","hmacSha256","hmacSync","checkSync","incr","reseedSync","kmdToSig","kinv","normalizePublicKey","bits2octets","z1","initSigArgs","finalizeSig","recSig","recovered","canonical","vopts","nodeCrypto","web","TAGGED_HASH_PREFIXES","_bigintTo32Bytes","_normalizePrivateKey","hashToPrivateKey","_len4","_key4","createHash","_len5","_key5","ckey","createHmac","sha256Sync","hmacSha256Sync","taggedHash","tagP","tagH","_len6","_key6","taggedHashSync","_len7","_key7","_JacobianPoint","defineProperties","keccak256","sha3","verifySignature","sinv","ERR_INVALID_ID","locationMultiaddrFromEnrFields","isIpv6","ipVal","protoName","protoVal","ipFamily","ipBytes","protocolBytes","multiaddrFromFields","createPeerIdFromPublicKey","encodeMultiaddrs","encodeWaku2","RawEnr","kvs","rsv","getStringValue","setStringValue","getNumberAsStringValue","setNumberAsStringValue","tcp6","udp6","multiaddrBytes","decodeMultiaddrs","deleteUndefined","waku2","decodeWaku2","TransportProtocol","TransportProtocolPerIpVersion","ENR","nodeId","uncompressedPubkey","setLocationMultiaddr","getAllLocationMultiaddrs","_this$multiaddrs","getLocationMultiaddr","_multiaddrs","getFullMultiaddr","locationMultiaddr","getFullMultiaddrs","_permanentCensorErrors","_censorErrors","LogLevels","warning","_logLevel","_globalLogger","_normalizeError","missing","normalize","_checkNormalize","LogLevel","ErrorCode","HEX","_log","logLevel","throwArgumentError","levels","INFO","WARNING","makeError","UNKNOWN_ERROR","messageDetails","NUMERIC_FAULT","fault","CALL_EXCEPTION","INSUFFICIENT_FUNDS","MISSING_NEW","NONCE_EXPIRED","REPLACEMENT_UNDERPRICED","TRANSACTION_REPLACED","UNPREDICTABLE_GAS_LIMIT","throwError","INVALID_ARGUMENT","argument","assert","assertArgument","checkNormalize","UNSUPPORTED_OPERATION","checkSafeUint53","checkArgumentCount","expectedCount","MISSING_ARGUMENT","UNEXPECTED_ARGUMENT","checkNew","kind","checkAbstract","globalLogger","setCensorship","censorship","permanent","setLogLevel","isHexable","toHexString","addSlice","isBytesLike","isHexString","arrayify","allowMissingPrefix","hexPad","HexCharacters","hexlify","arrayifyInteger","unarrayifyInteger","_encode","_decodeChildren","childOffset","_decode","consumed","BUFFER_OVERRUN","EnrDecoder","encoded","RECORD_PREFIX","fromRLP","RLP","checkValues","_seq","decodeSeq","rlpEncodedBytes","checkSignature","fromValues","v4Regex","v6Regex","isFormat","buff","hexN","decN","prevColon","useDec","sizeOf","toType","rcode","opcode","klass","toClass","toCode","SURROGATE_A","SURROGATE_B","nextCode","numA","isU8Arr","bytelength","P_24","P_16","P_8","readUInt32BE","readUInt16BE","writeUInt32BE","writeUInt16BE","targetStart","sourceStart","sourceEnd","sourceLen","_copyActual","FLUSH_MASK","consumedBytes","jumped","toUtf8","jumpOffset","authorities","additionals","flag_qr","opcodes","flag_aa","flag_z","rcodes","runknown","dLen","rns","rsoa","mname","rname","serial","refresh","retry","minimum","rtxt","rnull","rhinfo","cpu","os","rptr","rsrv","weight","rcaa","issuerCritical","ISSUER_CRITICAL","rmx","preference","raaaa","roption","optioncodes","spl","sourcePrefixLength","fam","ipBuf","ipLen","scopePrefixLength","tagsLen","padded","ropt","rdlen","encodingLengthList","encodeList","rdnskey","keydata","PROTOCOL_DNSSEC","ZONE_KEY","SECURE_ENTRYPOINT","rrrsig","typeCovered","labels","originalTTL","expiration","inception","keyTag","signersName","rrp","mbox","txt","typebitmap","typelist","typesByWindow","typeid","windowBuf","windowLength","extents","rnsec","nextDomain","rrtypes","rnsec3","hashLength","rds","digestdata","digestType","renc","udpPayloadSize","extendedRcode","ednsVersion","classes","class","flag_do","RECURSION_DESIRED","packet","allocing","decodeList","sanitizeSingle","sanitized","make","charset","paddingMode","byCharCode","byNum","padCode","safeLen","safeEnd","base64URL","HTTPStatusError","endpoint","ResponseError","cause","reduceError","baseParts","httpFlags","updFlags","parseFlags","InvalidProtocolError","BaseEndpoint","isHTTP","UDPEndpoint","ipv6","UDP4Endpoint","UDP6Endpoint","safeHost","HTTPEndpoint","v6Parts","toEndpoint","post","parseEndpoint","contentType","requestRaw","abortSignal","xhr","XMLHttpRequest","setRequestHeader","responseType","ontimeout","onreadystatechange","onload","utf8Codec","onabort","processResolvers","cors","lib","endpoints","resolverByName","byName","endpointByName","backup","description","country","lat","queryOne","queryDoh","UPDATE_URL","isNameString","wellknown","updateURL","localStoragePrefix","maxAge","_dataP","_data","outdated","cacheKey","maxTime","filterDoh","filterDns","retries","queryN","singleQuery","toMultiQuery","DnsOverHttps","_endpoints","resolveTXT","ENRTree","parseAndVerifyRoot","ROOT_PREFIX","rootValues","parseRootValues","decodedPublicKey","signedComponent","signedComponentBuffer","signatureBuffer","eRoot","lRoot","parseTree","tree","TREE_PREFIX","parseBranch","branch","BRANCH_PREFIX","isSatisfied","wanted","actual","addCapabilities","helpsSatisfyCapabilities","missingCapabilities","DnsNodeDiscovery","dnsOverHttp","dnsClient","enrTreeUrls","wantedNodeCapabilityCount","networkIndex","visits","errorTolerance","getNode","_wantedNodeCapability","_wantedNodeCapability2","_wantedNodeCapability3","_wantedNodeCapability4","maxSearches","totalSearches","fetchNodesUntilCapabilitiesFulfilled","_errorTolerance","_search","_peer$peerId","_peer$multiaddrs","_DNSTreeCache","getNextPeer","_wantedNodeCapability5","_wantedNodeCapability6","_wantedNodeCapability7","_wantedNodeCapability8","peerNodeIds","yieldNodesUntilCapabilitiesFulfilled","subdomain","_getTXTRecord","branches","entryType","getEntryType","circularRefs","selectRandomPath","PeerDiscoveryDns","_components","enrUrls","nextPeer","peerEnr","_this$_options$tagVal","_this$_options$tagTTL","tagsToUpdate","isPeerChanged","PeerExchangeCodec","WakuPeerExchange","rpcQuery","DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS","DEFAULT_MAX_RETRIES","DEFAULT_PEER_EXCHANGE_TAG_NAME","PeerExchangeDiscovery","queryingPeers","startRecurringQueries","_this$queryAttempts$g","_this$queryAttempts$g2","queryInterval","maxRetries","queryAttempts","currentAttempt","abortQueriesForPeer","peerExchange","handleDiscoveredPeer","_this$options$tagValu","_this$options$tagTTL","DEFAULT_LOCAL_TAG_NAME","LocalPeerCacheDiscovery","websocketMultiaddr","wsMultiaddr","getWsMultiaddrFromMultiaddrs","localStoragePeers","getPeersFromLocalStorage","existingPeerIndex","savePeersToLocalStorage","handleNewPeers","_this$options$tagName","_this$options2","_this$options3","storedPeersData","isValidStoredPeer","ContentPairContext","React","useContentPair","ContentPairProvider","setEncoder","setDecoder","useCreateContentPair","useCreateLightNode","setNode","isLoading","setLoading","setError","cancelled","useCreateNode","useLightPush","WakuContext","useWaku","LightNodeProvider","handleCommand","setNick","replaceAll","parseInput","command","nick","peerMultiaddr","strConnections","ChatList","renderedMessages","_message$sentTimestam","_jsxs","className","_jsx","formatDisplayDate","payloadAsUtf8","sentTimestamp","AlwaysScrollToBottom","toLocaleString","hour12","elementRef","scrollIntoView","MessageInput","hasLightPushPeers","inputText","setInputText","isActive","setActiveButton","onChange","onKeyDown","ReaderClass","ReaderBufferClass","WriterClass","WriterBufferClass","patchReader","patchWriter","ChatMessage","_ChatMessage","fromUtf8String","timestampNumber","chatMessage","cmp","fromWakuMessage","wakuMsg","chatMsg","OrderedSet","orderCmp","insertInOrder","getPeerIdsForProtocol","useMessages","newMessages","setMessage","unsubscribeFn","useFilterMessages","storedMessages","filteredMessages","useStoreMessages","localMessages","setLocalMessages","allMessages","tomorrow","setDate","getDate","_msgs","useNodePeers","discoveredBootstrapPeers","setBootstrapPeers","connectedBootstrapPeers","setConnectedBootstrapPeers","discoveredPeerExchangePeers","setPeerExchangePeers","connectedPeerExchangePeers","setConnectedPeerExchangePeers","handleDiscoveryBootstrap","isPeerDialable","handleConnectBootstrap","handleDiscoveryPeerExchange","handleConnectPeerExchange","initHookData","usePeers","setPeers","peerIds","allConnected","storePeers","filterPeers","lightPushPeers","isMultiaddrConnectable","Room","onPush","allConnectedLength","orZero","lightPushPeersLength","filterPeersLength","storePeersLength","commandHandler","App","pushLocalMessages","usePersistentNick","persistedNick","commandMessages","ReactDOM","getElementById"],"sourceRoot":""} \ No newline at end of file diff --git a/experimental/web-chat/static/js/main.b0962d94.js b/experimental/web-chat/static/js/main.b0962d94.js new file mode 100644 index 0000000..bd2ec1e --- /dev/null +++ b/experimental/web-chat/static/js/main.b0962d94.js @@ -0,0 +1,3 @@ +/*! For license information please see main.b0962d94.js.LICENSE.txt */ +(()=>{var __webpack_modules__={4762:e=>{"use strict";e.exports=function(e,t){var r=new Array(arguments.length-1),n=0,i=2,s=!0;for(;i{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),i=new Array(123),s=0;s<64;)i[n[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;r.encode=function(e,t,r){for(var i,s=null,o=[],a=0,c=0;t>2],i=(3&u)<<4,c=1;break;case 1:o[a++]=n[i|u>>4],i=(15&u)<<2,c=2;break;case 2:o[a++]=n[i|u>>6],o[a++]=n[63&u],c=0}a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=n[i],o[a++]=61,1===c&&(o[a++]=61)),s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var o="invalid encoding";r.decode=function(e,t,r){for(var n,s=r,a=0,c=0;c1)break;if(void 0===(u=i[u]))throw Error(o);switch(a){case 0:n=u,a=1;break;case 1:t[r++]=n<<2|(48&u)>>4,n=u,a=2;break;case 2:t[r++]=(15&n)<<4|(60&u)>>2,n=u,a=3;break;case 3:t[r++]=(3&n)<<6|u,a=0}}if(1===a)throw Error(o);return r-s},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},7351:e=>{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n{"use strict";function t(e){return"undefined"!==typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3]}function s(e,n,i){t[0]=e,n[i]=r[3],n[i+1]=r[2],n[i+2]=r[1],n[i+3]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?i:s,e.writeFloatBE=n?s:i,e.readFloatLE=n?o:a,e.readFloatBE=n?a:o}():function(){function t(e,t,r,n){var i=t<0?1:0;if(i&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((i<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((i<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var s=Math.floor(Math.log(t)/Math.LN2);e((i<<31|s+127<<23|8388607&Math.round(t*Math.pow(2,-s)*8388608))>>>0,r,n)}}function o(e,t,r){var n=e(t,r),i=2*(n>>31)+1,s=n>>>23&255,o=8388607&n;return 255===s?o?NaN:i*(1/0):0===s?1401298464324817e-60*i*o:i*Math.pow(2,s-150)*(o+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=o.bind(null,i),e.readFloatBE=o.bind(null,s)}(),"undefined"!==typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3],n[i+4]=r[4],n[i+5]=r[5],n[i+6]=r[6],n[i+7]=r[7]}function s(e,n,i){t[0]=e,n[i]=r[7],n[i+1]=r[6],n[i+2]=r[5],n[i+3]=r[4],n[i+4]=r[3],n[i+5]=r[2],n[i+6]=r[1],n[i+7]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?i:s,e.writeDoubleBE=n?s:i,e.readDoubleLE=n?o:a,e.readDoubleBE=n?a:o}():function(){function t(e,t,r,n,i,s){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,i,s+t),e(1/n>0?0:2147483648,i,s+r);else if(isNaN(n))e(0,i,s+t),e(2146959360,i,s+r);else if(n>17976931348623157e292)e(0,i,s+t),e((o<<31|2146435072)>>>0,i,s+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,i,s+t),e((o<<31|a/4294967296)>>>0,i,s+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,i,s+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,i,s+r)}}}function o(e,t,r,n,i){var s=e(n,i+t),o=e(n,i+r),a=2*(o>>31)+1,c=o>>>20&2047,u=4294967296*(1048575&o)+s;return 2047===c?u?NaN:a*(1/0):0===c?5e-324*a*u:a*Math.pow(2,c-1075)*(u+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=o.bind(null,i,0,4),e.readDoubleBE=o.bind(null,s,4,0)}(),e}function r(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function i(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},4882:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},6931:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(r){if(r<1||r>i)return e(r);o+r>n&&(s=e(n),o=0);var a=t.call(s,o,o+=r);return 7&o&&(o=1+(7|o)),a}}},8626:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?s[o++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(n>>10),s[o++]=56320+(1023&n)):s[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0);return i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))},r.write=function(e,t,r){for(var n,i,s=r,o=0;o>6|192,t[r++]=63&n|128):55296===(64512&n)&&56320===(64512&(i=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&i),++o,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-s}},6522:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(r){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(r){}!e&&"undefined"!==typeof process&&"env"in process&&(e={NODE_ENV:"production",PUBLIC_URL:"/web-chat",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}.DEBUG);return e},t.useColors=function(){if("undefined"!==typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!==typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!==typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(5237)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}},5237:(e,t,r)=>{e.exports=function(e){function t(e){let r,i,s,o=null;function a(){for(var e=arguments.length,n=new Array(e),i=0;i{if("%%"===e)return"%";u++;const i=t.formatters[r];if("function"===typeof i){const t=n[u];e=i.call(s,t),n.splice(u,1),u--}return e})),t.formatArgs.call(s,n);(s.log||t.log).apply(s,n)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"===typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+("undefined"===typeof r?":":r)+e);return n.log=this.log,n}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"===typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";function t(e,t){t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(e)?this._fromArray(e):(this._capacityMask=3,this._list=new Array(4))}t.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}},t.prototype.get=function(e){return this.peekAt(e)},t.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},t.prototype.peekFront=function(){return this.peek()},t.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(t.prototype,"length",{get:function(){return this.size()}}),t.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},t.prototype.push=function(e){if(0===arguments.length)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var i,s=this._list[t];if(e0;i--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(i=r-1-e;i>0;i--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return s}}},t.prototype.remove=function(e,t){var r,n=e,i=t;if(n===(0|n)&&this._head!==this._tail){var s=this.size(),o=this._list.length;if(!(n>=s||n<-s||t<1)){if(n<0&&(n+=s),1===t||!t)return(r=new Array(1))[0]=this.removeOne(n),r;if(0===n&&n+t>=s)return r=this.toArray(),this.clear(),r;var a;for(n+t>s&&(t=s-n),r=new Array(t),a=0;a0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+o&this._capacityMask,a=t-1;a>0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(n0;a--)this.unshift(this._list[n=n-1+o&this._capacityMask]);for(n=this._head-1+o&this._capacityMask;i>0;)this._list[n=n-1+o&this._capacityMask]=void 0,i--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+o&this._capacityMask,a=s-(t+e);a>0;a--)this.push(this._list[n++]);for(n=this._tail;i>0;)this._list[n=n+1+o&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=o>>>2&&this._shrinkArray(),r}}},t.prototype.splice=function(e,t){var r=e;if(r===(0|r)){var n=this.size();if(r<0&&(r+=n),!(r>n)){if(arguments.length>2){var i,s,o,a=arguments.length,c=this._list.length,u=2;if(!n||r0&&(this._head=this._head+r+c&this._capacityMask)):(o=this.remove(r,t),this._head=this._head+r+c&this._capacityMask);a>u;)this.unshift(arguments[--a]);for(i=r;i>0;i--)this.unshift(s[i-1])}else{var l=(s=new Array(n-(r+t))).length;for(i=0;ithis._tail){for(s=this._head;s>>=1,this._capacityMask>>>=1},t.prototype._nextPowerOf2=function(e){var t=1<{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,n){if(!e||"string"===typeof e)throw new TypeError("Please pass an Error to err-code");n||(n={}),"object"===typeof r&&(n=r,r=""),r&&(n.code=r);try{return t(e,n)}catch(i){n.message=e.message,n.stack=e.stack;const r=function(){};r.prototype=Object.create(Object.getPrototypeOf(e));return t(new r,n)}}},2605:(e,t,r)=>{"use strict";const n=r(9020);t.PP=n.EventIterator,n.EventIterator},9020:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e){let{highWaterMark:t=100,lowWaterMark:n=1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new r;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},7283:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,o){if("function"!==typeof n)throw new TypeError("The listener must be a function");var a=new i(n,s||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i{e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function i(i,s){r[i]=s,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},5411:(e,t,r)=>{var n;!function(){"use strict";var t="object"===typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"===typeof process&&process.versions&&process.versions.node&&(t=r.g);var i=!t.HI_BASE32_NO_COMMON_JS&&e.exports,s=r.amdO,o="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},c=[0,0,0,0,0,0,0,0],u=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},l=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,r,n,i,s,o,c,u,l=[],h=0,d=(e=e.replace(/=/g,"")).length,f=0,p=d>>3<<3;f>>2),l[h++]=255&(r<<6|n<<1|i>>>4),l[h++]=255&(i<<4|s>>>1),l[h++]=255&(s<<7|o<<2|c>>>3),l[h++]=255&(c<<5|u);var g=d-p;return 2===g?(t=a[e.charAt(f++)],r=a[e.charAt(f++)],l[h++]=255&(t<<3|r>>>2)):4===g?(t=a[e.charAt(f++)],r=a[e.charAt(f++)],n=a[e.charAt(f++)],i=a[e.charAt(f++)],l[h++]=255&(t<<3|r>>>2),l[h++]=255&(r<<6|n<<1|i>>>4)):5===g?(t=a[e.charAt(f++)],r=a[e.charAt(f++)],n=a[e.charAt(f++)],i=a[e.charAt(f++)],s=a[e.charAt(f++)],l[h++]=255&(t<<3|r>>>2),l[h++]=255&(r<<6|n<<1|i>>>4),l[h++]=255&(i<<4|s>>>1)):7===g&&(t=a[e.charAt(f++)],r=a[e.charAt(f++)],n=a[e.charAt(f++)],i=a[e.charAt(f++)],s=a[e.charAt(f++)],o=a[e.charAt(f++)],c=a[e.charAt(f++)],l[h++]=255&(t<<3|r>>>2),l[h++]=255&(r<<6|n<<1|i>>>4),l[h++]=255&(i<<4|s>>>1),l[h++]=255&(s<<7|o<<2|c>>>3)),l},h=function(e,t){if(!t)return function(e){for(var t,r,n="",i=e.length,s=0,o=0;s191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):u(s,n);for(var a=0;a191)&&u(s,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&u(s,n),r>1114111&&u(s,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296+(r>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n}(l(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var r,n,i,s,o,c,h,d,f="",p=e.indexOf("=");-1===p&&(p=e.length);for(var g=0,b=p>>3<<3;g>>2))+String.fromCharCode(255&(n<<6|i<<1|s>>>4))+String.fromCharCode(255&(s<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=p-b;return 2===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))):4===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|s>>>4))):5===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|s>>>4))+String.fromCharCode(255&(s<<4|o>>>1))):7===y&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],f+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|s>>>4))+String.fromCharCode(255&(s<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))),f},d={encode:function(e,t){var r="string"!==typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?function(e){for(var t,r,n,i,s,a="",c=e.length,u=0,l=5*parseInt(c/5);u>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|i>>>7)]+o[i>>>2&31]+o[31&(i<<3|s>>>5)]+o[31&s];var h=c-l;return 1===h?(t=e[u],a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e[u++],r=e[u],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e[u++],r=e[u++],n=e[u],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e[u++],r=e[u++],n=e[u++],i=e[u],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|i>>>7)]+o[i>>>2&31]+o[i<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,i,s,a="",c=e.length,u=0,l=5*parseInt(c/5);u>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|i>>>7)]+o[i>>>2&31]+o[31&(i<<3|s>>>5)]+o[31&s];var h=c-l;return 1===h?(t=e.charCodeAt(u),a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e.charCodeAt(u++),r=e.charCodeAt(u),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e.charCodeAt(u++),r=e.charCodeAt(u++),n=e.charCodeAt(u),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(u++),r=e.charCodeAt(u++),n=e.charCodeAt(u++),i=e.charCodeAt(u),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|i>>>7)]+o[i>>>2&31]+o[i<<3&31]+"="),a}(e):function(e){var t,r,n,i,s,a,u,l=!1,h="",d=0,f=0,p=e.length;if(""===e)return h;do{for(c[0]=c[5],c[1]=c[6],c[2]=c[7],u=f;d>6,c[u++]=128|63&a):a<55296||a>=57344?(c[u++]=224|a>>12,c[u++]=128|a>>6&63,c[u++]=128|63&a):(a=65536+((1023&a)<<10|1023&e.charCodeAt(++d)),c[u++]=240|a>>18,c[u++]=128|a>>12&63,c[u++]=128|a>>6&63,c[u++]=128|63&a);f=u-5,d===p&&++d,d>p&&u<6&&(l=!0),t=c[0],u>4?(r=c[1],n=c[2],i=c[3],s=c[4],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|i>>>7)]+o[i>>>2&31]+o[31&(i<<3|s>>>5)]+o[31&s]):1===u?h+=o[t>>>3]+o[t<<2&31]+"======":2===u?(r=c[1],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===u?(r=c[1],n=c[2],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):(r=c[1],n=c[2],i=c[3],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|i>>>7)]+o[i>>>2&31]+o[i<<3&31]+"=")}while(!l);return h}(e)},decode:h};h.asBytes=l,i?e.exports=d:(t.base32=d,s&&(void 0===(n=function(){return d}.call(d,r,d,e))||(e.exports=n)))}()},4053:e=>{e.exports=function(){return"undefined"!==typeof window&&"object"===typeof window.process&&"renderer"===window.process.type||(!("undefined"===typeof process||"object"!==typeof process.versions||!process.versions.electron)||"object"===typeof navigator&&"string"===typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0)}},8313:e=>{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},2161:(e,t,r)=>{var n;!function(){"use strict";var i="input is invalid type",s="object"===typeof window,o=s?window:{};o.JS_SHA3_NO_WINDOW&&(s=!1);var a=!s&&"object"===typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"===typeof process&&process.versions&&process.versions.node?o=r.g:a&&(o=self);for(var c=!o.JS_SHA3_NO_COMMON_JS&&e.exports,u=r.amdO,l=!o.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!==typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],f=[0,8,16,24],p=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],b=[128,256],y=["hex","buffer","arrayBuffer","array","digest"],m={128:168,256:136},w=o.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=!l||!o.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(e){return"object"===typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer},_=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(i);if(l&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!w(e)&&!v(e))throw new Error(i);return[e,!1]},E=function(e){return 0===_(e)[0].length},S=function(e){for(var t=[],r=0;r>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function K(e,t,r){q.call(this,e,t,r)}q.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=_(e);e=t[0];for(var r,n,i=t[1],s=this.blocks,o=this.byteCount,a=e.length,c=this.blockCount,u=0,l=this.s;u>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(s[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=e[u]<=o){for(this.start=r-o,this.block=s[c],r=0;r>=8);r>0;)i.unshift(r),r=255&(e>>=8),++n;return t?i.push(n):i.unshift(n),this.update(i),i.length},q.prototype.encodeString=function(e){var t=_(e);e=t[0];var r=t[1],n=0,i=e.length;if(r)for(var s=0;s=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++s)),n+=4)}else n=i;return n+=this.encode(8*n),this.update(e),n},q.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];o%t===0&&(r=S(r),F(r),s=0)}return i&&(e=r[s],a+=h[e>>4&15]+h[15&e],i>1&&(a+=h[e>>12&15]+h[e>>8&15]),i>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},q.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r===0&&(n=S(n),F(n))}return s&&(e=a<<2,t=n[o],c[e]=255&t,s>1&&(c[e+1]=t>>8&255),s>2&&(c[e+2]=t>>16&255)),c},K.prototype=new q,K.prototype.finalize=function(){return this.encode(this.outputBits,!0),q.prototype.finalize.call(this)};var F=function(e){var t,r,n,i,s,o,a,c,u,l,h,d,f,g,b,y,m,w,v,_,E,S,A,k,x,I,C,T,R,P,D,N,B,U,L,M,O,q,K,F,V,z,$,H,j,G,W,Y,Q,J,X,Z,ee,te,re,ne,ie,se,oe,ae,ce,ue,le;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],u=e[5]^e[15]^e[25]^e[35]^e[45],l=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|u>>>31),r=s^(u<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(l<<1|h>>>31),r=a^(h<<1|l>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|f>>>31),r=u^(f<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=l^(i<<1|s>>>31),r=h^(s<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],b=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,R=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,$=e[41]<<18|e[40]>>>14,U=e[2]<<1|e[3]>>>31,L=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,m=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,Q=e[23]<<10|e[22]>>>22,P=e[33]<<13|e[32]>>>19,D=e[32]<<13|e[33]>>>19,ue=e[42]<<2|e[43]>>>30,le=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,M=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,X=e[35]<<15|e[34]>>>17,N=e[45]<<29|e[44]>>>3,B=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,x=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,q=e[26]<<25|e[27]>>>7,K=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,E=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,H=e[8]<<27|e[9]>>>5,j=e[9]<<27|e[8]>>>5,I=e[18]<<20|e[19]>>>12,C=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,F=e[38]<<8|e[39]>>>24,V=e[39]<<8|e[38]>>>24,S=e[48]<<14|e[49]>>>18,A=e[49]<<14|e[48]>>>18,e[0]=g^~y&w,e[1]=b^~m&v,e[10]=k^~I&T,e[11]=x^~C&R,e[20]=U^~M&q,e[21]=L^~O&K,e[30]=H^~G&Y,e[31]=j^~W&Q,e[40]=te^~ne&se,e[41]=re^~ie&oe,e[2]=y^~w&_,e[3]=m^~v&E,e[12]=I^~T&P,e[13]=C^~R&D,e[22]=M^~q&F,e[23]=O^~K&V,e[32]=G^~Y&J,e[33]=W^~Q&X,e[42]=ne^~se&ae,e[43]=ie^~oe&ce,e[4]=w^~_&S,e[5]=v^~E&A,e[14]=T^~P&N,e[15]=R^~D&B,e[24]=q^~F&z,e[25]=K^~V&$,e[34]=Y^~J&Z,e[35]=Q^~X&ee,e[44]=se^~ae&ue,e[45]=oe^~ce&le,e[6]=_^~S&g,e[7]=E^~A&b,e[16]=P^~N&k,e[17]=D^~B&x,e[26]=F^~z&U,e[27]=V^~$&L,e[36]=J^~Z&H,e[37]=X^~ee&j,e[46]=ae^~ue&te,e[47]=ce^~le&re,e[8]=S^~g&y,e[9]=A^~b&m,e[18]=N^~k&I,e[19]=B^~x&C,e[28]=z^~U&M,e[29]=$^~L&O,e[38]=Z^~H&G,e[39]=ee^~j&W,e[48]=ue^~te&ne,e[49]=le^~re&ie,e[0]^=p[n],e[1]^=p[n+1]};if(c)e.exports=P;else{for(N=0;NObject.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},u=e=>{const t=[];for(const r in e)i.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)s.call(e,n)&&t.push(n)}return t};function l(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return u(e).forEach((r=>{o(t,r,l(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return u(e).forEach((r=>{o(t,r,l(e[r]))})),t}(e):e}const h=(e,t,r,n)=>(r.forEach((r=>{"undefined"===typeof t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?o(e,r,f(e[r],t[r],n)):o(e,r,l(t[r])))})),e),d=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r!a.includes(e))),r)})),n};function f(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?d(e,t,r):n(t)&&n(e)?h(e,t,u(t),r):l(t)}e.exports=function(){const e=f(l(c),this!==a&&this||{},c);let t={_:{}};for(var r=arguments.length,i=new Array(r),s=0;s{var t=1e3,r=60*t,n=60*r,i=24*n,s=7*i,o=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var u=typeof e;if("string"===u&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*o;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===u&&isFinite(e))return c.long?function(e){var s=Math.abs(e);if(s>=i)return a(e,s,i,"day");if(s>=n)return a(e,s,n,"hour");if(s>=r)return a(e,s,r,"minute");if(s>=t)return a(e,s,t,"second");return e+" ms"}(e):function(e){var s=Math.abs(e);if(s>=i)return Math.round(e/i)+"d";if(s>=n)return Math.round(e/n)+"h";if(s>=r)return Math.round(e/r)+"m";if(s>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},7364:function(e,t){(function(){var e,r,n,i,s,o,a,c;c=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,i,s,o,a;for(t=[],i=s=0;s<=3&&0!==e.length;i=++s){if(i>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}o=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(o)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},i=(n=function(e){return e.charCodeAt(0)})("0"),o=n("a"),s=n("A"),r=function(e){var t,r,a,c,u;for(c=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),u=a;a>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-o)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-s)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===u)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,i;if("string"!==typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"===typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(s){throw s,new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(s){throw s,new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"===typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(c(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},9353:(e,t,r)=>{var n=r(45);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.aes.Algorithm(e,t)}))}r(9151),r(1655),r(3900),e.exports=n.aes=n.aes||{},n.aes.startEncrypting=function(e,t,r,n){var i=g({key:e,output:r,decrypt:!1,mode:n});return i.start(t),i},n.aes.createEncryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!1,mode:t})},n.aes.startDecrypting=function(e,t,r,n){var i=g({key:e,output:r,decrypt:!0,mode:n});return i.start(t),i},n.aes.createDecryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!0,mode:t})},n.aes.Algorithm=function(e,t){l||d();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return p(r._w,e,t,!1)},decrypt:function(e,t){return p(r._w,e,t,!0)}}}),r._init=!1},n.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!==typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(n.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=n.util.createBuffer();for(var i=0;i>>=2;for(i=0;i>8^255&h^99,s[g]=h,o[h]=g,f=(d=e[h])<<24^h<<16^h<<8^h^d,p=((r=e[g])^(n=e[r])^(i=e[n]))<<24^(g^i)<<16^(g^n^i)<<8^g^r^i;for(var y=0;y<4;++y)c[y][g]=f,u[y][h]=p,f=f<<24|f>>>8,p=p<<24|p>>>8;0===g?g=b=1:(g=r^e[e[e[r^i]]],b^=e[e[b]])}}function f(e,t){for(var r,n=e.slice(0),i=1,o=n.length,c=h*(o+6+1),l=o;l>>16&255]<<24^s[r>>>8&255]<<16^s[255&r]<<8^s[r>>>24]^a[i]<<24,i++):o>6&&l%o===4&&(r=s[r>>>24]<<24^s[r>>>16&255]<<16^s[r>>>8&255]<<8^s[255&r]),n[l]=n[l-o]^r;if(t){for(var d,f=u[0],p=u[1],g=u[2],b=u[3],y=n.slice(0),m=(l=0,(c=n.length)-h);l>>24]]^p[s[d>>>16&255]]^g[s[d>>>8&255]]^b[s[255&d]];n=y}return n}function p(e,t,r,n){var i,a,l,h,d,f,p,g,b,y,m,w,v=e.length/4-1;n?(i=u[0],a=u[1],l=u[2],h=u[3],d=o):(i=c[0],a=c[1],l=c[2],h=c[3],d=s),f=t[0]^e[0],p=t[n?3:1]^e[1],g=t[2]^e[2],b=t[n?1:3]^e[3];for(var _=3,E=1;E>>24]^a[p>>>16&255]^l[g>>>8&255]^h[255&b]^e[++_],m=i[p>>>24]^a[g>>>16&255]^l[b>>>8&255]^h[255&f]^e[++_],w=i[g>>>24]^a[b>>>16&255]^l[f>>>8&255]^h[255&p]^e[++_],b=i[b>>>24]^a[f>>>16&255]^l[p>>>8&255]^h[255&g]^e[++_],f=y,p=m,g=w;r[0]=d[f>>>24]<<24^d[p>>>16&255]<<16^d[g>>>8&255]<<8^d[255&b]^e[++_],r[n?3:1]=d[p>>>24]<<24^d[g>>>16&255]<<16^d[b>>>8&255]<<8^d[255&f]^e[++_],r[2]=d[g>>>24]<<24^d[b>>>16&255]<<16^d[f>>>8&255]<<8^d[255&p]^e[++_],r[n?1:3]=d[b>>>24]<<24^d[f>>>16&255]<<16^d[p>>>8&255]<<8^d[255&g]^e[++_]}function g(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var s=null;r instanceof n.util.ByteBuffer&&(s=r,r={}),(r=r||{}).output=s,r.iv=e,i.call(t,r)},t}},5465:(e,t,r)=>{var n=r(45);r(3900),r(3225);var i=e.exports=n.asn1=n.asn1||{};function s(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}i.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},i.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},i.create=function(e,t,r,s,o){if(n.util.isArray(s)){for(var a=[],c=0;ct){if(n.strict){var p=new Error("Too few bytes to read ASN.1 value.");throw p.available=e.length(),p.remaining=t,p.requested=f,p}f=t}var g=32===(32&c);if(g)if(h=[],void 0===f)for(;;){if(s(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}a=e.length(),h.push(o(e,t,r+1,n)),t-=a-e.length()}else for(;f>0;)a=e.length(),h.push(o(e,f,r+1,n)),t-=a-e.length(),f-=a-e.length();if(void 0===h&&u===i.Class.UNIVERSAL&&l===i.Type.BITSTRING&&(d=e.bytes(f)),void 0===h&&n.decodeBitStrings&&u===i.Class.UNIVERSAL&&l===i.Type.BITSTRING&&f>1){var b=e.read,y=t,m=0;if(l===i.Type.BITSTRING&&(s(e,t,1),m=e.getByte(),t--),0===m)try{a=e.length();var w=o(e,t,r+1,{strict:!0,decodeBitStrings:!0}),v=a-e.length();t-=v,l==i.Type.BITSTRING&&v++;var _=w.tagClass;v!==f||_!==i.Class.UNIVERSAL&&_!==i.Class.CONTEXT_SPECIFIC||(h=[w])}catch(S){}void 0===h&&(e.read=b,t=y)}if(void 0===h){if(void 0===f){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");f=t}if(l===i.Type.BMPSTRING)for(h="";f>0;f-=2)s(e,t,2),h+=String.fromCharCode(e.getInt16()),t-=2;else h=e.getBytes(f),t-=f}var E=void 0===d?null:{bitStringContents:d};return i.create(u,l,g,h,E)}i.fromDer=function(e,t){void 0===t&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"===typeof t&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.length(),i=o(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var s=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw s.byteCount=r,s.remaining=e.length(),s}return i},i.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,s=n.util.createBuffer(),o=!1;if("bitStringContents"in e&&(o=!0,e.original&&(o=i.equals(e,e.original))),o)s.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:s.putByte(0);for(var a=0;a1&&(0===e.value.charCodeAt(0)&&0===(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128===(128&e.value.charCodeAt(1)))?s.putBytes(e.value.substr(1)):s.putBytes(e.value);if(t.putByte(r),s.length()<=127)t.putByte(127&s.length());else{var c=s.length(),u="";do{u+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|u.length);for(a=u.length-1;a>=0;--a)t.putByte(u.charCodeAt(a))}return t.putBuffer(s),t},i.oidToDer=function(e){var t,r,i,s,o=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(o[0],10)+parseInt(o[1],10));for(var c=2;c>>=7,t||(s|=128),r.push(s),t=!1}while(i>0);for(var u=r.length-1;u>=0;--u)a.putByte(r[u])}return a},i.derToOid=function(e){var t;"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var i=0;e.length()>0;)i<<=7,128&(r=e.getByte())?i+=127&r:(t+="."+(i+r),i=0);return t},i.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),s=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),u=10;"+"!==c&&"-"!==c&&(a=parseInt(e.substr(10,2),10),u+=2)}if(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,0),u&&("+"===(c=e.charAt(u))||"-"===c)){var l=60*parseInt(e.substr(u+1,2),10)+parseInt(e.substr(u+4,2),10);l*=6e4,"+"===c?t.setTime(+t-l):t.setTime(+t+l)}return t},i.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;"Z"===e.charAt(e.length-1)&&(l=!0);var h=e.length-5,d=e.charAt(h);"+"!==d&&"-"!==d||(u=60*parseInt(e.substr(h+1,2),10)+parseInt(e.substr(h+4,2),10),u*=6e4,"+"===d&&(u*=-1),l=!0);return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),l?(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,c),t.setTime(+t+u)):(t.setFullYear(r,n,i),t.setHours(s,o,a,c)),t},i.dateToUtcTime=function(e){if("string"===typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},i.derToInteger=function(e){"string"===typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},i.validate=function(e,t,r,s){var o=!1;if(e.tagClass!==t.tagClass&&"undefined"!==typeof t.tagClass||e.type!==t.type&&"undefined"!==typeof t.type)s&&(e.tagClass!==t.tagClass&&s.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&s.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||"undefined"===typeof t.constructed){if(o=!0,t.value&&n.util.isArray(t.value))for(var a=0,c=0;o&&c0&&(s+="\n");for(var o="",c=0;c1?s+="0x"+n.util.bytesToHex(e.value.slice(1)):s+="(none)",e.value.length>0){var d=e.value.charCodeAt(0);1==d?s+=" (1 unused bit shown)":d>1&&(s+=" ("+d+" unused bits shown)")}}else if(e.type===i.Type.OCTETSTRING)a.test(e.value)||(s+="("+e.value+") "),s+="0x"+n.util.bytesToHex(e.value);else if(e.type===i.Type.UTF8)try{s+=n.util.decodeUtf8(e.value)}catch(p){if("URI malformed"!==p.message)throw p;s+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===i.Type.PRINTABLESTRING||e.type===i.Type.IA5String?s+=e.value:a.test(e.value)?s+="0x"+n.util.bytesToHex(e.value):0===e.value.length?s+="[null]":s+=e.value}return s}},6407:e=>{var t={};e.exports=t;var r={};t.encode=function(e,t,r){if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!==typeof r)throw new TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var i=0,s=t.length,o=t.charAt(0),a=[0];for(i=0;i0;)a.push(u%s),u=u/s|0}for(i=0;0===e[i]&&i=0;--i)n+=t[a[i]]}else n=function(e,t){var r=0,n=t.length,i=t.charAt(0),s=[0];for(r=0;r0;)s.push(a%n),a=a/n|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[s[r]];return c}(e,t);if(r){var l=new RegExp(".{1,"+r+"}","g");n=n.match(l).join("\r\n")}return n},t.decode=function(e,t){if("string"!==typeof e)throw new TypeError('"input" must be a string.');if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');var n=r[t];if(!n){n=r[t]=[];for(var i=0;i>=8;for(;l>0;)a.push(255&l),l>>=8}for(var h=0;e[h]===o&&h{var n=r(45);r(3900),e.exports=n.cipher=n.cipher||{},n.cipher.algorithms=n.cipher.algorithms||{},n.cipher.createCipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!1})},n.cipher.createDecipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!0})},n.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),n.cipher.algorithms[e]=t},n.cipher.getAlgorithm=function(e){return(e=e.toUpperCase())in n.cipher.algorithms?n.cipher.algorithms[e]:null};var i=n.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};i.prototype.start=function(e){e=e||{};var t={};for(var r in e)t[r]=e[r];t.decrypt=this._decrypt,this._finish=!1,this._input=n.util.createBuffer(),this.output=e.output||n.util.createBuffer(),this.mode.start(t)},i.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},i.prototype.finish=function(e){!e||"ECB"!==this.mode.name&&"CBC"!==this.mode.name||(this.mode.pad=function(t){return e(this.blockSize,t,!1)},this.mode.unpad=function(t){return e(this.blockSize,t,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t))&&(this._finish=!0,this.update(),!(this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))&&!(this.mode.afterFinish&&!this.mode.afterFinish(this.output,t)))}},1655:(e,t,r)=>{var n=r(45);r(3900),n.cipher=n.cipher||{};var i=e.exports=n.cipher.modes=n.cipher.modes||{};function s(e,t){if("string"===typeof e&&(e=n.util.createBuffer(e)),n.util.isArray(e)&&e.length>4){var r=e;e=n.util.createBuffer();for(var i=0;i0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},i.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},i.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb.prototype.decrypt=i.ofb.prototype.encrypt,i.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}o(this._inBlock)},i.ctr.prototype.decrypt=i.ctr.prototype.encrypt,i.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},i.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t,r=n.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?n.util.createBuffer(e.additionalData):n.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var i=r.length();if(12===i)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(a(8*i)))}this._inBlock=this._j0.slice(0),o(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var s=t.length()%this.blockSize;for(s&&t.fillWithByte(0,this.blockSize-s),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},i.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),o(this._inBlock)},i.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),o(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},i.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>4*(7-r%8)&15,i=this._m[r][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t},i.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},i.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,i=16*r,s=new Array(i),o=0;o>>1,i=new Array(r);i[n]=e.slice(0);for(var s=n>>>1;s>0;)this.pow(i[2*s],i[s]=[]),s>>=1;for(s=2;s{var n=r(45);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.des.Algorithm(e,t)}))}r(9151),r(1655),r(3900),e.exports=n.des=n.des||{},n.des.startEncrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createEncryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!1,mode:t})},n.des.startDecrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createDecryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!0,mode:t})},n.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return f(r._keys,e,t,!1)},decrypt:function(e,t){return f(r._keys,e,t,!0)}}}),r._init=!1},n.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=n.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw new Error("Invalid Triple-DES key size: "+8*t.length());this._keys=function(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],n=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],s=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],o=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],u=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],l=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],p=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],b=e.length()>8?3:1,y=[],m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],w=0,v=0;v>>4^E))<<4,_^=t=65535&((E^=t)>>>-16^_),_^=(t=858993459&(_>>>2^(E^=t<<-16)))<<2,_^=t=65535&((E^=t)>>>-16^_),_^=(t=1431655765&(_>>>1^(E^=t<<-16)))<<1,_^=t=16711935&((E^=t)>>>8^_),t=(_^=(t=1431655765&(_>>>1^(E^=t<<8)))<<1)<<8|(E^=t)>>>20&240,_=E<<24|E<<8&16711680|E>>>8&65280|E>>>24&240,E=t;for(var S=0;S>>26,E=E<<2|E>>>26):(_=_<<1|_>>>27,E=E<<1|E>>>27),E&=-15;var A=r[(_&=-15)>>>28]|n[_>>>24&15]|i[_>>>20&15]|s[_>>>16&15]|o[_>>>12&15]|a[_>>>8&15]|c[_>>>4&15],k=u[E>>>28]|l[E>>>24&15]|h[E>>>20&15]|d[E>>>16&15]|f[E>>>12&15]|p[E>>>8&15]|g[E>>>4&15];t=65535&(k>>>16^A),y[w++]=A^t,y[w++]=k^t<<16}}return y}(t),this._init=!0}},i("DES-ECB",n.cipher.modes.ecb),i("DES-CBC",n.cipher.modes.cbc),i("DES-CFB",n.cipher.modes.cfb),i("DES-OFB",n.cipher.modes.ofb),i("DES-CTR",n.cipher.modes.ctr),i("3DES-ECB",n.cipher.modes.ecb),i("3DES-CBC",n.cipher.modes.cbc),i("3DES-CFB",n.cipher.modes.cfb),i("3DES-OFB",n.cipher.modes.ofb),i("3DES-CTR",n.cipher.modes.ctr);var s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],a=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],c=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],u=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],h=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],d=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function f(e,t,r,n){var i,f,p=32===e.length?3:9;i=3===p?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],b=t[1];g^=(f=252645135&(g>>>4^b))<<4,g^=(f=65535&(g>>>16^(b^=f)))<<16,g^=f=858993459&((b^=f)>>>2^g),g^=f=16711935&((b^=f<<2)>>>8^g),g=(g^=(f=1431655765&(g>>>1^(b^=f<<8)))<<1)<<1|g>>>31,b=(b^=f)<<1|b>>>31;for(var y=0;y>>4|b<<28)^e[v+1];f=g,g=b,b=f^(o[_>>>24&63]|c[_>>>16&63]|l[_>>>8&63]|d[63&_]|s[E>>>24&63]|a[E>>>16&63]|u[E>>>8&63]|h[63&E])}f=g,g=b,b=f}b=b>>>1|b<<31,b^=f=1431655765&((g=g>>>1|g<<31)>>>1^b),b^=(f=16711935&(b>>>8^(g^=f<<1)))<<8,b^=(f=858993459&(b>>>2^(g^=f)))<<2,b^=f=65535&((g^=f)>>>16^b),b^=f=252645135&((g^=f<<16)>>>4^b),g^=f<<4,r[0]=g,r[1]=b}function p(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var s=null;r instanceof n.util.ByteBuffer&&(s=r,r={}),(r=r||{}).output=s,r.iv=e,i.call(t,r)},t}},45:e=>{e.exports={options:{usePureJavaScript:!1}}},8163:(e,t,r)=>{var n=r(45);r(5693),r(3900),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,i=null,s={start:function(s,o){if(null!==s)if("string"===typeof s){if(!((s=s.toLowerCase())in n.md.algorithms))throw new Error('Unknown hash algorithm "'+s+'"');t=n.md.algorithms[s].create()}else t=s;if(null===o)o=e;else{if("string"===typeof o)o=n.util.createBuffer(o);else if(n.util.isArray(o)){var a=o;o=n.util.createBuffer();for(var c=0;ct.blockLength&&(t.start(),t.update(o.bytes()),o=t.digest()),r=n.util.createBuffer(),i=n.util.createBuffer(),u=o.length();for(c=0;c{var n,i=r(45);e.exports=i.jsbn=i.jsbn||{};function s(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function o(){return new s(null)}function a(e,t,r,n,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this.data[e],u=this.data[e++]>>14,l=a*c+u*o;i=((c=o*c+((16383&l)<<14)+r.data[n]+i)>>28)+(l>>14)+a*u,r.data[n++]=268435455&c}return i}i.jsbn.BigInteger=s,"undefined"===typeof navigator?(s.prototype.am=a,n=28):"Microsoft Internet Explorer"==navigator.appName?(s.prototype.am=function(e,t,r,n,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this.data[e],u=this.data[e++]>>15,l=a*c+u*o;i=((c=o*c+((32767&l)<<15)+r.data[n]+(1073741823&i))>>>30)+(l>>>15)+a*u+(i>>>30),r.data[n++]=1073741823&c}return i},n=30):"Netscape"!=navigator.appName?(s.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this.data[e++]+r.data[n]+i;i=Math.floor(o/67108864),r.data[n++]=67108863&o}return i},n=26):(s.prototype.am=a,n=28),s.prototype.DB=n,s.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function b(e){this.m=e}function y(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function S(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function A(){}function k(e){return e}function x(e){this.r2=o(),this.q3=o(),s.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}b.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},b.prototype.revert=function(e){return e},b.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},b.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},b.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},y.prototype.convert=function(e){var t=o();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(s.ZERO)>0&&this.m.subTo(t,t),t},y.prototype.revert=function(e){var t=o();return e.copyTo(t),this.reduce(t),t},y.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},s.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},s.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},s.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,o=0;--n>=0;){var a=8==r?255&e[n]:f(e,n);a<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==o?this.data[this.t++]=a:o+r>this.DB?(this.data[this.t-1]|=(a&(1<>this.DB-o):this.data[this.t-1]|=a<=this.DB&&(o-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},s.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},s.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+o+1]=this.data[r]>>i|a,a=(this.data[r]&s)<=0;--r)t.data[r]=0;t.data[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},s.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,s=(1<>n;for(var o=r+1;o>n;n>0&&(t.data[this.t-r-1]|=(this.s&s)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()},s.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t.data[i]=0;for(i=0;i=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},s.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(l,a),i.lShiftTo(l,r)):(n.copyTo(a),i.copyTo(r));var h=a.t,d=a.data[h-1];if(0!=d){var f=d*(1<1?a.data[h-2]>>this.F2:0),p=this.FV/f,b=(1<=0&&(r.data[r.t++]=1,r.subTo(v,r)),s.ONE.dlShiftTo(h,v),v.subTo(a,a);a.t=0;){var _=r.data[--m]==d?this.DM:Math.floor(r.data[m]*p+(r.data[m-1]+y)*b);if((r.data[m]+=a.am(0,_,r,w,0,h))<_)for(a.dlShiftTo(w,v),r.subTo(v,r);r.data[m]<--_;)r.subTo(v,r)}null!=t&&(r.drShiftTo(h,t),c!=u&&s.ZERO.subTo(t,t)),r.t=h,r.clamp(),l>0&&r.rShiftTo(l,r),c<0&&s.ZERO.subTo(r,r)}}},s.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},s.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},s.prototype.exp=function(e,t){if(e>4294967295||e<1)return s.ONE;var r=o(),n=o(),i=t.convert(this),a=g(e)-1;for(i.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var c=r;r=n,n=c}return t.revert(r)},s.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,s=d(r));o>=0;)a>(a+=this.DB-t)):(r=this.data[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(i=!0),i&&(s+=d(r));return i?s:"0"},s.prototype.negate=function(){var e=o();return s.ZERO.subTo(this,e),e},s.prototype.abs=function(){return this.s<0?this.negate():this},s.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},s.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+g(this.data[this.t-1]^this.s&this.DM)},s.prototype.mod=function(e){var t=o();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(s.ZERO)>0&&e.subTo(t,t),t},s.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new b(t):new y(t),this.exp(e,r)},s.ZERO=p(0),s.ONE=p(1),A.prototype.convert=k,A.prototype.revert=k,A.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},A.prototype.sqrTo=function(e,t){e.squareTo(t)},x.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=o();return e.copyTo(t),this.reduce(t),t},x.prototype.revert=function(e){return e},x.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},x.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},x.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var I=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],C=(1<<26)/I[I.length-1];s.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},s.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=p(r),i=o(),s=o(),a="";for(this.divRemTo(n,i,s);i.signum()>0;)a=(r+s.intValue()).toString(e).substr(1)+a,i.divRemTo(n,i,s);return s.intValue().toString(e)+a},s.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,o=0,a=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(a,0)),i&&s.ZERO.subTo(this,this)},s.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(s.ONE.shiftLeft(e-1),w,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(s.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()},s.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},s.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},s.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r.data[--i]=0;for(n=r.t-this.t;i=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n0)if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r},s.prototype.millerRabin=function(e){var t=this.subtract(s.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n,i=t.shiftRight(r),o={nextBytes:function(e){for(var t=0;t=0);var c=n.modPow(i,this);if(0!=c.compareTo(s.ONE)&&0!=c.compareTo(t)){for(var u=1;u++>24},s.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},s.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},s.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},s.prototype.equals=function(e){return 0==this.compareTo(e)},s.prototype.min=function(e){return this.compareTo(e)<0?this:e},s.prototype.max=function(e){return this.compareTo(e)>0?this:e},s.prototype.and=function(e){var t=o();return this.bitwiseTo(e,m,t),t},s.prototype.or=function(e){var t=o();return this.bitwiseTo(e,w,t),t},s.prototype.xor=function(e){var t=o();return this.bitwiseTo(e,v,t),t},s.prototype.andNot=function(e){var t=o();return this.bitwiseTo(e,_,t),t},s.prototype.not=function(){for(var e=o(),t=0;t=this.t?0!=this.s:0!=(this.data[t]&1<1){var h=o();for(n.sqrTo(a[1],h);c<=l;)a[c]=o(),n.mulTo(h,a[c-2],a[c]),c+=2}var d,f,m=e.t-1,w=!0,v=o();for(i=g(e.data[m])-1;m>=0;){for(i>=u?d=e.data[m]>>i-u&l:(d=(e.data[m]&(1<0&&(d|=e.data[m-1]>>this.DB+i-u)),c=r;0==(1&d);)d>>=1,--c;if((i-=c)<0&&(i+=this.DB,--m),w)a[d].copyTo(s),w=!1;else{for(;c>1;)n.sqrTo(s,v),n.sqrTo(v,s),c-=2;c>0?n.sqrTo(s,v):(f=s,s=v,v=f),n.mulTo(v,a[d],s)}for(;m>=0&&0==(e.data[m]&1<=0?(r.subTo(n,r),t&&i.subTo(a,i),o.subTo(c,o)):(n.subTo(r,n),t&&a.subTo(i,a),c.subTo(o,c))}return 0!=n.compareTo(s.ONE)?s.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},s.prototype.pow=function(e){return this.exp(e,new A)},s.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(i0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},s.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=I[I.length-1]){for(t=0;t{var n=r(45);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},3225:(e,t,r)=>{var n=r(45);n.pki=n.pki||{};var i=e.exports=n.pki.oids=n.oids=n.oids||{};function s(e,t){i[e]=t,i[t]=e}function o(e,t){i[e]=t}s("1.2.840.113549.1.1.1","rsaEncryption"),s("1.2.840.113549.1.1.4","md5WithRSAEncryption"),s("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),s("1.2.840.113549.1.1.7","RSAES-OAEP"),s("1.2.840.113549.1.1.8","mgf1"),s("1.2.840.113549.1.1.9","pSpecified"),s("1.2.840.113549.1.1.10","RSASSA-PSS"),s("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),s("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),s("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),s("1.3.101.112","EdDSA25519"),s("1.2.840.10040.4.3","dsa-with-sha1"),s("1.3.14.3.2.7","desCBC"),s("1.3.14.3.2.26","sha1"),s("1.3.14.3.2.29","sha1WithRSASignature"),s("2.16.840.1.101.3.4.2.1","sha256"),s("2.16.840.1.101.3.4.2.2","sha384"),s("2.16.840.1.101.3.4.2.3","sha512"),s("2.16.840.1.101.3.4.2.4","sha224"),s("2.16.840.1.101.3.4.2.5","sha512-224"),s("2.16.840.1.101.3.4.2.6","sha512-256"),s("1.2.840.113549.2.2","md2"),s("1.2.840.113549.2.5","md5"),s("1.2.840.113549.1.7.1","data"),s("1.2.840.113549.1.7.2","signedData"),s("1.2.840.113549.1.7.3","envelopedData"),s("1.2.840.113549.1.7.4","signedAndEnvelopedData"),s("1.2.840.113549.1.7.5","digestedData"),s("1.2.840.113549.1.7.6","encryptedData"),s("1.2.840.113549.1.9.1","emailAddress"),s("1.2.840.113549.1.9.2","unstructuredName"),s("1.2.840.113549.1.9.3","contentType"),s("1.2.840.113549.1.9.4","messageDigest"),s("1.2.840.113549.1.9.5","signingTime"),s("1.2.840.113549.1.9.6","counterSignature"),s("1.2.840.113549.1.9.7","challengePassword"),s("1.2.840.113549.1.9.8","unstructuredAddress"),s("1.2.840.113549.1.9.14","extensionRequest"),s("1.2.840.113549.1.9.20","friendlyName"),s("1.2.840.113549.1.9.21","localKeyId"),s("1.2.840.113549.1.9.22.1","x509Certificate"),s("1.2.840.113549.1.12.10.1.1","keyBag"),s("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),s("1.2.840.113549.1.12.10.1.3","certBag"),s("1.2.840.113549.1.12.10.1.4","crlBag"),s("1.2.840.113549.1.12.10.1.5","secretBag"),s("1.2.840.113549.1.12.10.1.6","safeContentsBag"),s("1.2.840.113549.1.5.13","pkcs5PBES2"),s("1.2.840.113549.1.5.12","pkcs5PBKDF2"),s("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),s("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),s("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),s("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),s("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),s("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),s("1.2.840.113549.2.7","hmacWithSHA1"),s("1.2.840.113549.2.8","hmacWithSHA224"),s("1.2.840.113549.2.9","hmacWithSHA256"),s("1.2.840.113549.2.10","hmacWithSHA384"),s("1.2.840.113549.2.11","hmacWithSHA512"),s("1.2.840.113549.3.7","des-EDE3-CBC"),s("2.16.840.1.101.3.4.1.2","aes128-CBC"),s("2.16.840.1.101.3.4.1.22","aes192-CBC"),s("2.16.840.1.101.3.4.1.42","aes256-CBC"),s("2.5.4.3","commonName"),s("2.5.4.4","surname"),s("2.5.4.5","serialNumber"),s("2.5.4.6","countryName"),s("2.5.4.7","localityName"),s("2.5.4.8","stateOrProvinceName"),s("2.5.4.9","streetAddress"),s("2.5.4.10","organizationName"),s("2.5.4.11","organizationalUnitName"),s("2.5.4.12","title"),s("2.5.4.13","description"),s("2.5.4.15","businessCategory"),s("2.5.4.17","postalCode"),s("2.5.4.42","givenName"),s("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),s("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),s("2.16.840.1.113730.1.1","nsCertType"),s("2.16.840.1.113730.1.13","nsComment"),o("2.5.29.1","authorityKeyIdentifier"),o("2.5.29.2","keyAttributes"),o("2.5.29.3","certificatePolicies"),o("2.5.29.4","keyUsageRestriction"),o("2.5.29.5","policyMapping"),o("2.5.29.6","subtreesConstraint"),o("2.5.29.7","subjectAltName"),o("2.5.29.8","issuerAltName"),o("2.5.29.9","subjectDirectoryAttributes"),o("2.5.29.10","basicConstraints"),o("2.5.29.11","nameConstraints"),o("2.5.29.12","policyConstraints"),o("2.5.29.13","basicConstraints"),s("2.5.29.14","subjectKeyIdentifier"),s("2.5.29.15","keyUsage"),o("2.5.29.16","privateKeyUsagePeriod"),s("2.5.29.17","subjectAltName"),s("2.5.29.18","issuerAltName"),s("2.5.29.19","basicConstraints"),o("2.5.29.20","cRLNumber"),o("2.5.29.21","cRLReason"),o("2.5.29.22","expirationDate"),o("2.5.29.23","instructionCode"),o("2.5.29.24","invalidityDate"),o("2.5.29.25","cRLDistributionPoints"),o("2.5.29.26","issuingDistributionPoint"),o("2.5.29.27","deltaCRLIndicator"),o("2.5.29.28","issuingDistributionPoint"),o("2.5.29.29","certificateIssuer"),o("2.5.29.30","nameConstraints"),s("2.5.29.31","cRLDistributionPoints"),s("2.5.29.32","certificatePolicies"),o("2.5.29.33","policyMappings"),o("2.5.29.34","policyConstraints"),s("2.5.29.35","authorityKeyIdentifier"),o("2.5.29.36","policyConstraints"),s("2.5.29.37","extKeyUsage"),o("2.5.29.46","freshestCRL"),o("2.5.29.54","inhibitAnyPolicy"),s("1.3.6.1.4.1.11129.2.4.2","timestampList"),s("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),s("1.3.6.1.5.5.7.3.1","serverAuth"),s("1.3.6.1.5.5.7.3.2","clientAuth"),s("1.3.6.1.5.5.7.3.3","codeSigning"),s("1.3.6.1.5.5.7.3.4","emailProtection"),s("1.3.6.1.5.5.7.3.8","timeStamping")},3555:(e,t,r)=>{var n=r(45);if(r(9353),r(5465),r(2986),r(5693),r(3225),r(8009),r(5224),r(2795),r(1577),r(9408),r(3900),"undefined"===typeof i)var i=n.jsbn.BigInteger;var s=n.asn1,o=n.pki=n.pki||{};e.exports=o.pbe=n.pbe=n.pbe||{};var a=o.oids,c={name:"EncryptedPrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},u={name:"PBES2Algorithms",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},l={name:"pkcs-12PbeParams",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"iterations"}]};function h(e,t){return e.start().update(t).digest().getBytes()}function d(e){var t;if(e){if(!(t=o.oids[s.derToOid(e)])){var r=new Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}}else t="hmacWithSHA1";return f(t)}function f(e){var t=n.md;switch(e){case"hmacWithSHA224":t=n.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}o.encryptPrivateKeyInfo=function(e,t,r){(r=r||{}).saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var i,c,u,l=n.random.getBytesSync(r.saltSize),h=r.count,d=s.integerToDer(h);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){var p,g,b;switch(r.algorithm){case"aes128":i=16,p=16,g=a["aes128-CBC"],b=n.aes.createEncryptionCipher;break;case"aes192":i=24,p=16,g=a["aes192-CBC"],b=n.aes.createEncryptionCipher;break;case"aes256":i=32,p=16,g=a["aes256-CBC"],b=n.aes.createEncryptionCipher;break;case"des":i=8,p=8,g=a.desCBC,b=n.des.createEncryptionCipher;break;default:throw(E=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,E}var y="hmacWith"+r.prfAlgorithm.toUpperCase(),m=f(y),w=n.pkcs5.pbkdf2(t,l,h,i,m),v=n.random.getBytesSync(p);(S=b(w)).start(v),S.update(s.toDer(e)),S.finish(),u=S.output.getBytes();var _=function(e,t,r,i){var a=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,e),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,t.getBytes())]);"hmacWithSHA1"!==i&&a.value.push(s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,n.util.hexToBytes(r.toString(16))),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(o.oids[i]).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]));return a}(l,d,i,y);c=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a.pkcs5PBES2).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a.pkcs5PBKDF2).getBytes()),_]),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(g).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,v)])])])}else{var E;if("3des"!==r.algorithm)throw(E=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,E;i=24;var S,A=new n.util.ByteBuffer(l);w=o.pbe.generatePkcs12Key(t,A,1,h,i),v=o.pbe.generatePkcs12Key(t,A,2,h,i);(S=n.des.createEncryptionCipher(w)).start(v),S.update(s.toDer(e)),S.finish(),u=S.output.getBytes(),c=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,l),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,d.getBytes())])])}return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[c,s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,u)])},o.decryptPrivateKeyInfo=function(e,t){var r=null,i={},a=[];if(!s.validate(e,c,i,a)){var u=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw u.errors=a,u}var l=s.derToOid(i.encryptionOid),h=o.pbe.getCipher(l,i.encryptionParams,t),d=n.util.createBuffer(i.encryptedData);return h.update(d),h.finish()&&(r=s.fromDer(h.output)),r},o.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:s.toDer(e).getBytes()};return n.pem.encode(r,{maxline:t})},o.encryptedPrivateKeyFromPem=function(e){var t=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==t.type){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return s.fromDer(t.body)},o.encryptRsaPrivateKey=function(e,t,r){if(!(r=r||{}).legacy){var i=o.wrapRsaPrivateKey(o.privateKeyToAsn1(e));return i=o.encryptPrivateKeyInfo(i,t,r),o.encryptedPrivateKeyToPem(i)}var a,c,u,l;switch(r.algorithm){case"aes128":a="AES-128-CBC",u=16,c=n.random.getBytesSync(16),l=n.aes.createEncryptionCipher;break;case"aes192":a="AES-192-CBC",u=24,c=n.random.getBytesSync(16),l=n.aes.createEncryptionCipher;break;case"aes256":a="AES-256-CBC",u=32,c=n.random.getBytesSync(16),l=n.aes.createEncryptionCipher;break;case"3des":a="DES-EDE3-CBC",u=24,c=n.random.getBytesSync(8),l=n.des.createEncryptionCipher;break;case"des":a="DES-CBC",u=8,c=n.random.getBytesSync(8),l=n.des.createEncryptionCipher;break;default:var h=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw h.algorithm=r.algorithm,h}var d=l(n.pbe.opensslDeriveBytes(t,c.substr(0,8),u));d.start(c),d.update(s.toDer(o.privateKeyToAsn1(e))),d.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:a,parameters:n.util.bytesToHex(c).toUpperCase()},body:d.output.getBytes()};return n.pem.encode(f)},o.decryptRsaPrivateKey=function(e,t){var r=null,i=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==i.type&&"PRIVATE KEY"!==i.type&&"RSA PRIVATE KEY"!==i.type)throw(u=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=u,u;if(i.procType&&"ENCRYPTED"===i.procType.type){var a,c;switch(i.dekInfo.algorithm){case"DES-CBC":a=8,c=n.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,c=n.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,c=n.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,c=n.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,c=n.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,c=function(e){return n.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":a=8,c=function(e){return n.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":a=16,c=function(e){return n.rc2.createDecryptionCipher(e,128)};break;default:var u;throw(u=new Error('Could not decrypt private key; unsupported encryption algorithm "'+i.dekInfo.algorithm+'".')).algorithm=i.dekInfo.algorithm,u}var l=n.util.hexToBytes(i.dekInfo.parameters),h=c(n.pbe.opensslDeriveBytes(t,l.substr(0,8),a));if(h.start(l),h.update(n.util.createBuffer(i.body)),!h.finish())return r;r=h.output.getBytes()}else r=i.body;return null!==(r="ENCRYPTED PRIVATE KEY"===i.type?o.decryptPrivateKeyInfo(s.fromDer(r),t):s.fromDer(r))&&(r=o.privateKeyFromAsn1(r)),r},o.pbe.generatePkcs12Key=function(e,t,r,i,s,o){var a,c;if("undefined"===typeof o||null===o){if(!("sha1"in n.md))throw new Error('"sha1" hash algorithm unavailable.');o=n.md.sha1.create()}var u=o.digestLength,l=o.blockLength,h=new n.util.ByteBuffer,d=new n.util.ByteBuffer;if(null!==e&&void 0!==e){for(c=0;c=0;c--)T>>=8,T+=k.at(c)+C.at(c),C.setAt(c,255&T);I.putBuffer(C)}v=I,h.putBuffer(S)}return h.truncate(h.length()-s),h},o.pbe.getCipher=function(e,t,r){switch(e){case o.oids.pkcs5PBES2:return o.pbe.getCipherForPBES2(e,t,r);case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case o.oids["pbewithSHAAnd40BitRC2-CBC"]:return o.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},o.pbe.getCipherForPBES2=function(e,t,r){var i,a={},c=[];if(!s.validate(t,u,a,c))throw(i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,i;if((e=s.derToOid(a.kdfOid))!==o.oids.pkcs5PBKDF2)throw(i=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,i.supportedOids=["pkcs5PBKDF2"],i;if((e=s.derToOid(a.encOid))!==o.oids["aes128-CBC"]&&e!==o.oids["aes192-CBC"]&&e!==o.oids["aes256-CBC"]&&e!==o.oids["des-EDE3-CBC"]&&e!==o.oids.desCBC)throw(i=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,i.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],i;var l,h,f=a.kdfSalt,p=n.util.createBuffer(a.kdfIterationCount);switch(p=p.getInt(p.length()<<3),o.oids[e]){case"aes128-CBC":l=16,h=n.aes.createDecryptionCipher;break;case"aes192-CBC":l=24,h=n.aes.createDecryptionCipher;break;case"aes256-CBC":l=32,h=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":l=24,h=n.des.createDecryptionCipher;break;case"desCBC":l=8,h=n.des.createDecryptionCipher}var g=d(a.prfOid),b=n.pkcs5.pbkdf2(r,f,p,l,g),y=a.encIv,m=h(b);return m.start(y),m},o.pbe.getCipherForPKCS12PBE=function(e,t,r){var i={},a=[];if(!s.validate(t,l,i,a))throw(g=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=a,g;var c,u,h,f=n.util.createBuffer(i.salt),p=n.util.createBuffer(i.iterations);switch(p=p.getInt(p.length()<<3),e){case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,h=n.des.startDecrypting;break;case o.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,h=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var g;throw(g=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,g}var b=d(i.prfOid),y=o.pbe.generatePkcs12Key(r,f,1,p,c,b);return b.start(),h(y,o.pbe.generatePkcs12Key(r,f,2,p,u,b))},o.pbe.opensslDeriveBytes=function(e,t,r,i){if("undefined"===typeof i||null===i){if(!("md5"in n.md))throw new Error('"md5" hash algorithm unavailable.');i=n.md.md5.create()}null===t&&(t="");for(var s=[h(i,e+t)],o=16,a=1;o{var n=r(45);r(8163),r(5693),r(3900);var i,s=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(i=r(310)),e.exports=n.pbkdf2=s.pbkdf2=function(e,t,r,s,o,a){if("function"===typeof o&&(a=o,o=null),n.util.isNodejs&&!n.options.usePureJavaScript&&i.pbkdf2&&(null===o||"object"!==typeof o)&&(i.pbkdf2Sync.length>4||!o||"sha1"===o))return"string"!==typeof o&&(o="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),a?4===i.pbkdf2Sync.length?i.pbkdf2(e,t,r,s,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):i.pbkdf2(e,t,r,s,o,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):4===i.pbkdf2Sync.length?i.pbkdf2Sync(e,t,r,s).toString("binary"):i.pbkdf2Sync(e,t,r,s,o).toString("binary");if("undefined"!==typeof o&&null!==o||(o="sha1"),"string"===typeof o){if(!(o in n.md.algorithms))throw new Error("Unknown hash algorithm: "+o);o=n.md[o].create()}var c=o.digestLength;if(s>4294967295*c){var u=new Error("Derived key is too long.");if(a)return a(u);throw u}var l=Math.ceil(s/c),h=s-(l-1)*c,d=n.hmac.create();d.start(o,e);var f,p,g,b="";if(!a){for(var y=1;y<=l;++y){d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(y)),f=g=d.digest().getBytes();for(var m=2;m<=r;++m)d.start(null,null),d.update(g),p=d.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p;b+=yl)return a(null,b);d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(y)),f=g=d.digest().getBytes(),m=2,v()}function v(){if(m<=r)return d.start(null,null),d.update(g),p=d.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p,++m,n.util.setImmediate(v);b+=y{var n=r(45);r(3900);var i=e.exports=n.pem=n.pem||{};function s(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},i=0;i65&&-1!==o){var a=t[o];","===a?(++o,t=t.substr(0,o)+"\r\n "+t.substr(o)):t=t.substr(0,o)+"\r\n"+a+t.substr(o+1),s=i-o-1,o=-1,++i}else" "!==t[i]&&"\t"!==t[i]&&","!==t[i]||(o=i);return t}function o(e){return e.replace(/^\s+/,"")}i.encode=function(e,t){t=t||{};var r,i="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(i+=s(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(i+=s(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),i+=s(r)),e.headers)for(var o=0;o{var n=r(45);r(3900),r(2795),r(3753);var i=e.exports=n.pkcs1=n.pkcs1||{};function s(e,t,r){r||(r=n.md.sha1.create());for(var i="",s=Math.ceil(t/r.digestLength),o=0;o>24&255,o>>16&255,o>>8&255,255&o);r.start(),r.update(e+a),i+=r.digest().getBytes()}return i.substring(0,t)}i.encode_rsa_oaep=function(e,t,r){var i,o,a,c;"string"===typeof r?(i=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(i=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),c||(c=a);var u=Math.ceil(e.n.bitLength()/8),l=u-2*a.digestLength-2;if(t.length>l)throw(b=new Error("RSAES-OAEP input message length is too long.")).length=t.length,b.maxLength=l,b;i||(i=""),a.update(i,"raw");for(var h=a.digest(),d="",f=l-t.length,p=0;p{var n=r(45);r(3900),r(9463),r(2795),function(){if(n.prime)e.exports=n.prime;else{var t=e.exports=n.prime=n.prime||{},r=n.jsbn.BigInteger,i=[6,4,2,4,2,4,6,2],s=new r(null);s.fromInt(30);var o=function(e,t){return e|t};t.generateProbablePrime=function(e,t,i){"function"===typeof t&&(i=t,t={});var s=(t=t||{}).algorithm||"PRIMEINC";"string"===typeof s&&(s={name:s}),s.options=s.options||{};var o=t.prng||n.random,c={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;re&&(o=u(e,t));var f=o.toString(16);i.target.postMessage({hex:f,workLoad:l}),o.dAddOffset(h,0)}}}f()}(e,t,i,s);return a(e,t,i,s)}(e,c,s.options,i);throw new Error("Invalid prime generation algorithm: "+s.name)}}function a(e,t,r,n){var i=u(e,t),s=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(i.bitLength());"millerRabinTests"in r&&(s=r.millerRabinTests);var o=10;"maxBlockTime"in r&&(o=r.maxBlockTime),c(i,e,t,0,s,o,n)}function c(e,t,r,s,o,a,l){var h=+new Date;do{if(e.bitLength()>t&&(e=u(t,r)),e.isProbablePrime(o))return l(null,e);e.dAddOffset(i[s++%8],0)}while(a<0||+new Date-h{var n=r(45);r(3900);var i=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(i=r(310)),(e.exports=n.prng=n.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,s=new Array(32),o=0;o<32;++o)s[o]=r.create();function a(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,n=0;n<32;++n)t.reseeds%r===0&&(e.update(t.pools[n].digest().getBytes()),t.pools[n].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var i=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(i),t.generated=0}function u(e){var t=null,r=n.util.globalScope,i=r.crypto||r.msCrypto;i&&i.getRandomValues&&(t=function(e){return i.getRandomValues(e)});var s=n.util.createBuffer();if(t)for(;s.length()>16)))<<16,d=4294967295&(l=(2147483647&(l+=u>>15))+(l>>31));for(c=0;c<3;++c)h=d>>>(c<<3),h^=Math.floor(256*Math.random()),s.putByte(255&h)}return s.getBytes(e)}return t.pools=s,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var i=t.plugin.cipher,s=t.plugin.increment,o=t.plugin.formatKey,a=t.plugin.formatSeed,u=n.util.createBuffer();t.key=null,function l(h){if(h)return r(h);if(u.length()>=e)return r(null,u.getBytes(e));t.generated>1048575&&(t.key=null);if(null===t.key)return n.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,n){if(r)return e(r);t.collect(n),c(),e()}))}(l)}));var d=i(t.key,t.seed);t.generated+=d.length,u.putBytes(d),t.key=o(i(t.key,s(t.seed))),t.seed=a(i(t.key,t.seed)),n.util.setImmediate(l)}()},t.generateSync=function(e){var r=t.plugin.cipher,i=t.plugin.increment,s=t.plugin.formatKey,o=t.plugin.formatSeed;t.key=null;for(var c=n.util.createBuffer();c.length()1048575&&(t.key=null),null===t.key&&a();var u=r(t.key,t.seed);t.generated+=u.length,c.putBytes(u),t.key=s(r(t.key,i(t.seed))),t.seed=o(r(t.key,t.seed))}return c.getBytes(e)},i?(t.seedFile=function(e,t){i.randomBytes(e,(function(e,r){if(e)return t(e);t(null,r.toString())}))},t.seedFileSync=function(e){return i.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,u(e))}catch(r){t(r)}},t.seedFileSync=u),t.collect=function(e){for(var r=e.length,n=0;n>i&255);t.collect(n)},t.registerWorker=function(e){if(e===self)t.seedFile=function(e,t){self.addEventListener("message",(function e(r){var n=r.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",e),t(n.forge.prng.err,n.forge.prng.bytes))})),self.postMessage({forge:{prng:{needed:e}}})};else{e.addEventListener("message",(function(r){var n=r.data;n.forge&&n.forge.prng&&t.seedFile(n.forge.prng.needed,(function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})}))}))}},t}},2795:(e,t,r)=>{var n=r(45);r(9353),r(3899),r(1513),r(3900),n.random&&n.random.getBytes?e.exports=n.random:function(t){var r={},i=new Array(4),s=n.util.createBuffer();function o(){var e=n.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),n.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return n.aes._updateBlock(e,t,i,!1),s.putInt32(i[0]),s.putInt32(i[1]),s.putInt32(i[2]),s.putInt32(i[3]),s.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=o(),c=null,u=n.util.globalScope,l=u.crypto||u.msCrypto;if(l&&l.getRandomValues&&(c=function(e){return l.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!c){if("undefined"===typeof window||window.document,a.collectInt(+new Date,32),"undefined"!==typeof navigator){var h="";for(var d in navigator)try{"string"==typeof navigator[d]&&(h+=navigator[d])}catch(f){}a.collect(h),h=null}t&&(t().mousemove((function(e){a.collectInt(e.clientX,16),a.collectInt(e.clientY,16)})),t().keypress((function(e){a.collectInt(e.charCode,8)})))}if(n.random)for(var d in a)n.random[d]=a[d];else n.random=a;n.random.createInstance=o,e.exports=n.random}("undefined"!==typeof jQuery?jQuery:null)},1577:(e,t,r)=>{var n=r(45);r(3900);var i=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],s=[1,2,3,5],o=function(e,t){return e<>16-t},a=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"===typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,s=e,o=e.length(),a=t,c=Math.ceil(a/8),u=255>>(7&a);for(r=o;r<128;r++)s.putByte(i[s.at(r-1)+s.at(r-o)&255]);for(s.setAt(128-c,i[s.at(128-c)&u]),r=127-c;r>=0;r--)s.setAt(r,i[s.at(r+1)^s.at(r+c)]);return s};var c=function(e,t,r){var i,c,u,l,h=!1,d=null,f=null,p=null,g=[];for(e=n.rc2.expandKey(e,t),u=0;u<64;u++)g.push(e.getInt16Le());r?(i=function(e){for(u=0;u<4;u++)e[u]+=g[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),e[u]=o(e[u],s[u]),l++},c=function(e){for(u=0;u<4;u++)e[u]+=g[63&e[(u+3)%4]]}):(i=function(e){for(u=3;u>=0;u--)e[u]=a(e[u],s[u]),e[u]-=g[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),l--},c=function(e){for(u=3;u>=0;u--)e[u]-=g[63&e[(u+3)%4]]});var b=function(e){var t=[];for(u=0;u<4;u++){var n=d.getInt16Le();null!==p&&(r?n^=p.getInt16Le():p.putInt16Le(n)),t.push(65535&n)}l=r?0:63;for(var i=0;i=8;)b([[5,i],[1,c],[6,i],[1,c],[5,i]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,d,!r);else{var n=8===d.length()?8:8-d.length();d.fillWithByte(n,n)}if(t&&(h=!0,y.update()),!r&&(t=0===d.length()))if(e)t=e(8,f,!r);else{var i=f.length(),s=f.at(i-1);s>i?t=!1:f.truncate(s)}return t}}};n.rc2.startEncrypting=function(e,t,r){var i=n.rc2.createEncryptionCipher(e,128);return i.start(t,r),i},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var i=n.rc2.createDecryptionCipher(e,128);return i.start(t,r),i},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},9408:(e,t,r)=>{var n=r(45);if(r(5465),r(9463),r(3225),r(7668),r(8353),r(2795),r(3900),"undefined"===typeof i)var i=n.jsbn.BigInteger;var s=n.util.isNodejs?r(310):null,o=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var c=n.pki,u=[6,4,2,4,2,4,6,2],l={name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},h={name:"RSAPrivateKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},d={name:"RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},f=n.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},p={name:"DigestInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:o.Class.UNIVERSAL,type:o.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},g=function(e){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var n=o.oidToDer(t).getBytes(),i=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]),s=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]);s.value.push(o.create(o.Class.UNIVERSAL,o.Type.OID,!1,n)),s.value.push(o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,""));var a=o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(s),i.value.push(a),o.toDer(i).getBytes()},b=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var s;t.dP||(t.dP=t.d.mod(t.p.subtract(i.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(i.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{s=new i(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16)}while(s.compareTo(t.n)>=0||!s.gcd(t.n).equals(i.ONE));for(var o=(e=e.multiply(s.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);o.compareTo(a)<0;)o=o.add(t.p);var c=o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return c=c.multiply(s.modInverse(t.n)).mod(t.n)};function y(e,t,r){var i=n.util.createBuffer(),s=Math.ceil(t.n.bitLength()/8);if(e.length>s-11){var o=new Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=e.length,o.max=s-11,o}i.putByte(0),i.putByte(r);var a,c=s-3-e.length;if(0===r||1===r){a=0===r?0:255;for(var u=0;u0;){var l=0,h=n.random.getBytes(c);for(u=0;u1;){if(255!==o.getByte()){--o.read;break}++u}else if(2===c)for(u=0;o.length()>1;){if(0===o.getByte()){--o.read;break}++u}if(0!==o.getByte()||u!==s-3-o.length())throw new Error("Encryption block is invalid.");return o.getBytes()}function w(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=n.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&0===(128&r.charCodeAt(1))||255===r.charCodeAt(0)&&128===(128&r.charCodeAt(1)))?r.substr(1):r}function v(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function _(e){return n.util.isNodejs&&"function"===typeof s[e]}function E(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.crypto&&"object"===typeof a.globalScope.crypto.subtle&&"function"===typeof a.globalScope.crypto.subtle[e]}function S(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.msCrypto&&"object"===typeof a.globalScope.msCrypto.subtle&&"function"===typeof a.globalScope.msCrypto.subtle[e]}function A(e){for(var t=n.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),i=0;i0;)l.putByte(0),--h;return l.putBytes(n.util.hexToBytes(u)),l.getBytes()},c.rsa.decrypt=function(e,t,r,s){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var c=new i(n.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var u=b(c,t,r).toString(16),l=n.util.createBuffer(),h=o-Math.ceil(u.length/2);h>0;)l.putByte(0),--h;return l.putBytes(n.util.hexToBytes(u)),!1!==s?m(l.getBytes(),t,r):l.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"===typeof e&&(e=parseInt(e,10)),e=e||2048;var s,o=(r=r||{}).prng||n.random,a={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(s.eInt),s},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new i(null);r.fromInt(30);for(var n,s=0,o=function(e,t){return e|t},a=+new Date,l=0;null===e.keys&&(t<=0||lh?e.pqState=0:e.num.isProbablePrime(v(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(u[s++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(i.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var f=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}l+=(n=+new Date)-a,a=n}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,u){if(1===arguments.length?"object"===typeof e?(r=e,e=void 0):"function"===typeof e&&(u=e,e=void 0):2===arguments.length?"number"===typeof e?"function"===typeof t?(u=t,t=void 0):"number"!==typeof t&&(r=t,t=void 0):(r=e,u=t,e=void 0,t=void 0):3===arguments.length&&("number"===typeof t?"function"===typeof r&&(u=r,r=void 0):(u=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!n.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(u){if(_("generateKeyPair"))return s.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return u(e);u(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(E("generateKey")&&E("exportKey"))return a.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then((function(e){return a.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)})).then(void 0,(function(e){u(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(e)));u(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(S("generateKey")&&S("exportKey")){var l=a.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return l.oncomplete=function(e){var t=e.target.result,r=a.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(t)));u(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){u(e)}},void(l.onerror=function(e){u(e)})}}else if(_("generateKeyPairSync")){var h=s.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(h.privateKey),publicKey:c.publicKeyFromPem(h.publicKey)}}var d=c.rsa.createKeyPairGenerationState(e,t,r);if(!u)return c.rsa.stepKeyPairGenerationState(d,0),d.keys;!function(e,t,r){"function"===typeof t&&(r=t,t={});t=t||{};var s={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(s.prng=t.prng);function o(){a(e.pBits,(function(t,n){return t?r(t):(e.p=n,null!==e.q?u(t,e.q):void a(e.qBits,u))}))}function a(e,t){n.prime.generateProbablePrime(e,s,t)}function u(t,n){if(t)return r(t);if(e.q=n,e.p.compareTo(e.q)<0){var s=e.p;e.p=e.q,e.q=s}if(0!==e.p.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.p=null,void o();if(0!==e.q.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.q=null,void a(e.qBits,u);if(e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(i.ONE))return e.p=e.q=null,void o();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void a(e.qBits,u);var l=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}o()}(d,r,u)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,i){if("string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return y(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,i)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"===typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var s=t.encode(e,r,!0);return c.rsa.encrypt(s,r,!0)},verify:function(e,t,i,s){"string"===typeof i?i=i.toUpperCase():void 0===i&&(i="RSASSA-PKCS1-V1_5"),void 0===s&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===i?i={verify:function(e,t){t=m(t,r,!0);var i=o.fromDer(t,{parseAllBytes:s._parseAllDigestBytes}),a={},c=[];if(!o.validate(i,p,a,c))throw(u=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,u;var u,l=o.derToOid(a.algorithmIdentifier);if(l!==n.oids.md2&&l!==n.oids.md5&&l!==n.oids.sha1&&l!==n.oids.sha224&&l!==n.oids.sha256&&l!==n.oids.sha384&&l!==n.oids.sha512&&l!==n.oids["sha512-224"]&&l!==n.oids["sha512-256"])throw(u=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=l,u;if((l===n.oids.md2||l===n.oids.md5)&&!("parameters"in a))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return e===a.digest}}:"NONE"!==i&&"NULL"!==i&&null!==i||(i={verify:function(e,t){return e===(t=m(t,r,!0))}});var a=c.rsa.decrypt(t,r,!0,!1);return i.verify(e,a,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,i,s,o,a,u){var l={n:e,e:t,d:r,p:i,q:s,dP:o,dQ:a,qInv:u,decrypt:function(e,t,r){"string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var i=c.rsa.decrypt(e,l,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:m};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return n.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(i,l,!1)},sign:function(e,t){var r=!1;"string"===typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:g},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var n=t.encode(e,l.n.bitLength());return c.rsa.encrypt(n,l,r)}};return l},c.wrapRsaPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,o.toDer(e).getBytes())])},c.privateKeyFromAsn1=function(e){var t,r,s,a,u,d,f,p,g={},b=[];if(o.validate(e,l,g,b)&&(e=o.fromDer(n.util.createBuffer(g.privateKey))),g={},b=[],!o.validate(e,h,g,b)){var y=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw y.errors=b,y}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),s=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),u=n.util.createBuffer(g.privateKeyPrime2).toHex(),d=n.util.createBuffer(g.privateKeyExponent1).toHex(),f=n.util.createBuffer(g.privateKeyExponent2).toHex(),p=n.util.createBuffer(g.privateKeyCoefficient).toHex(),c.setRsaPrivateKey(new i(t,16),new i(r,16),new i(s,16),new i(a,16),new i(u,16),new i(d,16),new i(f,16),new i(p,16))},c.privateKeyToAsn1=c.privateKeyToRSAPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.e)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.d)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.p)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.q)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.dP)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.dQ)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.qInv))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(o.validate(e,f,t,r)){var s,a=o.derToOid(t.publicKeyOid);if(a!==c.oids.rsaEncryption)throw(s=new Error("Cannot read public key. Unknown OID.")).oid=a,s;e=t.rsaPublicKey}if(r=[],!o.validate(e,d,t,r))throw(s=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,s;var u=n.util.createBuffer(t.publicKeyModulus).toHex(),l=n.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new i(u,16),new i(l,16))},c.publicKeyToAsn1=c.publicKeyToSubjectPublicKeyInfo=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.publicKeyToRSAPublicKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.e))])}},3753:(e,t,r)=>{var n=r(45);r(5693),r(3900);var i=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=i,i.create=function(){o||(s=String.fromCharCode(128),s+=n.util.fillString(String.fromCharCode(0),64),o=!0);var e=null,t=n.util.createBuffer(),r=new Array(80),i={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s>>0,c>>>0];for(var u=i.fullMessageLength.length-1;u>=0;--u)i.fullMessageLength[u]+=c[1],c[1]=c[0]+(i.fullMessageLength[u]/4294967296>>>0),i.fullMessageLength[u]=i.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(s),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var c,u=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;o.putBytes(s.substr(0,i.blockLength-u));for(var l=8*i.fullMessageLength[0],h=0;h>>0,o.putInt32(l>>>0),l=c>>>0;o.putInt32(l);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,o);var f=n.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f},i};var s=null,o=!1;function a(e,t,r){for(var n,i,s,o,a,c,u,l=r.length();l>=64;){for(i=e.h0,s=e.h1,o=e.h2,a=e.h3,c=e.h4,u=0;u<16;++u)n=r.getInt32(),t[u]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;u<20;++u)n=(n=t[u-3]^t[u-8]^t[u-14]^t[u-16])<<1|n>>>31,t[u]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;u<32;++u)n=(n=t[u-3]^t[u-8]^t[u-14]^t[u-16])<<1|n>>>31,t[u]=n,n=(i<<5|i>>>27)+(s^o^a)+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;u<40;++u)n=(n=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|n>>>30,t[u]=n,n=(i<<5|i>>>27)+(s^o^a)+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;u<60;++u)n=(n=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|n>>>30,t[u]=n,n=(i<<5|i>>>27)+(s&o|a&(s^o))+c+2400959708+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;u<80;++u)n=(n=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|n>>>30,t[u]=n,n=(i<<5|i>>>27)+(s^o^a)+c+3395469782+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;e.h0=e.h0+i|0,e.h1=e.h1+s|0,e.h2=e.h2+o|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,l-=64}}},3899:(e,t,r)=>{var n=r(45);r(5693),r(3900);var i=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=i,i.create=function(){o||(s=String.fromCharCode(128),s+=n.util.fillString(String.fromCharCode(0),64),a=[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],o=!0);var e=null,t=n.util.createBuffer(),r=new Array(64),i={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s>>0,a>>>0];for(var u=i.fullMessageLength.length-1;u>=0;--u)i.fullMessageLength[u]+=a[1],a[1]=a[0]+(i.fullMessageLength[u]/4294967296>>>0),i.fullMessageLength[u]=i.fullMessageLength[u]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(s),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var a,u=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;o.putBytes(s.substr(0,i.blockLength-u));for(var l=8*i.fullMessageLength[0],h=0;h>>0,o.putInt32(l>>>0),l=a>>>0;o.putInt32(l);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};c(d,r,o);var f=n.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f.putInt32(d.h5),f.putInt32(d.h6),f.putInt32(d.h7),f},i};var s=null,o=!1,a=null;function c(e,t,r){for(var n,i,s,o,c,u,l,h,d,f,p,g,b,y=r.length();y>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=((n=t[c-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=((i=t[c-15])>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[c]=n+t[c-7]+i+t[c-16]|0;for(u=e.h0,l=e.h1,h=e.h2,d=e.h3,f=e.h4,p=e.h5,g=e.h6,b=e.h7,c=0;c<64;++c)s=(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),o=u&l|h&(u^l),n=b+((f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7))+(g^f&(p^g))+a[c]+t[c],b=g,g=p,p=f,f=d+n>>>0,d=h,h=l,l=u,u=n+(i=s+o)>>>0;e.h0=e.h0+u|0,e.h1=e.h1+l|0,e.h2=e.h2+h|0,e.h3=e.h3+d|0,e.h4=e.h4+f|0,e.h5=e.h5+p|0,e.h6=e.h6+g|0,e.h7=e.h7+b|0,y-=64}}},8138:(e,t,r)=>{var n=r(45);r(5693),r(3900);var i=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=i;var s=n.sha384=n.sha512.sha384=n.sha512.sha384||{};s.create=function(){return i.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=s,n.sha512.sha256=n.sha512.sha256||{create:function(){return i.create("SHA-512/256")}},n.md["sha512/256"]=n.md.algorithms["sha512/256"]=n.sha512.sha256,n.sha512.sha224=n.sha512.sha224||{create:function(){return i.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,i.create=function(e){if(a||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),128),c=[[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]],(u={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],u["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],u["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],u["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],a=!0),"undefined"===typeof e&&(e="SHA-512"),!(e in u))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=u[e],r=null,i=n.util.createBuffer(),s=new Array(80),h=0;h<80;++h)s[h]=new Array(2);var d=64;switch(e){case"SHA-384":d=48;break;case"SHA-512/256":d=32;break;case"SHA-512/224":d=28}var f={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:d,messageLength:0,fullMessageLength:null,messageLengthSize:16,start:function(){f.messageLength=0,f.fullMessageLength=f.messageLength128=[];for(var e=f.messageLengthSize/4,s=0;s>>0,o>>>0];for(var a=f.fullMessageLength.length-1;a>=0;--a)f.fullMessageLength[a]+=o[1],o[1]=o[0]+(f.fullMessageLength[a]/4294967296>>>0),f.fullMessageLength[a]=f.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return i.putBytes(e),l(r,s,i),(i.read>2048||0===i.length())&&i.compact(),f},f.digest=function(){var t=n.util.createBuffer();t.putBytes(i.bytes());var a,c=f.fullMessageLength[f.fullMessageLength.length-1]+f.messageLengthSize&f.blockLength-1;t.putBytes(o.substr(0,f.blockLength-c));for(var u=8*f.fullMessageLength[0],h=0;h>>0,t.putInt32(u>>>0),u=a>>>0;t.putInt32(u);var d=new Array(r.length);for(h=0;h=128;){for(R=0;R<16;++R)t[R][0]=r.getInt32()>>>0,t[R][1]=r.getInt32()>>>0;for(;R<80;++R)n=(((P=(N=t[R-2])[0])>>>19|(D=N[1])<<13)^(D>>>29|P<<3)^P>>>6)>>>0,i=((P<<13|D>>>19)^(D<<3|P>>>29)^(P<<26|D>>>6))>>>0,s=(((P=(U=t[R-15])[0])>>>1|(D=U[1])<<31)^(P>>>8|D<<24)^P>>>7)>>>0,o=((P<<31|D>>>1)^(P<<24|D>>>8)^(P<<25|D>>>7))>>>0,B=t[R-7],L=t[R-16],D=i+B[1]+o+L[1],t[R][0]=n+B[0]+s+L[0]+(D/4294967296>>>0)>>>0,t[R][1]=D>>>0;for(p=e[0][0],g=e[0][1],b=e[1][0],y=e[1][1],m=e[2][0],w=e[2][1],v=e[3][0],_=e[3][1],E=e[4][0],S=e[4][1],A=e[5][0],k=e[5][1],x=e[6][0],I=e[6][1],C=e[7][0],T=e[7][1],R=0;R<80;++R)l=((E>>>14|S<<18)^(E>>>18|S<<14)^(S>>>9|E<<23))>>>0,h=(x^E&(A^x))>>>0,a=((p>>>28|g<<4)^(g>>>2|p<<30)^(g>>>7|p<<25))>>>0,u=((p<<4|g>>>28)^(g<<30|p>>>2)^(g<<25|p>>>7))>>>0,d=(p&b|m&(p^b))>>>0,f=(g&y|w&(g^y))>>>0,D=T+(((E<<18|S>>>14)^(E<<14|S>>>18)^(S<<23|E>>>9))>>>0)+((I^S&(k^I))>>>0)+c[R][1]+t[R][1],n=C+l+h+c[R][0]+t[R][0]+(D/4294967296>>>0)>>>0,i=D>>>0,s=a+d+((D=u+f)/4294967296>>>0)>>>0,o=D>>>0,C=x,T=I,x=A,I=k,A=E,k=S,E=v+n+((D=_+i)/4294967296>>>0)>>>0,S=D>>>0,v=m,_=w,m=b,w=y,b=p,y=g,p=n+s+((D=i+o)/4294967296>>>0)>>>0,g=D>>>0;D=e[0][1]+g,e[0][0]=e[0][0]+p+(D/4294967296>>>0)>>>0,e[0][1]=D>>>0,D=e[1][1]+y,e[1][0]=e[1][0]+b+(D/4294967296>>>0)>>>0,e[1][1]=D>>>0,D=e[2][1]+w,e[2][0]=e[2][0]+m+(D/4294967296>>>0)>>>0,e[2][1]=D>>>0,D=e[3][1]+_,e[3][0]=e[3][0]+v+(D/4294967296>>>0)>>>0,e[3][1]=D>>>0,D=e[4][1]+S,e[4][0]=e[4][0]+E+(D/4294967296>>>0)>>>0,e[4][1]=D>>>0,D=e[5][1]+k,e[5][0]=e[5][0]+A+(D/4294967296>>>0)>>>0,e[5][1]=D>>>0,D=e[6][1]+I,e[6][0]=e[6][0]+x+(D/4294967296>>>0)>>>0,e[6][1]=D>>>0,D=e[7][1]+T,e[7][0]=e[7][0]+C+(D/4294967296>>>0)>>>0,e[7][1]=D>>>0,M-=128}}},3900:(e,t,r)=>{var n=r(45),i=r(6407),s=e.exports=n.util=n.util||{};function o(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function a(e){if(this.data="",this.read=0,"string"===typeof e)this.data=e;else if(s.isArrayBuffer(e)||s.isArrayBufferView(e))if("undefined"!==typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(n){for(var r=0;r15?(r=Date.now(),o(e)):(t.push(e),1===t.length&&i.setAttribute("a",n=!n))}}s.nextTick=s.setImmediate}(),s.isNodejs="undefined"!==typeof process&&process.versions&&process.versions.node,s.globalScope=s.isNodejs?r.g:"undefined"===typeof self?window:self,s.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},s.isArrayBuffer=function(e){return"undefined"!==typeof ArrayBuffer&&e instanceof ArrayBuffer},s.isArrayBufferView=function(e){return e&&s.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},s.ByteBuffer=a,s.ByteStringBuffer=a;s.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},s.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},s.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},s.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},s.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},s.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},s.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(s.encodeUtf8(e))},s.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},s.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},s.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},s.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},s.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},s.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},s.ByteStringBuffer.prototype.putInt=function(e,t){o(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},s.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},s.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},s.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},s.ByteStringBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},s.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},s.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},s.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},s.ByteStringBuffer.prototype.copy=function(){var e=s.createBuffer(this.data);return e.read=this.read,e},s.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},s.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},s.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},s.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},s.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},s.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},s.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},s.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},s.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},s.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},s.DataBuffer.prototype.putInt=function(e,t){o(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},s.DataBuffer.prototype.putSignedInt=function(e,t){return o(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},s.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},s.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},s.DataBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},s.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},s.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},s.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},s.DataBuffer.prototype.copy=function(){return new s.DataBuffer(this)},s.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},s.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},s.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},s.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},s.xorBytes=function(e,t,r){for(var n="",i="",s="",o=0,a=0;r>0;--r,++o)i=e.charCodeAt(o)^t.charCodeAt(o),a>=10&&(n+=s,s="",a=0),s+=String.fromCharCode(i),++a;return n+=s},s.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],l="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";s.encode64=function(e,t){for(var r,n,i,s="",o="",a=0;a>2),s+=c.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":(s+=c.charAt((15&n)<<2|i>>6),s+=isNaN(i)?"=":c.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+=s},s.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,i,s="",o=0;o>4),64!==n&&(s+=String.fromCharCode((15&r)<<4|n>>2),64!==i&&(s+=String.fromCharCode((3&n)<<6|i)));return s},s.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},s.decodeUtf8=function(e){return decodeURIComponent(escape(e))},s.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:i.encode,decode:i.decode}},s.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},s.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,s=0;s>2),s+=c.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":(s+=c.charAt((15&n)<<2|i>>6),s+=isNaN(i)?"=":c.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+=s},s.binary.base64.decode=function(e,t,r){var n,i,s,o,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,l=r=r||0;c>4,64!==s&&(a[l++]=(15&i)<<4|s>>2,64!==o&&(a[l++]=(3&s)<<6|o));return t?l-r:a.subarray(0,l)},s.binary.base58.encode=function(e,t){return s.binary.baseN.encode(e,l,t)},s.binary.base58.decode=function(e,t){return s.binary.baseN.decode(e,l,t)},s.text={utf8:{},utf16:{}},s.text.utf8.encode=function(e,t,r){e=s.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,o=0;o0&&s.push(r),o=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i");break;case"%":s.push("%");break;default:s.push("<%"+a+"?>")}}return s.push(e.substring(o)),s.join("")},s.formatNumber=function(e,t,r,n){var i=e,s=isNaN(t=Math.abs(t))?2:t,o=void 0===r?",":r,a=void 0===n?".":n,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+a:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+a)+(s?o+Math.abs(i-u).toFixed(s).slice(2):"")},s.formatSize=function(e){return e=e>=1073741824?s.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?s.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?s.formatNumber(e/1024,0)+" KiB":s.formatNumber(e,0)+" bytes"},s.bytesFromIP=function(e){return-1!==e.indexOf(".")?s.bytesFromIPv4(e):-1!==e.indexOf(":")?s.bytesFromIPv6(e):null},s.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=s.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(o)}if(r.length>0){var u=r[n];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),0===u.start&&t.unshift(""),7===u.end&&t.push(""))}return t.join(":")},s.estimateCores=function(e,t){if("function"===typeof e&&(t=e,e={}),e=e||{},"cores"in s&&!e.update)return t(null,s.cores);if("undefined"!==typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return s.cores=navigator.hardwareConcurrency,t(null,s.cores);if("undefined"===typeof Worker)return s.cores=1,t(null,s.cores);if("undefined"===typeof Blob)return s.cores=2,t(null,s.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()a.st&&i.sti.st&&a.st{"use strict";var t=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach((function(e){n[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(i){return!1}}()?Object.assign:function(e,i){for(var s,o,a=function(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),c=1;c{"use strict";e.exports=c;var n,i=r(1509),s=i.LongBits,o=i.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var u="undefined"!==typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},l=function(){return i.Buffer?function(e){return(c.create=function(e){return i.Buffer.isBuffer(e)?new n(e):u(e)})(e)}:u};function h(){var e=new s(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new s(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}c.create=l(),c.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,c.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return e}}(),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return d(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|d(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,r);if(t===r){var n=i.Buffer;return n?n.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return o.read(e,0,e.length)},c.prototype.skip=function(e){if("number"===typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!==(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=l(),n._configure();var t=i.Long?"toLong":"toNumber";i.merge(c.prototype,{int64:function(){return h.call(this)[t](!1)},uint64:function(){return h.call(this)[t](!0)},sint64:function(){return h.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},7707:(e,t,r)=>{"use strict";e.exports=s;var n=r(3338);(s.prototype=Object.create(n.prototype)).constructor=s;var i=r(1509);function s(e){n.call(this,e)}s._configure=function(){i.Buffer&&(s.prototype._slice=i.Buffer.prototype.slice)},s.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},s._configure()},6350:(e,t,r)=>{"use strict";e.exports=i;var n=r(1509);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var s=i.zero=new i(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var o=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(e){if(0===e)return s;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new i(r,n)},i.from=function(e){if("number"===typeof e)return i.fromNumber(e);if(n.isString(e)){if(!n.Long)return i.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):s},i.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;i.fromHash=function(e){return e===o?s:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},1509:function(e,t,r){"use strict";var n=t;function i(e,t,r){for(var n=Object.keys(t),i=0;i0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"===typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"===typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!==typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=i,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=s,n.ProtocolError=s("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r{"use strict";e.exports=h;var n,i=r(1509),s=i.LongBits,o=i.base64,a=i.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function u(){}function l(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(u,0,0),this.tail=this.head,this.states=null}var d=function(){return i.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function f(e,t,r){t[r]=255&e}function p(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function b(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(h.alloc=i.pool(h.alloc,i.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},p.prototype=Object.create(c.prototype),p.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new p((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,s.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=s.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=s.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(f,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(b,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=s.from(e);return this._push(b,4,t.lo)._push(b,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(i.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(i.float.writeDoubleLE,8,e)};var y=i.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(f,1,0);if(i.isString(e)){var r=h.alloc(t=o.length(e));o.decode(e,r,0),e=r}return this.uint32(t)._push(y,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(f,1,0)},h.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new c(u,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(u,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},3931:(e,t,r)=>{"use strict";e.exports=s;var n=r(5850);(s.prototype=Object.create(n.prototype)).constructor=s;var i=r(1509);function s(){n.call(this)}function o(e,t,r){e.length<40?i.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}s._configure=function(){s.alloc=i._Buffer_allocUnsafe,s.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(s.writeBytesBuffer,t,e),this},s.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},s._configure()},8275:(e,t)=>{"use strict";class r{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const n=r.toUint8Array(e),i=r.toUint8Array(t);if(n.length!==i.byteLength)return!1;for(let r=0;r1&&void 0!==arguments[1]&&arguments[1];const n=r.toArrayBuffer(e),i=new DataView(n);let s="";for(let r=0;r1&&void 0!==arguments[1]&&arguments[1];const r=new ArrayBuffer(2*e.length),n=new DataView(r);for(let i=0;i1&&void 0!==arguments[1]?arguments[1]:"utf8";const n=r.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return c.toString(n,!0);case"utf16":case"utf16be":return c.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8";if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return c.fromString(e,!0);case"utf16":case"utf16be":return c.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=r.toUint8Array(e);if("undefined"!==typeof btoa){const e=this.ToString(t,"binary");return btoa(e)}return Buffer.from(t).toString("base64")}static FromBase64(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!u.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!==typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!u.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.FromBinary(e);case"utf8":return a.fromString(e);case"utf16":case"utf16be":return c.fromString(e);case"utf16le":case"usc2":return c.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.ToBinary(e);case"utf8":return a.toString(e);case"utf16":case"utf16be":return c.toString(e);case"utf16le":case"usc2":return c.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){const t=e.length,r=new Uint8Array(t);for(let n=0;n1&&void 0!==arguments[1]&&arguments[1];return c.toString(e,t)}static FromUtf16String(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return c.fromString(e,t)}static Base64Padding(e){const t=4-e.length%4;if(t<4)for(let r=0;r{"use strict";var n=r(5043),i=r(2123),s=r(8853);function o(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r
{ (): A }\n\ntype PipeSource =\n Iterable |\n AsyncIterable |\n SourceFn |\n Duplex\n\ntype PipeTransform =\n Transform |\n Duplex\n\ntype PipeSink =\n Sink |\n Duplex\n\ntype PipeOutput =\n A extends Sink ? ReturnType :\n A extends Duplex ? ReturnType :\n never\n\n// single item pipe output includes pipe source types\ntype SingleItemPipeOutput =\n A extends Iterable ? A :\n A extends AsyncIterable ? A :\n A extends SourceFn ? ReturnType :\n A extends Duplex ? A['source'] :\n PipeOutput\n\ntype PipeFnInput =\n A extends Iterable ? A :\n A extends AsyncIterable ? A :\n A extends SourceFn ? ReturnType :\n A extends Transform ? ReturnType :\n A extends Duplex ? A['source'] :\n never\n\n// one item, just a pass-through\nexport function pipe<\n A extends PipeSource\n> (\n source: A\n): SingleItemPipeOutput\n\n// two items, source to sink\nexport function pipe<\n A extends PipeSource,\n B extends PipeSink>\n> (\n source: A,\n sink: B\n): PipeOutput\n\n// three items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeSink>\n> (\n source: A,\n transform1: B,\n sink: C\n): PipeOutput\n\n// many items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeTransform>,\n D extends PipeSink>\n> (\n source: A,\n transform1: B,\n transform2: C,\n sink: D\n): PipeOutput\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeTransform>,\n D extends PipeTransform>,\n E extends PipeSink>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n sink: E\n): PipeOutput\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeTransform>,\n D extends PipeTransform>,\n E extends PipeTransform>,\n F extends PipeSink>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n sink: F\n): PipeOutput\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeTransform>,\n D extends PipeTransform>,\n E extends PipeTransform>,\n F extends PipeTransform>,\n G extends PipeSink>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n sink: G\n): PipeOutput\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeTransform>,\n D extends PipeTransform>,\n E extends PipeTransform>,\n F extends PipeTransform>,\n G extends PipeTransform>,\n H extends PipeSink>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n sink: H\n): PipeOutput\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeTransform>,\n D extends PipeTransform>,\n E extends PipeTransform>,\n F extends PipeTransform>,\n G extends PipeTransform>,\n H extends PipeTransform>,\n I extends PipeSink>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n sink: I\n): PipeOutput\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeTransform>,\n D extends PipeTransform>,\n E extends PipeTransform>,\n F extends PipeTransform>,\n G extends PipeTransform>,\n H extends PipeTransform>,\n I extends PipeTransform>,\n J extends PipeSink>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n transform8: I,\n sink: J\n): PipeOutput\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeTransform>,\n D extends PipeTransform>,\n E extends PipeTransform>,\n F extends PipeTransform>,\n G extends PipeTransform>,\n H extends PipeTransform>,\n I extends PipeTransform>,\n J extends PipeTransform>,\n K extends PipeSink>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n transform8: I,\n transform9: J,\n sink: K\n): PipeOutput\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform>,\n C extends PipeTransform>,\n D extends PipeTransform>,\n E extends PipeTransform>,\n F extends PipeTransform>,\n G extends PipeTransform>,\n H extends PipeTransform>,\n I extends PipeTransform>,\n J extends PipeTransform>,\n K extends PipeTransform>,\n L extends PipeSink>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n transform8: I,\n transform9: J,\n transform10: K,\n sink: L\n): PipeOutput\n\nexport function pipe (first: any, ...rest: any[]): any {\n if (first == null) {\n throw new Error('Empty pipeline')\n }\n\n // Duplex at start: wrap in function and return duplex source\n if (isDuplex(first)) {\n const duplex = first\n first = () => duplex.source\n // Iterable at start: wrap in function\n } else if (isIterable(first) || isAsyncIterable(first)) {\n const source = first\n first = () => source\n }\n\n const fns = [first, ...rest]\n\n if (fns.length > 1) {\n // Duplex at end: use duplex sink\n if (isDuplex(fns[fns.length - 1])) {\n fns[fns.length - 1] = fns[fns.length - 1].sink\n }\n }\n\n if (fns.length > 2) {\n // Duplex in the middle, consume source with duplex sink and return duplex source\n for (let i = 1; i < fns.length - 1; i++) {\n if (isDuplex(fns[i])) {\n fns[i] = duplexPipelineFn(fns[i])\n }\n }\n }\n\n return rawPipe(...fns)\n}\n\nexport const rawPipe = (...fns: any): any => {\n let res\n while (fns.length > 0) {\n res = fns.shift()(res)\n }\n return res\n}\n\nconst isAsyncIterable = (obj: any): obj is AsyncIterable => {\n return obj?.[Symbol.asyncIterator] != null\n}\n\nconst isIterable = (obj: any): obj is Iterable => {\n return obj?.[Symbol.iterator] != null\n}\n\nconst isDuplex = (obj: any): obj is Duplex => {\n if (obj == null) {\n return false\n }\n\n return obj.sink != null && obj.source != null\n}\n\nconst duplexPipelineFn = (duplex: Duplex) => {\n return (source: any) => {\n const p = duplex.sink(source)\n\n if (p?.then != null) {\n const stream = pushable({\n objectMode: true\n })\n p.then(() => {\n stream.end()\n }, (err: Error) => {\n stream.end(err)\n })\n\n let sourceWrap: () => Iterable | AsyncIterable\n const source = duplex.source\n\n if (isAsyncIterable(source)) {\n sourceWrap = async function * () {\n yield * source\n stream.end()\n }\n } else if (isIterable(source)) {\n sourceWrap = function * () {\n yield * source\n stream.end()\n }\n } else {\n throw new Error('Unknown duplex source type - must be Iterable or AsyncIterable')\n }\n\n return merge(stream, sourceWrap())\n }\n\n return duplex.source\n }\n}\n","import type { PeerUpdate, Stream } from \"@libp2p/interface\";\nimport { Peer } from \"@libp2p/interface\";\nimport { Libp2p } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport { selectConnection } from \"@waku/utils/libp2p\";\n\nexport class StreamManager {\n private streamPool: Map>;\n private readonly log: Logger;\n\n constructor(\n public multicodec: string,\n public getConnections: Libp2p[\"getConnections\"],\n public addEventListener: Libp2p[\"addEventListener\"]\n ) {\n this.log = new Logger(`stream-manager:${multicodec}`);\n this.addEventListener(\n \"peer:update\",\n this.handlePeerUpdateStreamPool.bind(this)\n );\n this.getStream = this.getStream.bind(this);\n this.streamPool = new Map();\n }\n\n public async getStream(peer: Peer): Promise {\n const peerIdStr = peer.id.toString();\n const streamPromise = this.streamPool.get(peerIdStr);\n\n if (!streamPromise) {\n return this.newStream(peer); // fallback by creating a new stream on the spot\n }\n\n // We have the stream, let's remove it from the map\n this.streamPool.delete(peerIdStr);\n\n this.prepareNewStream(peer);\n\n const stream = await streamPromise;\n\n if (!stream || stream.status === \"closed\") {\n return this.newStream(peer); // fallback by creating a new stream on the spot\n }\n\n return stream;\n }\n\n private async newStream(peer: Peer): Promise {\n const connections = this.getConnections(peer.id);\n const connection = selectConnection(connections);\n if (!connection) {\n throw new Error(\"Failed to get a connection to the peer\");\n }\n return connection.newStream(this.multicodec);\n }\n\n private prepareNewStream(peer: Peer): void {\n const streamPromise = this.newStream(peer).catch(() => {\n // No error thrown as this call is not triggered by the user\n this.log.error(\n `Failed to prepare a new stream for ${peer.id.toString()}`\n );\n });\n this.streamPool.set(peer.id.toString(), streamPromise);\n }\n\n private handlePeerUpdateStreamPool = (evt: CustomEvent): void => {\n const peer = evt.detail.peer;\n if (peer.protocols.includes(this.multicodec)) {\n this.log.info(`Preemptively opening a stream to ${peer.id.toString()}`);\n this.prepareNewStream(peer);\n }\n };\n}\n","import type { Connection, Peer, PeerStore } from \"@libp2p/interface\";\nimport { ShardInfo } from \"@waku/interfaces\";\n\nimport { bytesToUtf8 } from \"../bytes/index.js\";\nimport { decodeRelayShard } from \"../common/relay_shard_codec.js\";\n\n/**\n * Returns a pseudo-random peer that supports the given protocol.\n * Useful for protocols such as store and light push\n */\nexport function selectRandomPeer(peers: Peer[]): Peer | undefined {\n if (peers.length === 0) return;\n\n const index = Math.round(Math.random() * (peers.length - 1));\n return peers[index];\n}\n\n/**\n * Function to sort peers by latency from lowest to highest\n * @param peerStore - The Libp2p PeerStore\n * @param peers - The list of peers to choose from\n * @returns Sorted array of peers by latency\n */\nexport async function sortPeersByLatency(\n peerStore: PeerStore,\n peers: Peer[]\n): Promise {\n if (peers.length === 0) return [];\n\n const results = await Promise.all(\n peers.map(async (peer) => {\n try {\n const pingBytes = (await peerStore.get(peer.id)).metadata.get(\"ping\");\n if (!pingBytes) return { peer, ping: Infinity };\n\n const ping = Number(bytesToUtf8(pingBytes));\n return { peer, ping };\n } catch (error) {\n return { peer, ping: Infinity };\n }\n })\n );\n\n // filter out null values\n const validResults = results.filter(\n (result): result is { peer: Peer; ping: number } => result !== null\n );\n\n return validResults\n .sort((a, b) => a.ping - b.ping)\n .map((result) => result.peer);\n}\n\n/**\n * Returns the list of peers that supports the given protocol.\n */\nexport async function getPeersForProtocol(\n peerStore: PeerStore,\n protocols: string[]\n): Promise {\n const peers: Peer[] = [];\n await peerStore.forEach((peer) => {\n for (let i = 0; i < protocols.length; i++) {\n if (peer.protocols.includes(protocols[i])) {\n peers.push(peer);\n break;\n }\n }\n });\n return peers;\n}\n\nexport async function getConnectedPeersForProtocolAndShard(\n connections: Connection[],\n peerStore: PeerStore,\n protocols: string[],\n shardInfo?: ShardInfo\n): Promise {\n const openConnections = connections.filter(\n (connection) => connection.status === \"open\"\n );\n\n const peerPromises = openConnections.map(async (connection) => {\n const peer = await peerStore.get(connection.remotePeer);\n const supportsProtocol = protocols.some((protocol) =>\n peer.protocols.includes(protocol)\n );\n\n if (supportsProtocol) {\n if (shardInfo) {\n const encodedPeerShardInfo = peer.metadata.get(\"shardInfo\");\n const peerShardInfo =\n encodedPeerShardInfo && decodeRelayShard(encodedPeerShardInfo);\n\n if (peerShardInfo && shardInfo.clusterId === peerShardInfo.clusterId) {\n return peer;\n }\n } else {\n return peer;\n }\n }\n return null;\n });\n\n const peersWithNulls = await Promise.all(peerPromises);\n return peersWithNulls.filter((peer): peer is Peer => peer !== null);\n}\n\nexport function selectConnection(\n connections: Connection[]\n): Connection | undefined {\n if (!connections.length) return;\n if (connections.length === 1) return connections[0];\n\n let latestConnection: Connection | undefined;\n\n connections.forEach((connection) => {\n if (connection.status === \"open\") {\n if (!latestConnection) {\n latestConnection = connection;\n } else if (connection.timeline.open > latestConnection.timeline.open) {\n latestConnection = connection;\n }\n }\n });\n\n return latestConnection;\n}\n","import type { Libp2p } from \"@libp2p/interface\";\nimport type { Peer, PeerStore, Stream } from \"@libp2p/interface\";\nimport type {\n IBaseProtocolCore,\n Libp2pComponents,\n ProtocolCreateOptions,\n PubsubTopic\n} from \"@waku/interfaces\";\nimport { ensureShardingConfigured, Logger } from \"@waku/utils\";\nimport {\n getConnectedPeersForProtocolAndShard,\n getPeersForProtocol,\n sortPeersByLatency\n} from \"@waku/utils/libp2p\";\n\nimport { filterPeersByDiscovery } from \"./filterPeers.js\";\nimport { StreamManager } from \"./stream_manager.js\";\n\n/**\n * A class with predefined helpers, to be used as a base to implement Waku\n * Protocols.\n */\nexport class BaseProtocol implements IBaseProtocolCore {\n public readonly addLibp2pEventListener: Libp2p[\"addEventListener\"];\n public readonly removeLibp2pEventListener: Libp2p[\"removeEventListener\"];\n protected streamManager: StreamManager;\n\n constructor(\n public multicodec: string,\n private components: Libp2pComponents,\n private log: Logger,\n public readonly pubsubTopics: PubsubTopic[],\n private options?: ProtocolCreateOptions\n ) {\n this.addLibp2pEventListener = components.events.addEventListener.bind(\n components.events\n );\n this.removeLibp2pEventListener = components.events.removeEventListener.bind(\n components.events\n );\n\n this.streamManager = new StreamManager(\n multicodec,\n components.connectionManager.getConnections.bind(\n components.connectionManager\n ),\n this.addLibp2pEventListener\n );\n }\n protected async getStream(peer: Peer): Promise {\n return this.streamManager.getStream(peer);\n }\n\n public get peerStore(): PeerStore {\n return this.components.peerStore;\n }\n\n /**\n * Returns known peers from the address book (`libp2p.peerStore`) that support\n * the class protocol. Waku may or may not be currently connected to these\n * peers.\n */\n public async allPeers(): Promise {\n return getPeersForProtocol(this.peerStore, [this.multicodec]);\n }\n\n public async connectedPeers(): Promise {\n const peers = await this.allPeers();\n return peers.filter((peer) => {\n return (\n this.components.connectionManager.getConnections(peer.id).length > 0\n );\n });\n }\n\n /**\n * Retrieves a list of connected peers that support the protocol. The list is sorted by latency.\n *\n * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.\n * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.\n\n * @returns A list of peers that support the protocol sorted by latency.\n */\n async getPeers(\n {\n numPeers,\n maxBootstrapPeers\n }: {\n numPeers: number;\n maxBootstrapPeers: number;\n } = {\n maxBootstrapPeers: 1,\n numPeers: 0\n }\n ): Promise {\n // Retrieve all connected peers that support the protocol & shard (if configured)\n const connectedPeersForProtocolAndShard =\n await getConnectedPeersForProtocolAndShard(\n this.components.connectionManager.getConnections(),\n this.peerStore,\n [this.multicodec],\n this.options?.shardInfo\n ? ensureShardingConfigured(this.options.shardInfo).shardInfo\n : undefined\n );\n\n // Filter the peers based on discovery & number of peers requested\n const filteredPeers = filterPeersByDiscovery(\n connectedPeersForProtocolAndShard,\n numPeers,\n maxBootstrapPeers\n );\n\n // Sort the peers by latency\n const sortedFilteredPeers = await sortPeersByLatency(\n this.peerStore,\n filteredPeers\n );\n\n if (sortedFilteredPeers.length === 0) {\n this.log.warn(\n \"No peers found. Ensure you have a connection to the network.\"\n );\n }\n\n if (sortedFilteredPeers.length < numPeers) {\n this.log.warn(\n `Only ${sortedFilteredPeers.length} peers found. Requested ${numPeers}.`\n );\n }\n\n return sortedFilteredPeers;\n }\n}\n","import { Peer } from \"@libp2p/interface\";\nimport { Tags } from \"@waku/interfaces\";\n\n/**\n * Retrieves a list of peers based on the specified criteria:\n * 1. If numPeers is 0, return all peers\n * 2. Bootstrap peers are prioritized\n * 3. Non-bootstrap peers are randomly selected to fill up to numPeers\n *\n * @param peers - The list of peers to filter from.\n * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned, irrespective of `maxBootstrapPeers`.\n * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.\n * @returns An array of peers based on the specified criteria.\n */\nexport function filterPeersByDiscovery(\n peers: Peer[],\n numPeers: number,\n maxBootstrapPeers: number\n): Peer[] {\n // Collect the bootstrap peers up to the specified maximum\n let bootstrapPeers = peers\n .filter((peer) => peer.tags.has(Tags.BOOTSTRAP))\n .slice(0, maxBootstrapPeers);\n\n // If numPeers is less than the number of bootstrap peers, adjust the bootstrapPeers array\n if (numPeers > 0 && numPeers < bootstrapPeers.length) {\n bootstrapPeers = bootstrapPeers.slice(0, numPeers);\n }\n\n // Collect non-bootstrap peers\n const nonBootstrapPeers = peers.filter(\n (peer) => !peer.tags.has(Tags.BOOTSTRAP)\n );\n\n // If numPeers is 0, return all peers\n if (numPeers === 0) {\n return [...bootstrapPeers, ...nonBootstrapPeers];\n }\n\n // Initialize the list of selected peers with the bootstrap peers\n const selectedPeers: Peer[] = [...bootstrapPeers];\n\n // Fill up to numPeers with remaining random peers if needed\n while (selectedPeers.length < numPeers && nonBootstrapPeers.length > 0) {\n const randomIndex = Math.floor(Math.random() * nonBootstrapPeers.length);\n const randomPeer = nonBootstrapPeers.splice(randomIndex, 1)[0];\n selectedPeers.push(randomPeer);\n }\n\n return selectedPeers;\n}\n","const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default {\n randomUUID\n};","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import { proto_filter_v2 as proto, WakuMessage } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\n\n/**\n * FilterPushRPC represents a message conforming to the Waku FilterPush protocol.\n * Protocol documentation: https://rfc.vac.dev/spec/12/\n */\nexport class FilterPushRpc {\n public constructor(public proto: proto.MessagePush) {}\n\n static decode(bytes: Uint8Array): FilterPushRpc {\n const res = proto.MessagePush.decode(bytes);\n return new FilterPushRpc(res);\n }\n\n encode(): Uint8Array {\n return proto.MessagePush.encode(this.proto);\n }\n\n get wakuMessage(): WakuMessage | undefined {\n return this.proto.wakuMessage;\n }\n\n /**\n * Get the pubsub topic from the FilterPushRpc object.\n * @returns string\n */\n get pubsubTopic(): string | undefined {\n return this.proto.pubsubTopic;\n }\n}\n\nexport class FilterSubscribeRpc {\n public constructor(public proto: proto.FilterSubscribeRequest) {}\n\n static createSubscribeRequest(\n pubsubTopic: string,\n contentTopics: string[]\n ): FilterSubscribeRpc {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType:\n proto.FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBE,\n pubsubTopic,\n contentTopics\n });\n }\n\n static createUnsubscribeRequest(\n pubsubTopic: string,\n contentTopics: string[]\n ): FilterSubscribeRpc {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType:\n proto.FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE,\n pubsubTopic,\n contentTopics\n });\n }\n\n static createUnsubscribeAllRequest(pubsubTopic: string): FilterSubscribeRpc {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType:\n proto.FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE_ALL,\n pubsubTopic,\n contentTopics: []\n });\n }\n\n static createSubscriberPingRequest(): FilterSubscribeRpc {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType:\n proto.FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBER_PING,\n pubsubTopic: \"\",\n contentTopics: []\n });\n }\n\n static decode(bytes: Uint8Array): FilterSubscribeRpc {\n const res = proto.FilterSubscribeRequest.decode(bytes);\n return new FilterSubscribeRpc(res);\n }\n\n encode(): Uint8Array {\n return proto.FilterSubscribeRequest.encode(this.proto);\n }\n\n get filterSubscribeType(): proto.FilterSubscribeRequest.FilterSubscribeType {\n return this.proto.filterSubscribeType;\n }\n\n get requestId(): string {\n return this.proto.requestId;\n }\n\n get pubsubTopic(): string | undefined {\n return this.proto.pubsubTopic;\n }\n\n get contentTopics(): string[] {\n return this.proto.contentTopics;\n }\n}\n\nexport class FilterSubscribeResponse {\n public constructor(public proto: proto.FilterSubscribeResponse) {}\n\n static decode(bytes: Uint8Array): FilterSubscribeResponse {\n const res = proto.FilterSubscribeResponse.decode(bytes);\n return new FilterSubscribeResponse(res);\n }\n\n encode(): Uint8Array {\n return proto.FilterSubscribeResponse.encode(this.proto);\n }\n\n get statusCode(): number {\n return this.proto.statusCode;\n }\n\n get statusDesc(): string | undefined {\n return this.proto.statusDesc;\n }\n\n get requestId(): string {\n return this.proto.requestId;\n }\n}\n","import { Stream } from \"@libp2p/interface\";\nimport type { Peer } from \"@libp2p/interface\";\nimport type { IncomingStreamData } from \"@libp2p/interface-internal\";\nimport type {\n Callback,\n ContentTopic,\n IAsyncIterator,\n IDecodedMessage,\n IDecoder,\n IFilter,\n IProtoMessage,\n IReceiver,\n Libp2p,\n ProtocolCreateOptions,\n PubsubTopic,\n SingleShardInfo,\n Unsubscribe\n} from \"@waku/interfaces\";\nimport { DefaultPubsubTopic } from \"@waku/interfaces\";\nimport { messageHashStr } from \"@waku/message-hash\";\nimport { WakuMessage } from \"@waku/proto\";\nimport {\n ensurePubsubTopicIsConfigured,\n groupByContentTopic,\n singleShardInfoToPubsubTopic,\n toAsyncIterator\n} from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\n\nimport { BaseProtocol } from \"../base_protocol.js\";\n\nimport {\n FilterPushRpc,\n FilterSubscribeResponse,\n FilterSubscribeRpc\n} from \"./filter_rpc.js\";\n\nconst log = new Logger(\"filter:v2\");\n\ntype SubscriptionCallback = {\n decoders: IDecoder[];\n callback: Callback;\n};\n\nexport const FilterCodecs = {\n SUBSCRIBE: \"/vac/waku/filter-subscribe/2.0.0-beta1\",\n PUSH: \"/vac/waku/filter-push/2.0.0-beta1\"\n};\n\n/**\n * A subscription object refers to a subscription to a given pubsub topic.\n */\nclass Subscription {\n readonly peers: Peer[];\n private readonly pubsubTopic: PubsubTopic;\n private newStream: (peer: Peer) => Promise;\n readonly receivedMessagesHashStr: string[] = [];\n\n private subscriptionCallbacks: Map<\n ContentTopic,\n SubscriptionCallback\n >;\n\n constructor(\n pubsubTopic: PubsubTopic,\n remotePeers: Peer[],\n newStream: (peer: Peer) => Promise\n ) {\n this.peers = remotePeers;\n this.pubsubTopic = pubsubTopic;\n this.newStream = newStream;\n this.subscriptionCallbacks = new Map();\n }\n\n async subscribe(\n decoders: IDecoder | IDecoder[],\n callback: Callback\n ): Promise {\n const decodersArray = Array.isArray(decoders) ? decoders : [decoders];\n\n // check that all decoders are configured for the same pubsub topic as this subscription\n decodersArray.forEach((decoder) => {\n if (decoder.pubsubTopic !== this.pubsubTopic) {\n throw new Error(\n `Pubsub topic not configured: decoder is configured for pubsub topic ${decoder.pubsubTopic} but this subscription is for pubsub topic ${this.pubsubTopic}. Please create a new Subscription for the different pubsub topic.`\n );\n }\n });\n\n const decodersGroupedByCT = groupByContentTopic(decodersArray);\n const contentTopics = Array.from(decodersGroupedByCT.keys());\n\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n\n const request = FilterSubscribeRpc.createSubscribeRequest(\n this.pubsubTopic,\n contentTopics\n );\n\n try {\n const res = await pipe(\n [request.encode()],\n lp.encode,\n stream,\n lp.decode,\n async (source) => await all(source)\n );\n\n if (!res || !res.length) {\n throw Error(\n `No response received for request ${request.requestId}: ${res}`\n );\n }\n\n const { statusCode, requestId, statusDesc } =\n FilterSubscribeResponse.decode(res[0].slice());\n\n if (statusCode < 200 || statusCode >= 300) {\n throw new Error(\n `Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`\n );\n }\n\n log.info(\n \"Subscribed to peer \",\n peer.id.toString(),\n \"for content topics\",\n contentTopics\n );\n } catch (e) {\n throw new Error(\n \"Error subscribing to peer: \" +\n peer.id.toString() +\n \" for content topics: \" +\n contentTopics +\n \": \" +\n e\n );\n }\n });\n\n const results = await Promise.allSettled(promises);\n\n this.handleErrors(results, \"subscribe\");\n\n // Save the callback functions by content topics so they\n // can easily be removed (reciprocally replaced) if `unsubscribe` (reciprocally `subscribe`)\n // is called for those content topics\n decodersGroupedByCT.forEach((decoders, contentTopic) => {\n // Cast the type because a given `subscriptionCallbacks` map may hold\n // Decoder that decode to different implementations of `IDecodedMessage`\n const subscriptionCallback = {\n decoders,\n callback\n } as unknown as SubscriptionCallback;\n\n // The callback and decoder may override previous values, this is on\n // purpose as the user may call `subscribe` to refresh the subscription\n this.subscriptionCallbacks.set(contentTopic, subscriptionCallback);\n });\n }\n\n async unsubscribe(contentTopics: ContentTopic[]): Promise {\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n const unsubscribeRequest = FilterSubscribeRpc.createUnsubscribeRequest(\n this.pubsubTopic,\n contentTopics\n );\n\n try {\n await pipe([unsubscribeRequest.encode()], lp.encode, stream.sink);\n } catch (error) {\n throw new Error(\"Error unsubscribing: \" + error);\n }\n\n contentTopics.forEach((contentTopic: string) => {\n this.subscriptionCallbacks.delete(contentTopic);\n });\n });\n\n const results = await Promise.allSettled(promises);\n\n this.handleErrors(results, \"unsubscribe\");\n }\n\n async ping(): Promise {\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n\n const request = FilterSubscribeRpc.createSubscriberPingRequest();\n\n try {\n const res = await pipe(\n [request.encode()],\n lp.encode,\n stream,\n lp.decode,\n async (source) => await all(source)\n );\n\n if (!res || !res.length) {\n throw Error(\n `No response received for request ${request.requestId}: ${res}`\n );\n }\n\n const { statusCode, requestId, statusDesc } =\n FilterSubscribeResponse.decode(res[0].slice());\n\n if (statusCode < 200 || statusCode >= 300) {\n throw new Error(\n `Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`\n );\n }\n log.info(`Ping successful for peer ${peer.id.toString()}`);\n } catch (error) {\n log.error(\"Error pinging: \", error);\n throw error; // Rethrow the actual error instead of wrapping it\n }\n });\n\n const results = await Promise.allSettled(promises);\n\n this.handleErrors(results, \"ping\");\n }\n\n async unsubscribeAll(): Promise {\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n\n const request = FilterSubscribeRpc.createUnsubscribeAllRequest(\n this.pubsubTopic\n );\n\n try {\n const res = await pipe(\n [request.encode()],\n lp.encode,\n stream,\n lp.decode,\n async (source) => await all(source)\n );\n\n if (!res || !res.length) {\n throw Error(\n `No response received for request ${request.requestId}: ${res}`\n );\n }\n\n const { statusCode, requestId, statusDesc } =\n FilterSubscribeResponse.decode(res[0].slice());\n\n if (statusCode < 200 || statusCode >= 300) {\n throw new Error(\n `Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`\n );\n }\n\n this.subscriptionCallbacks.clear();\n log.info(\n `Unsubscribed from all content topics for pubsub topic ${this.pubsubTopic}`\n );\n } catch (error) {\n throw new Error(\n \"Error unsubscribing from all content topics: \" + error\n );\n }\n });\n\n const results = await Promise.allSettled(promises);\n\n this.handleErrors(results, \"unsubscribeAll\");\n }\n\n async processMessage(message: WakuMessage): Promise {\n const hashedMessageStr = messageHashStr(\n this.pubsubTopic,\n message as IProtoMessage\n );\n if (this.receivedMessagesHashStr.includes(hashedMessageStr)) {\n log.info(\"Message already received, skipping\");\n return;\n }\n this.receivedMessagesHashStr.push(hashedMessageStr);\n\n const { contentTopic } = message;\n const subscriptionCallback = this.subscriptionCallbacks.get(contentTopic);\n if (!subscriptionCallback) {\n log.error(\"No subscription callback available for \", contentTopic);\n return;\n }\n log.info(\n \"Processing message with content topic \",\n contentTopic,\n \" on pubsub topic \",\n this.pubsubTopic\n );\n await pushMessage(subscriptionCallback, this.pubsubTopic, message);\n }\n\n // Filter out only the rejected promises and extract & handle their reasons\n private handleErrors(\n results: PromiseSettledResult[],\n type: \"ping\" | \"subscribe\" | \"unsubscribe\" | \"unsubscribeAll\"\n ): void {\n const errors = results\n .filter(\n (result): result is PromiseRejectedResult =>\n result.status === \"rejected\"\n )\n .map((rejectedResult) => rejectedResult.reason);\n\n if (errors.length === this.peers.length) {\n const errorCounts = new Map();\n // TODO: streamline error logging with https://github.com/orgs/waku-org/projects/2/views/1?pane=issue&itemId=42849952\n errors.forEach((error) => {\n const message = error instanceof Error ? error.message : String(error);\n errorCounts.set(message, (errorCounts.get(message) || 0) + 1);\n });\n\n const uniqueErrorMessages = Array.from(\n errorCounts,\n ([message, count]) => `${message} (occurred ${count} times)`\n ).join(\", \");\n throw new Error(`Error ${type} all peers: ${uniqueErrorMessages}`);\n } else if (errors.length > 0) {\n // TODO: handle renewing faulty peers with new peers (https://github.com/waku-org/js-waku/issues/1463)\n log.warn(\n `Some ${type} failed. These will be refreshed with new peers`,\n errors\n );\n } else {\n log.info(`${type} successful for all peers`);\n }\n }\n}\n\nconst DEFAULT_NUM_PEERS = 3;\n\nclass Filter extends BaseProtocol implements IReceiver {\n private activeSubscriptions = new Map();\n\n private getActiveSubscription(\n pubsubTopic: PubsubTopic\n ): Subscription | undefined {\n return this.activeSubscriptions.get(pubsubTopic);\n }\n\n private setActiveSubscription(\n pubsubTopic: PubsubTopic,\n subscription: Subscription\n ): Subscription {\n this.activeSubscriptions.set(pubsubTopic, subscription);\n return subscription;\n }\n\n //TODO: Remove when FilterCore and FilterSDK are introduced\n private readonly numPeersToUse: number;\n\n constructor(libp2p: Libp2p, options?: ProtocolCreateOptions) {\n super(\n FilterCodecs.SUBSCRIBE,\n libp2p.components,\n log,\n options!.pubsubTopics!,\n options\n );\n\n this.numPeersToUse = options?.numPeersToUse ?? DEFAULT_NUM_PEERS;\n\n libp2p.handle(FilterCodecs.PUSH, this.onRequest.bind(this)).catch((e) => {\n log.error(\"Failed to register \", FilterCodecs.PUSH, e);\n });\n\n this.activeSubscriptions = new Map();\n }\n\n /**\n * Creates a new subscription to the given pubsub topic.\n * The subscription is made to multiple peers for decentralization.\n * @param pubsubTopicShardInfo The pubsub topic to subscribe to.\n * @returns The subscription object.\n */\n async createSubscription(\n pubsubTopicShardInfo: SingleShardInfo | PubsubTopic = DefaultPubsubTopic\n ): Promise {\n const pubsubTopic =\n typeof pubsubTopicShardInfo == \"string\"\n ? pubsubTopicShardInfo\n : singleShardInfoToPubsubTopic(pubsubTopicShardInfo);\n\n ensurePubsubTopicIsConfigured(pubsubTopic, this.pubsubTopics);\n\n const peers = await this.getPeers({\n maxBootstrapPeers: 1,\n numPeers: this.numPeersToUse\n });\n if (peers.length === 0) {\n throw new Error(\"No peer found to initiate subscription.\");\n }\n\n log.info(\n `Creating filter subscription with ${peers.length} peers: `,\n peers.map((peer) => peer.id.toString())\n );\n\n const subscription =\n this.getActiveSubscription(pubsubTopic) ??\n this.setActiveSubscription(\n pubsubTopic,\n new Subscription(pubsubTopic, peers, this.getStream.bind(this))\n );\n\n return subscription;\n }\n\n public toSubscriptionIterator(\n decoders: IDecoder | IDecoder[]\n ): Promise> {\n return toAsyncIterator(this, decoders);\n }\n\n /**\n * This method is used to satisfy the `IReceiver` interface.\n *\n * @hidden\n *\n * @param decoders The decoders to use for the subscription.\n * @param callback The callback function to use for the subscription.\n * @param opts Optional protocol options for the subscription.\n *\n * @returns A Promise that resolves to a function that unsubscribes from the subscription.\n *\n * @remarks\n * This method should not be used directly.\n * Instead, use `createSubscription` to create a new subscription.\n */\n async subscribe(\n decoders: IDecoder | IDecoder[],\n callback: Callback\n ): Promise {\n const subscription = await this.createSubscription();\n\n await subscription.subscribe(decoders, callback);\n\n const contentTopics = Array.from(\n groupByContentTopic(\n Array.isArray(decoders) ? decoders : [decoders]\n ).keys()\n );\n\n return async () => {\n await subscription.unsubscribe(contentTopics);\n };\n }\n\n private onRequest(streamData: IncomingStreamData): void {\n const { connection, stream } = streamData;\n const { remotePeer } = connection;\n log.info(`Received message from ${remotePeer.toString()}`);\n try {\n pipe(stream, lp.decode, async (source) => {\n for await (const bytes of source) {\n const response = FilterPushRpc.decode(bytes.slice());\n\n const { pubsubTopic, wakuMessage } = response;\n\n if (!wakuMessage) {\n log.error(\"Received empty message\");\n return;\n }\n\n if (!pubsubTopic) {\n log.error(\"Pubsub topic missing from push message\");\n return;\n }\n\n const subscription = this.getActiveSubscription(pubsubTopic);\n\n if (!subscription) {\n log.error(\n `No subscription locally registered for topic ${pubsubTopic}`\n );\n return;\n }\n\n await subscription.processMessage(wakuMessage);\n }\n }).then(\n () => {\n log.info(\"Receiving pipe closed.\");\n },\n (e) => {\n log.error(\"Error with receiving pipe\", e);\n }\n );\n } catch (e) {\n log.error(\"Error decoding message\", e);\n }\n }\n}\n\nexport function wakuFilter(\n init: ProtocolCreateOptions = { pubsubTopics: [] }\n): (libp2p: Libp2p) => IFilter {\n return (libp2p: Libp2p) => new Filter(libp2p, init);\n}\n\nasync function pushMessage(\n subscriptionCallback: SubscriptionCallback,\n pubsubTopic: PubsubTopic,\n message: WakuMessage\n): Promise {\n const { decoders, callback } = subscriptionCallback;\n\n const { contentTopic } = message;\n if (!contentTopic) {\n log.warn(\"Message has no content topic, skipping\");\n return;\n }\n\n try {\n const decodePromises = decoders.map((dec) =>\n dec\n .fromProtoObj(pubsubTopic, message as IProtoMessage)\n .then((decoded) => decoded || Promise.reject(\"Decoding failed\"))\n );\n\n const decodedMessage = await Promise.any(decodePromises);\n\n await callback(decodedMessage);\n } catch (e) {\n log.error(\"Error decoding message\", e);\n }\n}\n","import { proto_lightpush as proto } from \"@waku/proto\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\nimport { v4 as uuid } from \"uuid\";\n\nexport class PushRpc {\n public constructor(public proto: proto.PushRpc) {}\n\n static createRequest(\n message: proto.WakuMessage,\n pubsubTopic: string\n ): PushRpc {\n return new PushRpc({\n requestId: uuid(),\n request: {\n message: message,\n pubsubTopic: pubsubTopic\n },\n response: undefined\n });\n }\n\n static decode(bytes: Uint8ArrayList): PushRpc {\n const res = proto.PushRpc.decode(bytes);\n return new PushRpc(res);\n }\n\n encode(): Uint8Array {\n return proto.PushRpc.encode(this.proto);\n }\n\n get query(): proto.PushRequest | undefined {\n return this.proto.request;\n }\n\n get response(): proto.PushResponse | undefined {\n return this.proto.response;\n }\n}\n","import type { Peer, PeerId, Stream } from \"@libp2p/interface\";\nimport {\n Failure,\n IBaseProtocolCore,\n IEncoder,\n IMessage,\n Libp2p,\n ProtocolCreateOptions,\n ProtocolError,\n ProtocolResult\n} from \"@waku/interfaces\";\nimport { PushResponse } from \"@waku/proto\";\nimport { isMessageSizeUnderCap } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\n\nimport { BaseProtocol } from \"../base_protocol.js\";\n\nimport { PushRpc } from \"./push_rpc.js\";\n\nconst log = new Logger(\"light-push\");\n\nexport const LightPushCodec = \"/vac/waku/lightpush/2.0.0-beta1\";\nexport { PushResponse };\n\ntype PreparePushMessageResult = ProtocolResult<\"query\", PushRpc>;\n\ntype CoreSendResult = ProtocolResult<\"success\", PeerId, \"failure\", Failure>;\n\n/**\n * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).\n */\nexport class LightPushCore extends BaseProtocol implements IBaseProtocolCore {\n constructor(libp2p: Libp2p, options?: ProtocolCreateOptions) {\n super(\n LightPushCodec,\n libp2p.components,\n log,\n options!.pubsubTopics!,\n options\n );\n }\n\n private async preparePushMessage(\n encoder: IEncoder,\n message: IMessage\n ): Promise {\n try {\n if (!message.payload || message.payload.length === 0) {\n log.error(\"Failed to send waku light push: payload is empty\");\n return { query: null, error: ProtocolError.EMPTY_PAYLOAD };\n }\n\n if (!(await isMessageSizeUnderCap(encoder, message))) {\n log.error(\"Failed to send waku light push: message is bigger than 1MB\");\n return { query: null, error: ProtocolError.SIZE_TOO_BIG };\n }\n\n const protoMessage = await encoder.toProtoObj(message);\n if (!protoMessage) {\n log.error(\"Failed to encode to protoMessage, aborting push\");\n return {\n query: null,\n error: ProtocolError.ENCODE_FAILED\n };\n }\n\n const query = PushRpc.createRequest(protoMessage, encoder.pubsubTopic);\n return { query, error: null };\n } catch (error) {\n log.error(\"Failed to prepare push message\", error);\n\n return {\n query: null,\n error: ProtocolError.GENERIC_FAIL\n };\n }\n }\n\n async send(\n encoder: IEncoder,\n message: IMessage,\n peer: Peer\n ): Promise {\n const { query, error: preparationError } = await this.preparePushMessage(\n encoder,\n message\n );\n\n if (preparationError || !query) {\n return {\n success: null,\n failure: {\n error: preparationError,\n peerId: peer.id\n }\n };\n }\n\n let stream: Stream | undefined;\n try {\n stream = await this.getStream(peer);\n } catch (err) {\n log.error(\n `Failed to get a stream for remote peer${peer.id.toString()}`,\n err\n );\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_FAULT,\n peerId: peer.id\n }\n };\n }\n\n let res: Uint8ArrayList[] | undefined;\n try {\n res = await pipe(\n [query.encode()],\n lp.encode,\n stream,\n lp.decode,\n async (source) => await all(source)\n );\n } catch (err) {\n log.error(\"Failed to send waku light push request\", err);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n\n let response: PushResponse | undefined;\n try {\n response = PushRpc.decode(bytes).response;\n } catch (err) {\n log.error(\"Failed to decode push reply\", err);\n return {\n success: null,\n failure: {\n error: ProtocolError.DECODE_FAILED,\n peerId: peer.id\n }\n };\n }\n\n if (!response) {\n log.error(\"Remote peer fault: No response in PushRPC\");\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_FAULT,\n peerId: peer.id\n }\n };\n }\n\n if (!response.isSuccess) {\n log.error(\"Remote peer rejected the message: \", response.info);\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n }\n };\n }\n\n return { success: peer.id, failure: null };\n }\n}\n","import { IProtoMessage } from \"@waku/interfaces\";\nimport { WakuMessage as WakuMessageProto } from \"@waku/proto\";\n\nconst EmptyMessage: IProtoMessage = {\n payload: new Uint8Array(),\n contentTopic: \"\",\n version: undefined,\n timestamp: undefined,\n meta: undefined,\n rateLimitProof: undefined,\n ephemeral: undefined\n};\n\nexport function toProtoMessage(wire: WakuMessageProto): IProtoMessage {\n return { ...EmptyMessage, ...wire };\n}\n","import { proto_store as proto } from \"@waku/proto\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\nimport { v4 as uuid } from \"uuid\";\n\nconst OneMillion = BigInt(1_000_000);\n\nexport enum PageDirection {\n BACKWARD = \"backward\",\n FORWARD = \"forward\"\n}\n\nexport interface Params {\n contentTopics: string[];\n pubsubTopic: string;\n pageDirection: PageDirection;\n pageSize: number;\n startTime?: Date;\n endTime?: Date;\n cursor?: proto.Index;\n}\n\nexport class HistoryRpc {\n private constructor(public readonly proto: proto.HistoryRpc) {}\n\n get query(): proto.HistoryQuery | undefined {\n return this.proto.query;\n }\n\n get response(): proto.HistoryResponse | undefined {\n return this.proto.response;\n }\n\n /**\n * Create History Query.\n */\n static createQuery(params: Params): HistoryRpc {\n const contentFilters = params.contentTopics.map((contentTopic) => {\n return { contentTopic };\n });\n\n const direction = directionToProto(params.pageDirection);\n\n const pagingInfo = {\n pageSize: BigInt(params.pageSize),\n cursor: params.cursor,\n direction\n } as proto.PagingInfo;\n\n let startTime, endTime;\n if (params.startTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n startTime = BigInt(params.startTime.valueOf()) * OneMillion;\n }\n\n if (params.endTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n endTime = BigInt(params.endTime.valueOf()) * OneMillion;\n }\n return new HistoryRpc({\n requestId: uuid(),\n query: {\n pubsubTopic: params.pubsubTopic,\n contentFilters,\n pagingInfo,\n startTime,\n endTime\n },\n response: undefined\n });\n }\n\n decode(bytes: Uint8ArrayList): HistoryRpc {\n const res = proto.HistoryRpc.decode(bytes);\n return new HistoryRpc(res);\n }\n\n encode(): Uint8Array {\n return proto.HistoryRpc.encode(this.proto);\n }\n}\n\nfunction directionToProto(\n pageDirection: PageDirection\n): proto.PagingInfo.Direction {\n switch (pageDirection) {\n case PageDirection.BACKWARD:\n return proto.PagingInfo.Direction.BACKWARD;\n case PageDirection.FORWARD:\n return proto.PagingInfo.Direction.FORWARD;\n default:\n return proto.PagingInfo.Direction.BACKWARD;\n }\n}\n","import type { Peer } from \"@libp2p/interface\";\nimport {\n Cursor,\n IDecodedMessage,\n IDecoder,\n IStoreCore,\n Libp2p,\n ProtocolCreateOptions\n} from \"@waku/interfaces\";\nimport { proto_store as proto } from \"@waku/proto\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\n\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { toProtoMessage } from \"../to_proto_message.js\";\n\nimport { HistoryRpc, PageDirection, Params } from \"./history_rpc.js\";\n\nimport HistoryError = proto.HistoryResponse.HistoryError;\n\nconst log = new Logger(\"store\");\n\nexport const StoreCodec = \"/vac/waku/store/2.0.0-beta4\";\n\nexport { PageDirection, Params };\n\nexport interface TimeFilter {\n startTime: Date;\n endTime: Date;\n}\n\nexport interface QueryOptions {\n /**\n * The direction in which pages are retrieved:\n * - { @link PageDirection.BACKWARD }: Most recent page first.\n * - { @link PageDirection.FORWARD }: Oldest page first.\n *\n * Note: This does not affect the ordering of messages with the page\n * (the oldest message is always first).\n *\n * @default { @link PageDirection.BACKWARD }\n */\n pageDirection?: PageDirection;\n /**\n * The number of message per page.\n *\n * @default { @link DefaultPageSize }\n */\n pageSize?: number;\n /**\n * Retrieve messages with a timestamp within the provided values.\n */\n timeFilter?: TimeFilter;\n /**\n * Cursor as an index to start a query from.\n * The cursor index will be exclusive (i.e. the message at the cursor index will not be included in the result).\n * If undefined, the query will start from the beginning or end of the history, depending on the page direction.\n */\n cursor?: Cursor;\n}\n\n/**\n * Implements the [Waku v2 Store protocol](https://rfc.vac.dev/spec/13/).\n *\n * The Waku Store protocol can be used to retrieved historical messages.\n */\nexport class StoreCore extends BaseProtocol implements IStoreCore {\n constructor(libp2p: Libp2p, options?: ProtocolCreateOptions) {\n super(StoreCodec, libp2p.components, log, options!.pubsubTopics!, options);\n }\n\n async *queryPerPage(\n queryOpts: Params,\n decoders: Map>,\n peer: Peer\n ): AsyncGenerator[]> {\n if (\n queryOpts.contentTopics.toString() !==\n Array.from(decoders.keys()).toString()\n ) {\n throw new Error(\n \"Internal error, the decoders should match the query's content topics\"\n );\n }\n\n let currentCursor = queryOpts.cursor;\n while (true) {\n queryOpts.cursor = currentCursor;\n\n const historyRpcQuery = HistoryRpc.createQuery(queryOpts);\n\n const stream = await this.getStream(peer);\n\n const res = await pipe(\n [historyRpcQuery.encode()],\n lp.encode,\n stream,\n lp.decode,\n async (source) => await all(source)\n );\n\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n\n const reply = historyRpcQuery.decode(bytes);\n\n if (!reply.response) {\n log.warn(\"Stopping pagination due to store `response` field missing\");\n break;\n }\n\n const response = reply.response as proto.HistoryResponse;\n\n if (response.error && response.error !== HistoryError.NONE) {\n throw \"History response contains an Error: \" + response.error;\n }\n\n if (!response.messages || !response.messages.length) {\n log.warn(\n \"Stopping pagination due to store `response.messages` field missing or empty\"\n );\n break;\n }\n\n log.error(`${response.messages.length} messages retrieved from store`);\n\n yield response.messages.map((protoMsg) => {\n const contentTopic = protoMsg.contentTopic;\n if (typeof contentTopic !== \"undefined\") {\n const decoder = decoders.get(contentTopic);\n if (decoder) {\n return decoder.fromProtoObj(\n queryOpts.pubsubTopic,\n toProtoMessage(protoMsg)\n );\n }\n }\n return Promise.resolve(undefined);\n });\n\n const nextCursor = response.pagingInfo?.cursor;\n if (typeof nextCursor === \"undefined\") {\n // If the server does not return cursor then there is an issue,\n // Need to abort, or we end up in an infinite loop\n log.warn(\n \"Stopping pagination due to `response.pagingInfo.cursor` missing from store response\"\n );\n break;\n }\n\n currentCursor = nextCursor;\n\n const responsePageSize = response.pagingInfo?.pageSize;\n const queryPageSize = historyRpcQuery.query?.pagingInfo?.pageSize;\n if (\n // Response page size smaller than query, meaning this is the last page\n responsePageSize &&\n queryPageSize &&\n responsePageSize < queryPageSize\n ) {\n break;\n }\n }\n }\n}\n","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.addEventListener || emitter.on || emitter.addListener;\n\tconst removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\t\tif (options.filter && !options.filter(value)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = error => {\n\t\t\tcancel();\n\t\t\treject(error);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener('abort', () => {\n\t\t\t\trejectHandler(options.signal.reason);\n\t\t\t}, {once: true});\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\ttimeout.cancel = cancel;\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]);\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\tif (options.filter && !options.filter(value)) {\n\t\t\tcancel();\n\t\t\treturn;\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\tif (options.signal) {\n\t\toptions.signal.addEventListener('abort', () => {\n\t\t\trejectHandler(options.signal.reason);\n\t\t}, {once: true});\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n","import type { IdentifyResult } from \"@libp2p/interface\";\nimport type {\n IBaseProtocolCore,\n IMetadata,\n IRelay,\n Waku\n} from \"@waku/interfaces\";\nimport { Protocols } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport { pEvent } from \"p-event\";\nconst log = new Logger(\"wait-for-remote-peer\");\n\n//TODO: move this function within the Waku class: https://github.com/waku-org/js-waku/issues/1761\n/**\n * Wait for a remote peer to be ready given the passed protocols.\n * Must be used after attempting to connect to nodes, using\n * {@link @waku/sdk!WakuNode.dial} or a bootstrap method with\n * {@link @waku/sdk!createLightNode}.\n *\n * If the passed protocols is a GossipSub protocol, then it resolves only once\n * a peer is in a mesh, to help ensure that other peers will send and receive\n * message to us.\n *\n * @param waku The Waku Node\n * @param protocols The protocols that need to be enabled by remote peers.\n * @param timeoutMs A timeout value in milliseconds..\n *\n * @returns A promise that **resolves** if all desired protocols are fulfilled by\n * remote nodes, **rejects** if the timeoutMs is reached.\n * @throws If passing a protocol that is not mounted\n * @default Wait for remote peers with protocols enabled locally and no time out is applied.\n */\nexport async function waitForRemotePeer(\n waku: Waku,\n protocols?: Protocols[],\n timeoutMs?: number\n): Promise {\n protocols = protocols ?? getEnabledProtocols(waku);\n\n if (!waku.isStarted()) return Promise.reject(\"Waku node is not started\");\n\n const promises = [];\n\n if (protocols.includes(Protocols.Relay)) {\n if (!waku.relay)\n throw new Error(\"Cannot wait for Relay peer: protocol not mounted\");\n promises.push(waitForGossipSubPeerInMesh(waku.relay));\n }\n\n if (protocols.includes(Protocols.Store)) {\n if (!waku.store)\n throw new Error(\"Cannot wait for Store peer: protocol not mounted\");\n promises.push(\n waitForConnectedPeer(waku.store.protocol, waku.libp2p.services.metadata)\n );\n }\n\n if (protocols.includes(Protocols.LightPush)) {\n if (!waku.lightPush)\n throw new Error(\"Cannot wait for LightPush peer: protocol not mounted\");\n promises.push(\n waitForConnectedPeer(\n waku.lightPush.protocol,\n waku.libp2p.services.metadata\n )\n );\n }\n\n if (protocols.includes(Protocols.Filter)) {\n if (!waku.filter)\n throw new Error(\"Cannot wait for Filter peer: protocol not mounted\");\n promises.push(\n waitForConnectedPeer(waku.filter, waku.libp2p.services.metadata)\n );\n }\n\n if (timeoutMs) {\n await rejectOnTimeout(\n Promise.all(promises),\n timeoutMs,\n \"Timed out waiting for a remote peer.\"\n );\n } else {\n await Promise.all(promises);\n }\n}\n\n//TODO: move this function within protocol SDK class: https://github.com/waku-org/js-waku/issues/1761\n/**\n * Wait for a peer with the given protocol to be connected.\n * If sharding is enabled on the node, it will also wait for the peer to be confirmed by the metadata service.\n */\nasync function waitForConnectedPeer(\n protocol: IBaseProtocolCore,\n metadataService?: IMetadata\n): Promise {\n const codec = protocol.multicodec;\n const peers = await protocol.connectedPeers();\n\n if (peers.length) {\n if (!metadataService) {\n log.info(`${codec} peer found: `, peers[0].id.toString());\n return;\n }\n\n // once a peer is connected, we need to confirm the metadata handshake with at least one of those peers if sharding is enabled\n try {\n await Promise.any(\n peers.map((peer) => metadataService.confirmOrAttemptHandshake(peer.id))\n );\n return;\n } catch (e) {\n if ((e as any).code === \"ERR_CONNECTION_BEING_CLOSED\")\n log.error(\n `Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`\n );\n\n log.error(`Error waiting for handshake confirmation: ${e}`);\n }\n }\n\n log.info(`Waiting for ${codec} peer`);\n\n // else we'll just wait for the next peer to connect\n await new Promise((resolve) => {\n const cb = (evt: CustomEvent): void => {\n if (evt.detail?.protocols?.includes(codec)) {\n if (metadataService) {\n metadataService\n .confirmOrAttemptHandshake(evt.detail.peerId)\n .then(() => {\n protocol.removeLibp2pEventListener(\"peer:identify\", cb);\n resolve();\n })\n .catch((e) => {\n if (e.code === \"ERR_CONNECTION_BEING_CLOSED\")\n log.error(\n `Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`\n );\n\n log.error(`Error waiting for handshake confirmation: ${e}`);\n });\n } else {\n protocol.removeLibp2pEventListener(\"peer:identify\", cb);\n resolve();\n }\n }\n };\n protocol.addLibp2pEventListener(\"peer:identify\", cb);\n });\n}\n\n/**\n * Wait for at least one peer with the given protocol to be connected and in the gossipsub\n * mesh for all pubsubTopics.\n */\nasync function waitForGossipSubPeerInMesh(waku: IRelay): Promise {\n let peers = waku.getMeshPeers();\n const pubsubTopics = waku.pubsubTopics;\n\n for (const topic of pubsubTopics) {\n while (peers.length == 0) {\n await pEvent(waku.gossipSub, \"gossipsub:heartbeat\");\n peers = waku.getMeshPeers(topic);\n }\n }\n}\n\nconst awaitTimeout = (ms: number, rejectReason: string): Promise =>\n new Promise((_resolve, reject) => setTimeout(() => reject(rejectReason), ms));\n\nasync function rejectOnTimeout(\n promise: Promise,\n timeoutMs: number,\n rejectReason: string\n): Promise {\n await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);\n}\n\nfunction getEnabledProtocols(waku: Waku): Protocols[] {\n const protocols = [];\n\n if (waku.relay) {\n protocols.push(Protocols.Relay);\n }\n\n if (waku.filter) {\n protocols.push(Protocols.Filter);\n }\n\n if (waku.store) {\n protocols.push(Protocols.Store);\n }\n\n if (waku.lightPush) {\n protocols.push(Protocols.LightPush);\n }\n\n return protocols;\n}\n","import { setMaxListeners as nodeSetMaxListeners } from 'events'\n\n// create a setMaxListeners that doesn't break browser usage\nexport const setMaxListeners: typeof nodeSetMaxListeners = (n, ...eventTargets) => {\n try {\n nodeSetMaxListeners(n, ...eventTargets)\n } catch {\n // swallow error, gulp\n }\n}\n","import { setMaxListeners } from './events.js'\n\nexport interface EventCallback { (evt: EventType): void }\nexport interface EventObject { handleEvent: EventCallback }\nexport type EventHandler = EventCallback | EventObject\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n * Adds types to the EventTarget class. Hopefully this won't be necessary forever.\n *\n * https://github.com/microsoft/TypeScript/issues/28357\n * https://github.com/microsoft/TypeScript/issues/43477\n * https://github.com/microsoft/TypeScript/issues/299\n * etc\n */\nexport interface TypedEventTarget > extends EventTarget {\n addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void\n\n listenerCount (type: string): number\n\n removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void\n\n removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void\n\n safeDispatchEvent(type: keyof EventMap, detail: CustomEventInit): boolean\n}\n\n/**\n * An implementation of a typed event target\n * etc\n */\nexport class TypedEventEmitter> extends EventTarget implements TypedEventTarget {\n #listeners = new Map()\n\n constructor () {\n super()\n\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this)\n }\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n\n safeDispatchEvent(type: keyof EventMap, detail: CustomEventInit = {}): boolean {\n return this.dispatchEvent(new CustomEvent(type as string, detail))\n }\n}\n\n/**\n * CustomEvent is a standard event but it's not supported by node.\n *\n * Remove this when https://github.com/nodejs/node/issues/40678 is closed.\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n */\nclass CustomEventPolyfill extends Event {\n /** Returns any custom data event was created with. Typically used for synthetic events. */\n public detail: T\n\n constructor (message: string, data?: EventInit & { detail: T }) {\n super(message, data)\n // @ts-expect-error could be undefined\n this.detail = data?.detail\n }\n}\n\nexport const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill\n","import type { PeerId, PeerStore } from \"@libp2p/interface\";\nimport type { PingService } from \"@libp2p/ping\";\nimport type { IRelay, PeerIdStr } from \"@waku/interfaces\";\nimport type { KeepAliveOptions } from \"@waku/interfaces\";\nimport { Logger, pubsubTopicToSingleShardInfo } from \"@waku/utils\";\nimport { utf8ToBytes } from \"@waku/utils/bytes\";\n\nimport { createEncoder } from \"./message/version_0.js\";\n\nexport const RelayPingContentTopic = \"/relay-ping/1/ping/null\";\nconst log = new Logger(\"keep-alive\");\n\nexport class KeepAliveManager {\n private pingKeepAliveTimers: Map>;\n private relayKeepAliveTimers: Map[]>;\n private options: KeepAliveOptions;\n private relay?: IRelay;\n\n constructor(options: KeepAliveOptions, relay?: IRelay) {\n this.pingKeepAliveTimers = new Map();\n this.relayKeepAliveTimers = new Map();\n this.options = options;\n this.relay = relay;\n }\n\n public start(\n peerId: PeerId,\n libp2pPing: PingService,\n peerStore: PeerStore\n ): void {\n // Just in case a timer already exists for this peer\n this.stop(peerId);\n\n const { pingKeepAlive: pingPeriodSecs, relayKeepAlive: relayPeriodSecs } =\n this.options;\n\n const peerIdStr = peerId.toString();\n\n // Ping the peer every pingPeriodSecs seconds\n // if pingPeriodSecs is 0, don't ping the peer\n if (pingPeriodSecs !== 0) {\n const interval = setInterval(() => {\n void (async () => {\n let ping: number;\n try {\n // ping the peer for keep alive\n // also update the peer store with the latency\n try {\n ping = await libp2pPing.ping(peerId);\n log.info(`Ping succeeded (${peerIdStr})`, ping);\n } catch (error) {\n log.error(`Ping failed for peer (${peerIdStr}).\n Next ping will be attempted in ${pingPeriodSecs} seconds.\n `);\n return;\n }\n\n try {\n await peerStore.patch(peerId, {\n metadata: {\n ping: utf8ToBytes(ping.toString())\n }\n });\n } catch (e) {\n log.error(\"Failed to update ping\", e);\n }\n } catch (e) {\n log.error(`Ping failed (${peerIdStr})`, e);\n }\n })();\n }, pingPeriodSecs * 1000);\n\n this.pingKeepAliveTimers.set(peerIdStr, interval);\n }\n\n const relay = this.relay;\n if (relay && relayPeriodSecs !== 0) {\n const intervals = this.scheduleRelayPings(\n relay,\n relayPeriodSecs,\n peerId.toString()\n );\n this.relayKeepAliveTimers.set(peerId, intervals);\n }\n }\n\n public stop(peerId: PeerId): void {\n const peerIdStr = peerId.toString();\n\n if (this.pingKeepAliveTimers.has(peerIdStr)) {\n clearInterval(this.pingKeepAliveTimers.get(peerIdStr));\n this.pingKeepAliveTimers.delete(peerIdStr);\n }\n\n if (this.relayKeepAliveTimers.has(peerId)) {\n this.relayKeepAliveTimers.get(peerId)?.map(clearInterval);\n this.relayKeepAliveTimers.delete(peerId);\n }\n }\n\n public stopAll(): void {\n for (const timer of [\n ...Object.values(this.pingKeepAliveTimers),\n ...Object.values(this.relayKeepAliveTimers)\n ]) {\n clearInterval(timer);\n }\n\n this.pingKeepAliveTimers.clear();\n this.relayKeepAliveTimers.clear();\n }\n\n public connectionsExist(): boolean {\n return (\n this.pingKeepAliveTimers.size > 0 || this.relayKeepAliveTimers.size > 0\n );\n }\n\n private scheduleRelayPings(\n relay: IRelay,\n relayPeriodSecs: number,\n peerIdStr: PeerIdStr\n ): NodeJS.Timeout[] {\n // send a ping message to each PubsubTopic the peer is part of\n const intervals: NodeJS.Timeout[] = [];\n for (const topic of relay.pubsubTopics) {\n const meshPeers = relay.getMeshPeers(topic);\n if (!meshPeers.includes(peerIdStr)) continue;\n\n const encoder = createEncoder({\n pubsubTopicShardInfo: pubsubTopicToSingleShardInfo(topic),\n contentTopic: RelayPingContentTopic,\n ephemeral: true\n });\n const interval = setInterval(() => {\n log.info(\"Sending Waku Relay ping message\");\n relay\n .send(encoder, { payload: new Uint8Array([1]) })\n .catch((e) => log.error(\"Failed to send relay ping\", e));\n }, relayPeriodSecs * 1000);\n intervals.push(interval);\n }\n\n return intervals;\n }\n}\n","import type { Peer, PeerId, PeerInfo, PeerStore } from \"@libp2p/interface\";\nimport { CustomEvent, TypedEventEmitter } from \"@libp2p/interface\";\nimport {\n ConnectionManagerOptions,\n EConnectionStateEvents,\n EPeersByDiscoveryEvents,\n IConnectionManager,\n IConnectionStateEvents,\n IPeersByDiscoveryEvents,\n IRelay,\n KeepAliveOptions,\n PeersByDiscoveryResult,\n PubsubTopic,\n ShardInfo\n} from \"@waku/interfaces\";\nimport { Libp2p, Tags } from \"@waku/interfaces\";\nimport { decodeRelayShard, shardInfoToPubsubTopics } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\n\nimport { KeepAliveManager } from \"./keep_alive_manager.js\";\n\nconst log = new Logger(\"connection-manager\");\n\nexport const DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED = 1;\nexport const DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER = 3;\nexport const DEFAULT_MAX_PARALLEL_DIALS = 3;\n\nexport class ConnectionManager\n extends TypedEventEmitter\n implements IConnectionManager\n{\n private static instances = new Map();\n private keepAliveManager: KeepAliveManager;\n private options: ConnectionManagerOptions;\n private libp2p: Libp2p;\n private dialAttemptsForPeer: Map = new Map();\n private dialErrorsForPeer: Map = new Map();\n\n private currentActiveParallelDialCount = 0;\n private pendingPeerDialQueue: Array = [];\n private online: boolean = false;\n\n public isConnected(): boolean {\n return this.online;\n }\n\n private toggleOnline(): void {\n if (!this.online) {\n this.online = true;\n this.dispatchEvent(\n new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS, {\n detail: this.online\n })\n );\n }\n }\n\n private toggleOffline(): void {\n if (this.online && this.libp2p.getConnections().length == 0) {\n this.online = false;\n this.dispatchEvent(\n new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS, {\n detail: this.online\n })\n );\n }\n }\n\n public static create(\n peerId: string,\n libp2p: Libp2p,\n keepAliveOptions: KeepAliveOptions,\n pubsubTopics: PubsubTopic[],\n relay?: IRelay,\n options?: ConnectionManagerOptions\n ): ConnectionManager {\n let instance = ConnectionManager.instances.get(peerId);\n if (!instance) {\n instance = new ConnectionManager(\n libp2p,\n keepAliveOptions,\n pubsubTopics,\n relay,\n options\n );\n ConnectionManager.instances.set(peerId, instance);\n }\n\n return instance;\n }\n\n public async getPeersByDiscovery(): Promise {\n const peersDiscovered = await this.libp2p.peerStore.all();\n const peersConnected = this.libp2p\n .getConnections()\n .map((conn) => conn.remotePeer);\n\n const peersDiscoveredByBootstrap: Peer[] = [];\n const peersDiscoveredByPeerExchange: Peer[] = [];\n const peersDiscoveredByLocal: Peer[] = [];\n\n const peersConnectedByBootstrap: Peer[] = [];\n const peersConnectedByPeerExchange: Peer[] = [];\n const peersConnectedByLocal: Peer[] = [];\n\n for (const peer of peersDiscovered) {\n const tags = await this.getTagNamesForPeer(peer.id);\n\n if (tags.includes(Tags.BOOTSTRAP)) {\n peersDiscoveredByBootstrap.push(peer);\n } else if (tags.includes(Tags.PEER_EXCHANGE)) {\n peersDiscoveredByPeerExchange.push(peer);\n } else if (tags.includes(Tags.LOCAL)) {\n peersDiscoveredByLocal.push(peer);\n }\n }\n\n for (const peerId of peersConnected) {\n const peer = await this.libp2p.peerStore.get(peerId);\n const tags = await this.getTagNamesForPeer(peerId);\n\n if (tags.includes(Tags.BOOTSTRAP)) {\n peersConnectedByBootstrap.push(peer);\n } else if (tags.includes(Tags.PEER_EXCHANGE)) {\n peersConnectedByPeerExchange.push(peer);\n } else if (tags.includes(Tags.LOCAL)) {\n peersConnectedByLocal.push(peer);\n }\n }\n\n return {\n DISCOVERED: {\n [Tags.BOOTSTRAP]: peersDiscoveredByBootstrap,\n [Tags.PEER_EXCHANGE]: peersDiscoveredByPeerExchange,\n [Tags.LOCAL]: peersDiscoveredByLocal\n },\n CONNECTED: {\n [Tags.BOOTSTRAP]: peersConnectedByBootstrap,\n [Tags.PEER_EXCHANGE]: peersConnectedByPeerExchange,\n [Tags.LOCAL]: peersConnectedByLocal\n }\n };\n }\n\n private constructor(\n libp2p: Libp2p,\n keepAliveOptions: KeepAliveOptions,\n private configuredPubsubTopics: PubsubTopic[],\n relay?: IRelay,\n options?: Partial\n ) {\n super();\n this.libp2p = libp2p;\n this.configuredPubsubTopics = configuredPubsubTopics;\n this.options = {\n maxDialAttemptsForPeer: DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER,\n maxBootstrapPeersAllowed: DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,\n maxParallelDials: DEFAULT_MAX_PARALLEL_DIALS,\n ...options\n };\n\n this.keepAliveManager = new KeepAliveManager(keepAliveOptions, relay);\n\n this.run()\n .then(() => log.info(`Connection Manager is now running`))\n .catch((error) =>\n log.error(`Unexpected error while running service`, error)\n );\n\n // libp2p emits `peer:discovery` events during its initialization\n // which means that before the ConnectionManager is initialized, some peers may have been discovered\n // we will dial the peers in peerStore ONCE before we start to listen to the `peer:discovery` events within the ConnectionManager\n this.dialPeerStorePeers().catch((error) =>\n log.error(`Unexpected error while dialing peer store peers`, error)\n );\n }\n\n private async dialPeerStorePeers(): Promise {\n const peerInfos = await this.libp2p.peerStore.all();\n const dialPromises = [];\n for (const peerInfo of peerInfos) {\n if (\n this.libp2p.getConnections().find((c) => c.remotePeer === peerInfo.id)\n )\n continue;\n\n dialPromises.push(this.attemptDial(peerInfo.id));\n }\n try {\n await Promise.all(dialPromises);\n } catch (error) {\n log.error(`Unexpected error while dialing peer store peers`, error);\n }\n }\n\n private async run(): Promise {\n // start event listeners\n this.startPeerDiscoveryListener();\n this.startPeerConnectionListener();\n this.startPeerDisconnectionListener();\n }\n\n stop(): void {\n this.keepAliveManager.stopAll();\n this.libp2p.removeEventListener(\n \"peer:connect\",\n this.onEventHandlers[\"peer:connect\"]\n );\n this.libp2p.removeEventListener(\n \"peer:disconnect\",\n this.onEventHandlers[\"peer:disconnect\"]\n );\n this.libp2p.removeEventListener(\n \"peer:discovery\",\n this.onEventHandlers[\"peer:discovery\"]\n );\n }\n\n private async dialPeer(peerId: PeerId): Promise {\n this.currentActiveParallelDialCount += 1;\n let dialAttempt = 0;\n while (dialAttempt < this.options.maxDialAttemptsForPeer) {\n try {\n log.info(\n `Dialing peer ${peerId.toString()} on attempt ${dialAttempt + 1}`\n );\n await this.libp2p.dial(peerId);\n\n const tags = await this.getTagNamesForPeer(peerId);\n // add tag to connection describing discovery mechanism\n // don't add duplicate tags\n this.libp2p.getConnections(peerId).forEach((conn) => {\n conn.tags = Array.from(new Set([...conn.tags, ...tags]));\n });\n\n // instead of deleting the peer from the peer store, we set the dial attempt to -1\n // this helps us keep track of peers that have been dialed before\n this.dialAttemptsForPeer.set(peerId.toString(), -1);\n\n // Dialing succeeded, break the loop\n break;\n } catch (error) {\n if (error instanceof AggregateError) {\n // Handle AggregateError\n log.error(\n `Error dialing peer ${peerId.toString()} - ${error.errors}`\n );\n } else {\n // Handle generic error\n log.error(\n `Error dialing peer ${peerId.toString()} - ${\n (error as any).message\n }`\n );\n }\n this.dialErrorsForPeer.set(peerId.toString(), error);\n\n dialAttempt++;\n this.dialAttemptsForPeer.set(peerId.toString(), dialAttempt);\n }\n }\n\n // Always decrease the active dial count and process the dial queue\n this.currentActiveParallelDialCount--;\n this.processDialQueue();\n\n // If max dial attempts reached and dialing failed, delete the peer\n if (dialAttempt === this.options.maxDialAttemptsForPeer) {\n try {\n const error = this.dialErrorsForPeer.get(peerId.toString());\n\n if (error) {\n let errorMessage;\n if (error instanceof AggregateError) {\n if (!error.errors) {\n log.warn(`No errors array found for AggregateError`);\n } else if (error.errors.length === 0) {\n log.warn(`Errors array is empty for AggregateError`);\n } else {\n errorMessage = JSON.stringify(error.errors[0]);\n }\n } else {\n errorMessage = error.message;\n }\n\n log.info(\n `Deleting undialable peer ${peerId.toString()} from peer store. Reason: ${errorMessage}`\n );\n }\n\n this.dialErrorsForPeer.delete(peerId.toString());\n await this.libp2p.peerStore.delete(peerId);\n } catch (error) {\n throw new Error(\n `Error deleting undialable peer ${peerId.toString()} from peer store - ${error}`\n );\n }\n }\n }\n\n private async dropConnection(peerId: PeerId): Promise {\n try {\n this.keepAliveManager.stop(peerId);\n await this.libp2p.hangUp(peerId);\n log.info(`Dropped connection with peer ${peerId.toString()}`);\n } catch (error) {\n log.error(\n `Error dropping connection with peer ${peerId.toString()} - ${error}`\n );\n }\n }\n\n private processDialQueue(): void {\n if (\n this.pendingPeerDialQueue.length > 0 &&\n this.currentActiveParallelDialCount < this.options.maxParallelDials\n ) {\n const peerId = this.pendingPeerDialQueue.shift();\n if (!peerId) return;\n this.attemptDial(peerId).catch((error) => {\n log.error(error);\n });\n }\n }\n\n private startPeerDiscoveryListener(): void {\n this.libp2p.addEventListener(\n \"peer:discovery\",\n this.onEventHandlers[\"peer:discovery\"]\n );\n }\n\n private startPeerConnectionListener(): void {\n this.libp2p.addEventListener(\n \"peer:connect\",\n this.onEventHandlers[\"peer:connect\"]\n );\n }\n\n private startPeerDisconnectionListener(): void {\n // TODO: ensure that these following issues are updated and confirmed\n /**\n * NOTE: Event is not being emitted on closing nor losing a connection.\n * @see https://github.com/libp2p/js-libp2p/issues/939\n * @see https://github.com/status-im/js-waku/issues/252\n *\n * >This event will be triggered anytime we are disconnected from another peer,\n * >regardless of the circumstances of that disconnection.\n * >If we happen to have multiple connections to a peer,\n * >this event will **only** be triggered when the last connection is closed.\n * @see https://github.com/libp2p/js-libp2p/blob/bad9e8c0ff58d60a78314077720c82ae331cc55b/doc/API.md?plain=1#L2100\n */\n this.libp2p.addEventListener(\n \"peer:disconnect\",\n this.onEventHandlers[\"peer:disconnect\"]\n );\n }\n\n private async attemptDial(peerId: PeerId): Promise {\n if (!(await this.shouldDialPeer(peerId))) return;\n\n if (this.currentActiveParallelDialCount >= this.options.maxParallelDials) {\n this.pendingPeerDialQueue.push(peerId);\n return;\n }\n\n this.dialPeer(peerId).catch((err) => {\n log.error(`Error dialing peer ${peerId.toString()} : ${err}`);\n });\n }\n\n private onEventHandlers = {\n \"peer:discovery\": (evt: CustomEvent): void => {\n void (async () => {\n const { id: peerId } = evt.detail;\n\n await this.dispatchDiscoveryEvent(peerId);\n\n try {\n await this.attemptDial(peerId);\n } catch (error) {\n log.error(`Error dialing peer ${peerId.toString()} : ${error}`);\n }\n })();\n },\n \"peer:connect\": (evt: CustomEvent): void => {\n void (async () => {\n log.info(`Connected to peer ${evt.detail.toString()}`);\n\n const peerId = evt.detail;\n\n this.keepAliveManager.start(\n peerId,\n this.libp2p.services.ping,\n this.libp2p.peerStore\n );\n\n const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(\n Tags.BOOTSTRAP\n );\n\n if (isBootstrap) {\n const bootstrapConnections = this.libp2p\n .getConnections()\n .filter((conn) => conn.tags.includes(Tags.BOOTSTRAP));\n\n // If we have too many bootstrap connections, drop one\n if (\n bootstrapConnections.length > this.options.maxBootstrapPeersAllowed\n ) {\n await this.dropConnection(peerId);\n } else {\n this.dispatchEvent(\n new CustomEvent(\n EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP,\n {\n detail: peerId\n }\n )\n );\n }\n } else {\n this.dispatchEvent(\n new CustomEvent(\n EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE,\n {\n detail: peerId\n }\n )\n );\n }\n this.toggleOnline();\n })();\n },\n \"peer:disconnect\": (evt: CustomEvent): void => {\n void (async () => {\n this.keepAliveManager.stop(evt.detail);\n this.toggleOffline();\n })();\n }\n };\n\n /**\n * Checks if the peer should be dialed based on the following conditions:\n * 1. If the peer is already connected, don't dial\n * 2. If the peer is not part of any of the configured pubsub topics, don't dial\n * 3. If the peer is not dialable based on bootstrap status, don't dial\n * 4. If the peer is already has an active dial attempt, or has been dialed before, don't dial it\n * @returns true if the peer should be dialed, false otherwise\n */\n private async shouldDialPeer(peerId: PeerId): Promise {\n // if we're already connected to the peer, don't dial\n const isConnected = this.libp2p.getConnections(peerId).length > 0;\n if (isConnected) {\n log.warn(`Already connected to peer ${peerId.toString()}. Not dialing.`);\n return false;\n }\n\n // if the peer is not part of any of the configured pubsub topics, don't dial\n if (!(await this.isPeerTopicConfigured(peerId))) {\n const shardInfo = await this.getPeerShardInfo(\n peerId,\n this.libp2p.peerStore\n );\n log.warn(\n `Discovered peer ${peerId.toString()} with ShardInfo ${shardInfo} is not part of any of the configured pubsub topics (${\n this.configuredPubsubTopics\n }).\n Not dialing.`\n );\n return false;\n }\n\n // if the peer is not dialable based on bootstrap status, don't dial\n if (!(await this.isPeerDialableBasedOnBootstrapStatus(peerId))) {\n log.warn(\n `Peer ${peerId.toString()} is not dialable based on bootstrap status. Not dialing.`\n );\n return false;\n }\n\n // If the peer is already already has an active dial attempt, or has been dialed before, don't dial it\n if (this.dialAttemptsForPeer.has(peerId.toString())) {\n log.warn(\n `Peer ${peerId.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`\n );\n return false;\n }\n\n return true;\n }\n\n /**\n * Checks if the peer is dialable based on the following conditions:\n * 1. If the peer is a bootstrap peer, it is only dialable if the number of current bootstrap connections is less than the max allowed.\n * 2. If the peer is not a bootstrap peer\n */\n private async isPeerDialableBasedOnBootstrapStatus(\n peerId: PeerId\n ): Promise {\n const tagNames = await this.getTagNamesForPeer(peerId);\n\n const isBootstrap = tagNames.some((tagName) => tagName === Tags.BOOTSTRAP);\n\n if (isBootstrap) {\n const currentBootstrapConnections = this.libp2p\n .getConnections()\n .filter((conn) => {\n return conn.tags.find((name) => name === Tags.BOOTSTRAP);\n }).length;\n if (currentBootstrapConnections < this.options.maxBootstrapPeersAllowed)\n return true;\n } else {\n return true;\n }\n\n return false;\n }\n\n private async dispatchDiscoveryEvent(peerId: PeerId): Promise {\n const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(\n Tags.BOOTSTRAP\n );\n\n this.dispatchEvent(\n new CustomEvent(\n isBootstrap\n ? EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP\n : EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE,\n {\n detail: peerId\n }\n )\n );\n }\n\n /**\n * Fetches the tag names for a given peer\n */\n private async getTagNamesForPeer(peerId: PeerId): Promise {\n try {\n const peer = await this.libp2p.peerStore.get(peerId);\n return Array.from(peer.tags.keys());\n } catch (error) {\n log.error(`Failed to get peer ${peerId}, error: ${error}`);\n return [];\n }\n }\n\n private async isPeerTopicConfigured(peerId: PeerId): Promise {\n const shardInfo = await this.getPeerShardInfo(\n peerId,\n this.libp2p.peerStore\n );\n\n // If there's no shard information, simply return true\n if (!shardInfo) return true;\n\n const pubsubTopics = shardInfoToPubsubTopics(shardInfo);\n\n const isTopicConfigured = pubsubTopics.some((topic) =>\n this.configuredPubsubTopics.includes(topic)\n );\n return isTopicConfigured;\n }\n\n private async getPeerShardInfo(\n peerId: PeerId,\n peerStore: PeerStore\n ): Promise {\n const peer = await peerStore.get(peerId);\n const shardInfoBytes = peer.metadata.get(\"shardInfo\");\n if (!shardInfoBytes) return undefined;\n return decodeRelayShard(shardInfoBytes);\n }\n}\n","import type { PeerId } from \"@libp2p/interface\";\nimport { IncomingStreamData } from \"@libp2p/interface\";\nimport {\n type IMetadata,\n type Libp2pComponents,\n type PeerIdStr,\n ProtocolError,\n QueryResult,\n type ShardInfo\n} from \"@waku/interfaces\";\nimport { proto_metadata } from \"@waku/proto\";\nimport { encodeRelayShard, Logger, shardInfoToPubsubTopics } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\n\nimport { BaseProtocol } from \"../base_protocol.js\";\n\nconst log = new Logger(\"metadata\");\n\nexport const MetadataCodec = \"/vac/waku/metadata/1.0.0\";\n\nclass Metadata extends BaseProtocol implements IMetadata {\n private libp2pComponents: Libp2pComponents;\n handshakesConfirmed: Map = new Map();\n\n constructor(\n public shardInfo: ShardInfo,\n libp2p: Libp2pComponents\n ) {\n super(\n MetadataCodec,\n libp2p.components,\n log,\n shardInfoToPubsubTopics(shardInfo)\n );\n this.libp2pComponents = libp2p;\n void libp2p.registrar.handle(MetadataCodec, (streamData) => {\n void this.onRequest(streamData);\n });\n }\n\n /**\n * Handle an incoming metadata request\n */\n private async onRequest(streamData: IncomingStreamData): Promise {\n try {\n const { stream, connection } = streamData;\n const encodedShardInfo = proto_metadata.WakuMetadataResponse.encode(\n this.shardInfo\n );\n\n const encodedResponse = await pipe(\n [encodedShardInfo],\n lp.encode,\n stream,\n lp.decode,\n async (source) => await all(source)\n );\n\n const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse);\n\n if (error) {\n return;\n }\n\n await this.savePeerShardInfo(connection.remotePeer, shardInfo);\n } catch (error) {\n log.error(\"Error handling metadata request\", error);\n }\n }\n\n /**\n * Make a metadata query to a peer\n */\n async query(peerId: PeerId): Promise {\n const request = proto_metadata.WakuMetadataRequest.encode(this.shardInfo);\n\n const peer = await this.peerStore.get(peerId);\n if (!peer) {\n return {\n shardInfo: null,\n error: ProtocolError.NO_PEER_AVAILABLE\n };\n }\n\n const stream = await this.getStream(peer);\n\n const encodedResponse = await pipe(\n [request],\n lp.encode,\n stream,\n lp.decode,\n async (source) => await all(source)\n );\n\n const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse);\n\n if (error) {\n return {\n shardInfo: null,\n error\n };\n }\n\n await this.savePeerShardInfo(peerId, shardInfo);\n\n return {\n shardInfo,\n error: null\n };\n }\n\n public async confirmOrAttemptHandshake(peerId: PeerId): Promise {\n const shardInfo = this.handshakesConfirmed.get(peerId.toString());\n if (shardInfo) {\n return {\n shardInfo,\n error: null\n };\n }\n\n return await this.query(peerId);\n }\n\n private decodeMetadataResponse(\n encodedResponse: Uint8ArrayList[]\n ): QueryResult {\n const bytes = new Uint8ArrayList();\n\n encodedResponse.forEach((chunk) => {\n bytes.append(chunk);\n });\n const response = proto_metadata.WakuMetadataResponse.decode(\n bytes\n ) as ShardInfo;\n\n if (!response) {\n log.error(\"Error decoding metadata response\");\n return {\n shardInfo: null,\n error: ProtocolError.DECODE_FAILED\n };\n }\n\n return {\n shardInfo: response,\n error: null\n };\n }\n\n private async savePeerShardInfo(\n peerId: PeerId,\n shardInfo: ShardInfo\n ): Promise {\n // add or update the shardInfo to peer store\n await this.libp2pComponents.peerStore.merge(peerId, {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n });\n\n this.handshakesConfirmed.set(peerId.toString(), shardInfo);\n }\n}\n\nexport function wakuMetadata(\n shardInfo: ShardInfo\n): (components: Libp2pComponents) => IMetadata {\n return (components: Libp2pComponents) => new Metadata(shardInfo, components);\n}\n","/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n public type: string\n public code: string | string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.name = 'AbortError'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface RaceSignalOptions {\n /**\n * The message for the error thrown if the signal aborts\n */\n errorMessage?: string\n\n /**\n * The code for the error thrown if the signal aborts\n */\n errorCode?: string\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal (promise: Promise, signal?: AbortSignal, opts?: RaceSignalOptions): Promise {\n if (signal == null) {\n return promise\n }\n\n if (signal.aborted) {\n return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode))\n }\n\n let listener\n\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode)\n\n try {\n return await Promise.race([\n promise,\n new Promise((resolve, reject) => {\n listener = () => {\n reject(error)\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n","import deferred, { type DeferredPromise } from 'p-defer'\nimport { raceSignal, type RaceSignalOptions } from 'race-signal'\nimport { type AbortOptions } from './index.js'\n\nexport interface Pushable extends AsyncGenerator {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error, options?: AbortOptions & RaceSignalOptions): Promise\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T, options?: AbortOptions & RaceSignalOptions): Promise\n}\n\nclass QueuelessPushable implements Pushable {\n private readNext: DeferredPromise\n private haveNext: DeferredPromise\n private ended: boolean\n private nextResult: IteratorResult | undefined\n\n constructor () {\n this.ended = false\n\n this.readNext = deferred()\n this.haveNext = deferred()\n }\n\n [Symbol.asyncIterator] (): AsyncGenerator {\n return this\n }\n\n async next (): Promise> {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise\n }\n\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined')\n }\n\n const nextResult = this.nextResult\n this.nextResult = undefined\n\n // signal to the supplier that we read the value\n this.readNext.resolve()\n this.readNext = deferred()\n\n return nextResult\n }\n\n async throw (err?: Error): Promise> {\n this.ended = true\n\n if (err != null) {\n this.haveNext.reject(err)\n }\n\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n async return (): Promise> {\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n await this._push(undefined)\n\n return result\n }\n\n async push (value: T, options?: AbortOptions & RaceSignalOptions): Promise {\n await this._push(value, options)\n }\n\n async end (err?: Error, options?: AbortOptions & RaceSignalOptions): Promise {\n if (err != null) {\n await this.throw(err)\n } else {\n // abortable return\n await this._push(undefined, options)\n }\n }\n\n private async _push (value?: T, options?: AbortOptions & RaceSignalOptions): Promise {\n if (value != null && this.ended) {\n throw new Error('Cannot push value onto an ended pushable')\n }\n\n // already have a value, wait for it to be read\n if (this.nextResult != null) {\n await this.readNext.promise\n\n if (this.nextResult != null) {\n throw new Error('NeedNext promise resolved but nextResult was not consumed')\n }\n }\n\n if (value != null) {\n this.nextResult = { done: false, value }\n } else {\n this.ended = true\n this.nextResult = { done: true, value: undefined }\n }\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n this.haveNext = deferred()\n\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await raceSignal(\n this.readNext.promise,\n options?.signal,\n options\n )\n }\n}\n\nexport function pushable (): Pushable {\n return new QueuelessPushable()\n}\n","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive bytes over streams.\n *\n * @example\n *\n * ```typescript\n * import { byteStream } from 'it-byte-stream'\n *\n * const stream = byteStream(duplex)\n *\n * // read the next chunk\n * const bytes = await stream.read()\n *\n * // read the next five bytes\n * const fiveBytes = await stream.read(5)\n *\n * // write bytes into the stream\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n * ```\n */\n\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { pushable } from './pushable.js'\nimport type { Duplex } from 'it-stream-types'\n\nexport class CodeError extends Error {\n public readonly code: string\n\n constructor (message: string, code: string) {\n super(message)\n this.code = code\n }\n}\n\nexport class AbortError extends CodeError {\n public readonly type: string\n\n constructor (message: string) {\n super(message, 'ABORT_ERR')\n this.type = 'aborted'\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\nexport interface ByteStream {\n /**\n * Read a set number of bytes from the stream\n */\n read(bytes?: number, options?: AbortOptions): Promise\n\n /**\n * Write the passed bytes to the stream\n */\n write(input: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise\n\n /**\n * Returns the underlying stream\n */\n unwrap(): Stream\n}\n\nexport interface ByteStreamOpts {\n /**\n * After the stream is unwrapped, any bytes that have been read from the\n * incoming stream will be yielded in-order as `Uint8Array`(s).\n *\n * To yield a single `Uint8ArrayList` with all unread bytes instead, pass\n * `false` here.\n */\n yieldBytes?: boolean\n}\n\nexport function byteStream > (duplex: Stream, opts?: ByteStreamOpts): ByteStream {\n const write = pushable()\n\n duplex.sink(write).catch(async (err: Error) => {\n await write.end(err)\n })\n\n duplex.sink = async (source: any) => {\n for await (const buf of source) {\n await write.push(buf)\n }\n\n await write.end()\n }\n\n let source = duplex.source\n\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]()\n } else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]()\n }\n\n const readBuffer = new Uint8ArrayList()\n\n const W: ByteStream = {\n read: async (bytes?: number, options?: AbortOptions) => {\n options?.signal?.throwIfAborted()\n\n let listener: EventListener | undefined\n\n const abortPromise = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError('Read aborted'))\n }\n\n options?.signal?.addEventListener('abort', listener)\n })\n\n try {\n if (bytes == null) {\n // just read whatever arrives\n const { done, value } = await Promise.race([\n source.next(),\n abortPromise\n ])\n\n if (done === true) {\n return new Uint8ArrayList()\n }\n\n return value\n }\n\n while (readBuffer.byteLength < bytes) {\n const { value, done } = await Promise.race([\n source.next(),\n abortPromise\n ])\n\n if (done === true) {\n throw new CodeError('unexpected end of input', 'ERR_UNEXPECTED_EOF')\n }\n\n readBuffer.append(value)\n }\n\n const buf = readBuffer.sublist(0, bytes)\n readBuffer.consume(bytes)\n\n return buf\n } finally {\n if (listener != null) {\n options?.signal?.removeEventListener('abort', listener)\n }\n }\n },\n write: async (data, options?: AbortOptions) => {\n options?.signal?.throwIfAborted()\n\n // just write\n if (data instanceof Uint8Array) {\n await write.push(data, options)\n } else {\n await write.push(data.subarray(), options)\n }\n },\n unwrap: () => {\n if (readBuffer.byteLength > 0) {\n const originalStream = duplex.source\n duplex.source = (async function * () {\n if (opts?.yieldBytes === false) {\n yield readBuffer\n } else {\n yield * readBuffer\n }\n\n yield * originalStream\n }())\n }\n\n return duplex\n }\n }\n\n return W\n}\n","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed byte arrays over streams.\n *\n * @example\n *\n * ```typescript\n * import { lpStream } from 'it-length-prefixed-stream'\n *\n * const stream = lpStream(duplex)\n *\n * // read the next length-prefixed chunk\n * const bytes = await stream.read()\n *\n * // write a length-prefixed chunk\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // write several chunks, all individually length-prefixed\n * await stream.writeV([\n * Uint8Array.from([0, 1, 2, 3, 4]),\n * Uint8Array.from([5, 6, 7, 8, 9])\n * ])\n * ```\n */\nimport { byteStream, type ByteStreamOpts } from 'it-byte-stream'\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\n\nclass CodeError extends Error {\n public readonly code: string\n\n constructor (message: string, code: string) {\n super(message)\n this.code = code\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\nexport interface LengthPrefixedStream {\n /**\n * Read the next length-prefixed number of bytes from the stream\n */\n read(options?: AbortOptions): Promise\n\n /**\n * Write the passed bytes to the stream prefixed by their length\n */\n write(input: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise\n\n /**\n * Write passed list of bytes, prefix by their individual lengths to the stream as a single write\n */\n writeV(input: Array, options?: AbortOptions): Promise\n\n /**\n * Returns the underlying stream\n */\n unwrap(): Stream\n}\n\nexport interface LengthPrefixedStreamOpts extends ByteStreamOpts {\n // encoding opts\n lengthEncoder (value: number): Uint8ArrayList | Uint8Array\n\n // decoding opts\n lengthDecoder (data: Uint8ArrayList): number\n maxLengthLength: number\n maxDataLength: number\n}\n\nexport function lpStream > (duplex: Stream, opts: Partial = {}): LengthPrefixedStream {\n const bytes = byteStream(duplex, opts)\n\n if (opts.maxDataLength != null && opts.maxLengthLength == null) {\n // if max data length is set but max length length is not, calculate the\n // max length length needed to encode max data length\n opts.maxLengthLength = varint.encodingLength(opts.maxDataLength)\n }\n\n const decodeLength = opts?.lengthDecoder ?? varint.decode\n const encodeLength = opts?.lengthEncoder ?? varint.encode\n\n const W: LengthPrefixedStream = {\n read: async (options?: AbortOptions) => {\n let dataLength: number = -1\n const lengthBuffer = new Uint8ArrayList()\n\n while (true) {\n // read one byte at a time until we can decode a varint\n lengthBuffer.append(await bytes.read(1, options))\n\n try {\n dataLength = decodeLength(lengthBuffer)\n } catch (err) {\n if (err instanceof RangeError) {\n continue\n }\n\n throw err\n }\n\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw new CodeError('message length length too long', 'ERR_MSG_LENGTH_TOO_LONG')\n }\n\n if (dataLength > -1) {\n break\n }\n }\n\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw new CodeError('message length too long', 'ERR_MSG_DATA_TOO_LONG')\n }\n\n return bytes.read(dataLength, options)\n },\n write: async (data, options?: AbortOptions) => {\n // encode, write\n await bytes.write(new Uint8ArrayList(encodeLength(data.byteLength), data), options)\n },\n writeV: async (data, options?: AbortOptions) => {\n const list = new Uint8ArrayList(\n ...data.flatMap(buf => ([encodeLength(buf.byteLength), buf]))\n )\n\n // encode, write\n await bytes.write(list, options)\n },\n unwrap: () => {\n return bytes.unwrap()\n }\n }\n\n return W\n}\n","import defer from 'p-defer'\nimport type { Source, Duplex } from 'it-stream-types'\n\n/**\n * A pair of streams where one drains from the other\n */\nexport function pair (): Duplex, Source, Promise> {\n const deferred = defer>()\n let piped = false\n\n return {\n sink: async source => {\n if (piped) {\n throw new Error('already piped')\n }\n\n piped = true\n deferred.resolve(source)\n },\n source: (async function * () {\n const source = await deferred.promise\n\n yield * source\n }())\n }\n}\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","export const NOISE_MSG_MAX_LENGTH_BYTES = 65535\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16\n\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS)\n","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr: TypedArray) =>\n new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n else if (isBytes(data)) data = data.slice();\n else throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a)) throw new Error('Uint8Array expected');\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Check if object doens't have custom constructor (like Uint8Array/Array)\nconst isPlainObject = (obj: any) =>\n Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;\n\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))\n throw new Error('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport function ensureBytes(b: any, len?: number) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (typeof len === 'number')\n if (b.length !== len) throw new Error(`Uint8Array length ${len} expected`);\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\nexport type Cipher = {\n encrypt(plaintext: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\nexport type AsyncCipher = {\n encrypt(plaintext: Uint8Array): Promise;\n decrypt(ciphertext: Uint8Array): Promise;\n};\n\nexport type CipherWithOutput = Cipher & {\n encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n// Params is outside return type, so it is accessible before calling constructor\n// If function support multiple nonceLength's, we return best one\nexport type CipherParams = { blockSize: number; nonceLength?: number; tagLength?: number };\nexport type CipherCons = (key: Uint8Array, ...args: T) => Cipher;\nexport const wrapCipher = , P extends CipherParams>(\n params: P,\n c: C\n): C & P => {\n Object.assign(c, params);\n return c as C & P;\n};\n\nexport type XorStream = (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter?: number\n) => Uint8Array;\n\n// Polyfill for Safari 14\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\nexport function u64Lengths(ciphertext: Uint8Array, AAD?: Uint8Array) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n","function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`wrong positive integer: ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\n// TODO: merge with utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return (\n a != null &&\n typeof a === 'object' &&\n (a instanceof Uint8Array || a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\nexport type Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n","import { exists as aexists, output as aoutput } from './_assert.js';\nimport { Input, ensureBytes, toBytes, Hash } from './utils.js';\n\n// Poly1305 is a fast and parallel secret-key message-authentication code.\n// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf\n// https://datatracker.ietf.org/doc/html/rfc8439\n\n// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna\nconst u8to16 = (a: Uint8Array, i: number) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\nclass Poly1305 implements Hash {\n readonly blockLen = 16;\n readonly outputLen = 16;\n private buffer = new Uint8Array(16);\n private r = new Uint16Array(10);\n private h = new Uint16Array(10);\n private pad = new Uint16Array(8);\n private pos = 0;\n protected finished = false;\n\n constructor(key: Input) {\n key = toBytes(key);\n ensureBytes(key, 32);\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n\n private process(data: Uint8Array, offset: number, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n\n let c = 0;\n\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n\n private finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n }\n update(data: Input): this {\n aexists(this);\n const { buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n this.h.fill(0);\n this.r.fill(0);\n this.buffer.fill(0);\n this.pad.fill(0);\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n // buffer.subarray(pos).fill(0);\n for (; pos < 16; pos++) buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\n\nexport type CHash = ReturnType;\nexport function wrapConstructorWithKey>(hashCons: (key: Input) => Hash) {\n const hashC = (msg: Input, key: Input): Uint8Array => hashCons(key).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(32));\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input) => hashCons(key);\n return hashC;\n}\n\nexport const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));\n","// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { number as anumber, bytes as abytes, bool as abool } from './_assert.js';\nimport { XorStream, checkOpts, u32, utf8ToBytes } from './utils.js';\n\n/*\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n*/\n\nconst sigma16 = utf8ToBytes('expand 16-byte k');\nconst sigma32 = utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\n\nexport function rotl(a: number, b: number): number {\n return (a << b) | (a >>> (32 - b));\n}\n\nexport type CipherCoreFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n output: Uint32Array,\n counter: number,\n rounds?: number\n) => void;\n\nexport type ExtendNonceFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n input: Uint32Array,\n output: Uint32Array\n) => void;\n\nexport type CipherOpts = {\n allowShortKeys?: boolean; // Original salsa / chacha allow 16-byte keys\n extendNonceFn?: ExtendNonceFn;\n counterLength?: number;\n counterRight?: boolean; // right: nonce|counter; left: counter|nonce\n rounds?: number;\n};\n\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b: Uint8Array) {\n return b.byteOffset % 4 === 0;\n}\n\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\n\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(\n core: CipherCoreFn,\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n data: Uint8Array,\n output: Uint8Array,\n counter: number,\n rounds: number\n): void {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0) throw new Error('arx: invalid block position');\n for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n\nexport function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(\n { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },\n opts\n );\n if (typeof core !== 'function') throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter = 0\n ): Uint8Array => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (!output) output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length,\n k: Uint8Array,\n sigma: Uint32Array;\n if (l === 32) {\n k = key.slice();\n toClean.push(k);\n sigma = sigma32_32;\n } else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n } else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce)) {\n nonce = nonce.slice();\n toClean.push(nonce);\n }\n\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n while (toClean.length > 0) toClean.pop()!.fill(0);\n return output;\n };\n}\n","import {\n wrapCipher,\n CipherWithOutput,\n XorStream,\n createView,\n ensureBytes,\n equalBytes,\n setBigUint64,\n} from './utils.js';\nimport { poly1305 } from './_poly1305.js';\nimport { createCipher, rotl } from './_arx.js';\n\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\n\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(\n s: Uint32Array, k: Uint32Array, n: Uint32Array, out: Uint32Array, cnt: number, rounds = 20\n): void {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(\n s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array\n) {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3],\n x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3],\n x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7],\n x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00; o32[oi++] = x01;\n o32[oi++] = x02; o32[oi++] = x03;\n o32[oi++] = x12; o32[oi++] = x13;\n o32[oi++] = x14; o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h: ReturnType, msg: Uint8Array) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left) h.update(ZEROS16.subarray(left));\n};\n\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(\n fn: XorStream,\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n): Uint8Array {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD) updatePadded(h, AAD);\n updatePadded(h, data);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(data.length), true);\n h.update(num);\n const res = h.digest();\n authKey.fill(0);\n return res;\n}\n\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead =\n (xorStream: XorStream) =>\n (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): CipherWithOutput => {\n const tagLength = 16;\n ensureBytes(key, 32);\n ensureBytes(nonce);\n return {\n encrypt: (plaintext: Uint8Array, output?: Uint8Array) => {\n const plength = plaintext.length;\n const clength = plength + tagLength;\n if (output) {\n ensureBytes(output, clength);\n } else {\n output = new Uint8Array(clength);\n }\n xorStream(key, nonce, plaintext, output, 1);\n const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n output.set(tag, plength); // append tag\n return output;\n },\n decrypt: (ciphertext: Uint8Array, output?: Uint8Array) => {\n const clength = ciphertext.length;\n const plength = clength - tagLength;\n if (clength < tagLength)\n throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n if (output) {\n ensureBytes(output, plength);\n } else {\n output = new Uint8Array(plength);\n }\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag)) throw new Error('invalid tag');\n xorStream(key, nonce, data, output, 1);\n return output;\n },\n };\n };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 12, tagLength: 16 },\n _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 24, tagLength: 16 },\n _poly1305_aead(xchacha20)\n);\n","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x6a09e667 | 0;\n Al = 0xf3bcc908 | 0;\n Bh = 0xbb67ae85 | 0;\n Bl = 0x84caa73b | 0;\n Ch = 0x3c6ef372 | 0;\n Cl = 0xfe94f82b | 0;\n Dh = 0xa54ff53a | 0;\n Dl = 0x5f1d36f1 | 0;\n Eh = 0x510e527f | 0;\n El = 0xade682d1 | 0;\n Fh = 0x9b05688c | 0;\n Fl = 0x2b3e6c1f | 0;\n Gh = 0x1f83d9ab | 0;\n Gl = 0xfb41bd6b | 0;\n Hh = 0x5be0cd19 | 0;\n Hl = 0x137e2179 | 0;\n\n constructor() {\n super(128, 64, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nclass SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x8c3d37c8 | 0;\n Al = 0x19544da2 | 0;\n Bh = 0x73e19966 | 0;\n Bl = 0x89dcd4d6 | 0;\n Ch = 0x1dfab7ae | 0;\n Cl = 0x32ff9c82 | 0;\n Dh = 0x679dd514 | 0;\n Dl = 0x582f9fcf | 0;\n Eh = 0x0f6d2b69 | 0;\n El = 0x7bd44da8 | 0;\n Fh = 0x77e36f73 | 0;\n Fl = 0x04c48942 | 0;\n Gh = 0x3f9d85a8 | 0;\n Gl = 0x6a1d36c8 | 0;\n Hh = 0x1112e6ad | 0;\n Hl = 0x91d692a1 | 0;\n\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\nclass SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x22312194 | 0;\n Al = 0xfc2bf72c | 0;\n Bh = 0x9f555fa3 | 0;\n Bl = 0xc84c64c2 | 0;\n Ch = 0x2393b86b | 0;\n Cl = 0x6f53b151 | 0;\n Dh = 0x96387719 | 0;\n Dl = 0x5940eabd | 0;\n Eh = 0x96283ee2 | 0;\n El = 0xa88effe3 | 0;\n Fh = 0xbe5e1e25 | 0;\n Fl = 0x53863992 | 0;\n Gh = 0x2b0199fc | 0;\n Gl = 0x2c85b8aa | 0;\n Hh = 0x0eb72ddc | 0;\n Hl = 0x81c52ca2 | 0;\n\n constructor() {\n super();\n this.outputLen = 32;\n }\n}\n\nclass SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0xcbbb9d5d | 0;\n Al = 0xc1059ed8 | 0;\n Bh = 0x629a292a | 0;\n Bl = 0x367cd507 | 0;\n Ch = 0x9159015a | 0;\n Cl = 0x3070dd17 | 0;\n Dh = 0x152fecd8 | 0;\n Dl = 0xf70e5939 | 0;\n Eh = 0x67332667 | 0;\n El = 0xffc00b31 | 0;\n Fh = 0x8eb44a87 | 0;\n Fl = 0x68581511 | 0;\n Gh = 0xdb0c2e0d | 0;\n Gl = 0x64f98fa7 | 0;\n Hh = 0x47b5481d | 0;\n Hl = 0xbefa4fa4 | 0;\n\n constructor() {\n super();\n this.outputLen = 48;\n }\n}\n\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap> = { [K in keyof T]?: Validator };\n// type Record = { [P in K]: T; }\n\nexport function validateObject>(\n object: T,\n validators: ValMap,\n optValidators: ValMap = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n numberToBytesBE,\n numberToBytesLE,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp: IField, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField(field: IField) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f: IField, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('Expected power > 0');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f: IField, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv(f: IField, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f: IField) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x: T): boolean => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField & Required, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial> = {}\n): Readonly {\n if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f: Readonly = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper = (i: T[]) => T[];\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF>(c: GroupConstructor, bits: number) {\n const constTimeNegate = (condition: boolean, item: T): T => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W: number) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint) {\n let p = c.ZERO;\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group[] {\n const { windows, windowSize } = opts(W);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n wNAFCached(P: T, precomputesMap: Map, n: bigint, transform: Mapper): { p: T; f: T } {\n // @ts-ignore\n const W: number = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve = {\n Fp: IField; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic(curve: BasicCurve & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport { mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, FHash, Hex } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n// Edwards curves must declare params a & d.\nexport type CurveType = BasicCurve & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio √(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint; // for hash-to-curve standard\n};\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n// Instance of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointType extends Group {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n// Static methods of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointConstructor extends GroupConstructor {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n}\n\nexport type CurveFn = {\n CURVE: ReturnType;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n };\n};\n\n// It is not generic twisted curve for now, but ed25519/ed448 generic implementation\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n const inBig = (n: bigint) => typeof n === 'bigint' && _0n < n; // n in [1..]\n const inRange = (n: bigint, max: bigint) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]\n const in0MaskRange = (n: bigint) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]\n function assertInRange(n: bigint, max: bigint) {\n // n in [1..max-1]\n if (inRange(n, max)) return n;\n throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);\n }\n function assertGE0(n: bigint) {\n // n in [0..CURVE_ORDER-1]\n return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group\n }\n const pointPrecomputes = new Map();\n function isPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n\n constructor(\n readonly ex: bigint,\n readonly ey: bigint,\n readonly ez: bigint,\n readonly et: bigint\n ) {\n if (!in0MaskRange(ex)) throw new Error('x required');\n if (!in0MaskRange(ey)) throw new Error('y required');\n if (!in0MaskRange(ez)) throw new Error('z required');\n if (!in0MaskRange(et)) throw new Error('t required');\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error('invalid affine point');\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n const { a, d } = CURVE;\n if (this.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = this;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n isPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n protected is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n isPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar: bigint): Point {\n let n = assertGE0(scalar); // 0 <= scalar < CURVE.n\n if (n === _0n) return I;\n if (this.equals(I) || n === _1n) return this;\n if (this.equals(G)) return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint {\n const { ex: x, ey: y, ez: z } = this;\n const is0 = this.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n if (y === _0n) {\n // y=0 is allowed\n } else {\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n if (zip215) assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)\n else assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)\n }\n\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(ut.bytesToNumberLE(hash));\n }\n\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key: Hex) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n assertGE0(s); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\ntype Hex = string | Uint8Array;\n\nexport type CurveType = {\n P: bigint; // finite field prime\n nByteLength: number;\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array;\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n a: bigint;\n montgomeryBits: number;\n powPminus2?: (x: bigint) => bigint;\n xyToU?: (x: bigint, y: bigint) => bigint;\n Gu: bigint;\n randomBytes?: (bytesLength?: number) => Uint8Array;\n};\nexport type CurveFn = {\n scalarMult: (scalar: Hex, u: Hex) => Uint8Array;\n scalarMultBase: (scalar: Hex) => Uint8Array;\n getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n utils: { randomPrivateKey: () => Uint8Array };\n GuBytes: Uint8Array;\n};\n\nfunction validateOpts(curve: CurveType) {\n validateObject(\n curve,\n {\n a: 'bigint',\n },\n {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n }\n );\n // Set defaults\n return Object.freeze({ ...curve } as const);\n}\n\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n: bigint) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P));\n\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n\n // Accepts 0 as well\n function assertFieldElement(n: bigint): bigint {\n if (typeof n === 'bigint' && _0n <= n && n < P) return n;\n throw new Error('Expected valid scalar 0 < scalar < CURVE.P');\n }\n\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(pointU: bigint, scalar: bigint): bigint {\n const u = assertFieldElement(pointU);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = assertFieldElement(scalar);\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw: [bigint, bigint];\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n\n function encodeUCoordinate(u: bigint): Uint8Array {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n\n function decodeUCoordinate(uEnc: Hex): bigint {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32) u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n: Hex): bigint {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar: Hex, u: Hex): Uint8Array {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n) throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar: Hex): Uint8Array {\n return scalarMult(scalar, GuBytes);\n }\n\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes!(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { ExtPointType, twistedEdwards } from './abstract/edwards.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n Hex,\n numberToBytesLE,\n} from './abstract/utils.js';\nimport { createHasher, htfBasicOpts, expand_message_xmd } from './abstract/hash-to-curve.js';\nimport { AffinePoint, Group } from './abstract/curve.js';\n\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5);\n// prettier-ignore\nconst _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = Field(ED25519_P, undefined, true);\n\nconst ed25519Defaults = {\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: BigInt(8),\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n} as const;\n\nexport const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n});\nexport const ed25519ph = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n prehash: sha512,\n});\n\nexport const x25519 = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic\n\nconst ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1\nconst ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1)\nconst ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic\nconst ELL2_J = BigInt(486662);\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n\nfunction assertRstPoint(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/√(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(private readonly ep: ExtendedPoint) {}\n\n static fromAffine(ap: AffinePoint) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC> extends Hash> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC): HMAC {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC(hash, key);\n","import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { CHash, Input, toBytes } from './utils.js';\nimport { hmac } from './hmac.js';\n\n// HKDF (RFC 5869)\n// https://soatok.blog/2021/11/17/understanding-hkdf/\n\n/**\n * HKDF-Extract(IKM, salt) -> PRK\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash\n * @param ikm\n * @param salt\n * @returns\n */\nexport function extract(hash: CHash, ikm: Input, salt?: Input) {\n assertHash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined) salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\n\n// HKDF-Expand(PRK, info, L) -> OKM\nconst HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array();\n\n/**\n * HKDF-expand from the spec.\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in octets\n */\nexport function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) {\n assertHash(hash);\n assertNumber(length);\n if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined) info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n\n/**\n * HKDF (RFC 5869): extract + expand in one step.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information\n * @param length - length of output keying material in octets\n */\nexport const hkdf = (\n hash: CHash,\n ikm: Input,\n salt: Input | undefined,\n info: Input | undefined,\n length: number\n) => expand(hash, extract(hash, ikm, salt), info, length);\n","import { pureJsCrypto } from './js.js'\n\nexport const defaultCrypto = pureJsCrypto\n","import { chacha20poly1305 } from '@noble/ciphers/chacha'\nimport { x25519 } from '@noble/curves/ed25519'\nimport { extract, expand } from '@noble/hashes/hkdf'\nimport { sha256 } from '@noble/hashes/sha256'\nimport type { bytes32 } from '../@types/basic.js'\nimport type { Hkdf } from '../@types/handshake.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport type { ICryptoInterface } from '../crypto.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const pureJsCrypto: ICryptoInterface = {\n hashSHA256 (data: Uint8Array | Uint8ArrayList): Uint8Array {\n return sha256(data.subarray())\n },\n\n getHKDF (ck: bytes32, ikm: Uint8Array): Hkdf {\n const prk = extract(sha256, ikm, ck)\n const okmU8Array = expand(sha256, prk, undefined, 96)\n const okm = okmU8Array\n\n const k1 = okm.subarray(0, 32)\n const k2 = okm.subarray(32, 64)\n const k3 = okm.subarray(64, 96)\n\n return [k1, k2, k3]\n },\n\n generateX25519KeyPair (): KeyPair {\n const secretKey = x25519.utils.randomPrivateKey()\n const publicKey = x25519.getPublicKey(secretKey)\n\n return {\n publicKey,\n privateKey: secretKey\n }\n },\n\n generateX25519KeyPairFromSeed (seed: Uint8Array): KeyPair {\n const publicKey = x25519.getPublicKey(seed)\n\n return {\n publicKey,\n privateKey: seed\n }\n },\n\n generateX25519SharedKey (privateKey: Uint8Array | Uint8ArrayList, publicKey: Uint8Array | Uint8ArrayList): Uint8Array {\n return x25519.getSharedSecret(privateKey.subarray(), publicKey.subarray())\n },\n\n chaCha20Poly1305Encrypt (plaintext: Uint8Array | Uint8ArrayList, nonce: Uint8Array, ad: Uint8Array, k: bytes32): Uint8Array {\n return chacha20poly1305(k, nonce, ad).encrypt(plaintext.subarray())\n },\n\n chaCha20Poly1305Decrypt (ciphertext: Uint8Array | Uint8ArrayList, nonce: Uint8Array, ad: Uint8Array, k: bytes32, dst?: Uint8Array): Uint8Array | null {\n return chacha20poly1305(k, nonce, ad).decrypt(ciphertext.subarray(), dst)\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { alloc as uint8ArrayAlloc, allocUnsafe as uint8ArrayAllocUnsafe } from 'uint8arrays/alloc'\nimport type { bytes } from './@types/basic.js'\nimport type { MessageBuffer } from './@types/handshake.js'\nimport type { LengthDecoderFunction } from 'it-length-prefixed'\n\nexport const uint16BEEncode = (value: number): Uint8Array => {\n const target = uint8ArrayAllocUnsafe(2)\n new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false)\n return target\n}\nuint16BEEncode.bytes = 2\n\nexport const uint16BEDecode: LengthDecoderFunction = (data: Uint8Array | Uint8ArrayList): number => {\n if (data.length < 2) throw RangeError('Could not decode int16BE')\n\n if (data instanceof Uint8Array) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false)\n }\n\n return data.getUint16(0)\n}\nuint16BEDecode.bytes = 2\n\n// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)\n\nexport function encode0 (message: MessageBuffer): Uint8ArrayList {\n return new Uint8ArrayList(message.ne, message.ciphertext)\n}\n\nexport function encode1 (message: MessageBuffer): Uint8ArrayList {\n return new Uint8ArrayList(message.ne, message.ns, message.ciphertext)\n}\n\nexport function encode2 (message: MessageBuffer): Uint8ArrayList {\n return new Uint8ArrayList(message.ns, message.ciphertext)\n}\n\nexport function decode0 (input: bytes): MessageBuffer {\n if (input.length < 32) {\n throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ciphertext: input.subarray(32, input.length),\n ns: uint8ArrayAlloc(0)\n }\n}\n\nexport function decode1 (input: bytes): MessageBuffer {\n if (input.length < 80) {\n throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ns: input.subarray(32, 80),\n ciphertext: input.subarray(80, input.length)\n }\n}\n\nexport function decode2 (input: bytes): MessageBuffer {\n if (input.length < 48) {\n throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')\n }\n\n return {\n ne: uint8ArrayAlloc(0),\n ns: input.subarray(0, 48),\n ciphertext: input.subarray(48, input.length)\n }\n}\n","export class UnexpectedPeerError extends Error {\n public code: string\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.code = UnexpectedPeerError.code\n }\n\n static readonly code = 'ERR_UNEXPECTED_PEER'\n}\n\nexport class InvalidCryptoExchangeError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.code = InvalidCryptoExchangeError.code\n }\n\n static readonly code = 'ERR_INVALID_CRYPTO_EXCHANGE'\n}\n","/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n public readonly code: string\n public readonly type: string\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n this.code = AbortError.code\n this.type = AbortError.type\n }\n\n static readonly code = 'ABORT_ERR'\n\n static readonly type = 'aborted'\n}\n\nexport class CodeError = Record> extends Error {\n public readonly props: T\n\n constructor (\n message: string,\n public readonly code: string,\n props?: T\n ) {\n super(message)\n\n this.name = props?.name ?? 'CodeError'\n this.props = props ?? {} as T // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\n\nexport class AggregateCodeError = Record> extends AggregateError {\n public readonly props: T\n\n constructor (\n errors: Error[],\n message: string,\n public readonly code: string,\n props?: T\n ) {\n super(errors, message)\n\n this.name = props?.name ?? 'AggregateCodeError'\n this.props = props ?? {} as T // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\n\nexport class UnexpectedPeerError extends Error {\n public code: string\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n this.code = UnexpectedPeerError.code\n }\n\n static readonly code = 'ERR_UNEXPECTED_PEER'\n}\n\nexport class InvalidCryptoExchangeError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n this.code = InvalidCryptoExchangeError.code\n }\n\n static readonly code = 'ERR_INVALID_CRYPTO_EXCHANGE'\n}\n\nexport class InvalidCryptoTransmissionError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto transmission') {\n super(message)\n this.name = 'InvalidCryptoTransmissionError'\n this.code = InvalidCryptoTransmissionError.code\n }\n\n static readonly code = 'ERR_INVALID_CRYPTO_TRANSMISSION'\n}\n\n// Error codes\n\nexport const ERR_TIMEOUT = 'ERR_TIMEOUT'\nexport const ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS'\nexport const ERR_NOT_FOUND = 'ERR_NOT_FOUND'\nexport const ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE'\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import 'node-forge/lib/util.js'\nimport 'node-forge/lib/jsbn.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport function bigIntegerToUintBase64url (num: { abs(): any }, len?: number): string {\n // Call `.abs()` to convert to unsigned\n let buf = Uint8Array.from(num.abs().toByteArray()) // toByteArray converts to big endian\n\n // toByteArray() gives us back a signed array, which will include a leading 0\n // byte if the most significant bit of the number is 1:\n // https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-integer\n // Our number will always be positive so we should remove the leading padding.\n buf = buf[0] === 0 ? buf.subarray(1) : buf\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return uint8ArrayToString(buf, 'base64url')\n}\n\n// Convert a base64url encoded string to a BigInteger\nexport function base64urlToBigInteger (str: string): typeof forge.jsbn.BigInteger {\n const buf = base64urlToBuffer(str)\n return new forge.jsbn.BigInteger(uint8ArrayToString(buf, 'base16'), 16)\n}\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n\nexport function isPromise (thing: any): thing is Promise {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n","import { ed25519 as ed } from '@noble/curves/ed25519'\nimport type { Uint8ArrayKeyPair } from './interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32\nconst PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed (seed: Uint8Array): Uint8ArrayKeyPair {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw)\n}\n\nexport function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH)\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i]\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i]\n }\n return privateKey\n}\n","/* eslint-env browser */\n\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get (win = globalThis) {\n const nativeCrypto = win.crypto\n\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n 'Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n","import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\n\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' }\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions): AESCipher {\n const algorithm = opts?.algorithm ?? 'AES-GCM'\n let keyLength = opts?.keyLength ?? 16\n const nonceLength = opts?.nonceLength ?? 12\n const digest = opts?.digest ?? 'SHA-256'\n const saltLength = opts?.saltLength ?? 16\n const iterations = opts?.iterations ?? 32767\n\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n }\n } else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt'])\n }\n\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data)\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)])\n }\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = data.subarray(0, saltLength)\n const nonce = data.subarray(saltLength, saltLength + nonceLength)\n const ciphertext = data.subarray(saltLength + nonceLength)\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt'])\n }\n } else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt'])\n }\n\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext)\n return new Uint8Array(plaintext)\n }\n\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n","import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\nimport type { Multibase } from 'multiformats'\n\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter (privateKey: Uint8Array, password: string): Promise> {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\n","const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n","import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = (): Codec => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n","import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n\n this.code = code\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { isPromise } from '../util.js'\nimport * as crypto from './ed25519.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Ed25519PublicKey {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id (): Promise {\n const encoding = identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n }\n\n bytes = ensureKey(bytes, crypto.privateKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const { privateKey, publicKey } = crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array): Promise {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE')\n }\n return key\n}\n","import { CodeError } from '@libp2p/interface'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { base64urlToBuffer } from '../util.js'\nimport webcrypto from '../webcrypto.js'\nimport type { ECDHKey, ECDHKeyPair, JWKEncodedPrivateKey, JWKEncodedPublicKey } from './interface.js'\n\nconst bits = {\n 'P-256': 256,\n 'P-384': 384,\n 'P-521': 521\n}\n\nconst curveTypes = Object.keys(bits)\nconst names = curveTypes.join(' / ')\n\nexport async function generateEphmeralKeyPair (curve: string): Promise {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve\n },\n true,\n ['deriveBits']\n )\n\n // forcePrivate is used for testing only\n const genSharedKey = async (theirPub: Uint8Array, forcePrivate?: ECDHKeyPair): Promise => {\n let privateKey\n\n if (forcePrivate != null) {\n privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPrivateKey(curve, forcePrivate),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n ['deriveBits']\n )\n } else {\n privateKey = pair.privateKey\n }\n\n const key = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPublicKey(curve, theirPub),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n []\n )\n\n const buffer = await webcrypto.get().subtle.deriveBits(\n {\n name: 'ECDH',\n // @ts-expect-error namedCurve is missing from the types\n namedCurve: curve,\n public: key\n },\n privateKey,\n bits[curve]\n )\n\n return new Uint8Array(buffer, 0, buffer.byteLength)\n }\n\n const publicKey = await webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n\n const ecdhKey: ECDHKey = {\n key: marshalPublicKey(publicKey),\n genSharedKey\n }\n\n return ecdhKey\n}\n\nconst curveLengths = {\n 'P-256': 32,\n 'P-384': 48,\n 'P-521': 66\n}\n\n// Marshal converts a jwk encoded ECDH public key into the\n// form specified in section 4.3.6 of ANSI X9.62. (This is the format\n// go-ipfs uses)\nfunction marshalPublicKey (jwk: JsonWebKey): Uint8Array {\n if (jwk.crv == null || jwk.x == null || jwk.y == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {\n throw new CodeError(`Unknown curve: ${jwk.crv}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[jwk.crv]\n\n return uint8ArrayConcat([\n Uint8Array.from([4]), // uncompressed point\n base64urlToBuffer(jwk.x, byteLen),\n base64urlToBuffer(jwk.y, byteLen)\n ], 1 + byteLen * 2)\n}\n\n// Unmarshal converts a point, serialized by Marshal, into an jwk encoded key\nfunction unmarshalPublicKey (curve: string, key: Uint8Array): JWKEncodedPublicKey {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[curve]\n\n if (!uint8ArrayEquals(key.subarray(0, 1), Uint8Array.from([4]))) {\n throw new CodeError('Cannot unmarshal public key - invalid key format', 'ERR_INVALID_KEY_FORMAT')\n }\n\n return {\n kty: 'EC',\n crv: curve,\n x: uint8ArrayToString(key.subarray(1, byteLen + 1), 'base64url'),\n y: uint8ArrayToString(key.subarray(1 + byteLen), 'base64url'),\n ext: true\n }\n}\n\nconst unmarshalPrivateKey = (curve: string, key: ECDHKeyPair): JWKEncodedPrivateKey => ({\n ...unmarshalPublicKey(curve, key.public),\n d: uint8ArrayToString(key.private, 'base64url')\n})\n","import 'node-forge/lib/rsa.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { base64urlToBigInteger } from '../util.js'\n\nexport interface JWK {\n encrypt(msg: string): string\n decrypt(msg: string): string\n}\n\nfunction convert (key: any, types: string[]): Array {\n return types.map(t => base64urlToBigInteger(key[t]))\n}\n\nexport function jwk2priv (key: JsonWebKey): JWK {\n return forge.pki.setRsaPrivateKey(...convert(key, ['n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'qi']))\n}\n\nexport function jwk2pub (key: JsonWebKey): JWK {\n return forge.pki.setRsaPublicKey(...convert(key, ['n', 'e']))\n}\n","import { CodeError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport { jwk2pub, jwk2priv } from './jwk2pem.js'\nimport * as utils from './rsa-utils.js'\nimport type { JWKKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport { utils }\n\nexport async function generateKey (bits: number): Promise {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey): Promise {\n return webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\n/*\n\nRSA encryption/decryption for the browser with webcrypto workaround\n\"bloody dark magic. webcrypto's why.\"\n\nExplanation:\n - Convert JWK to nodeForge\n - Convert msg Uint8Array to nodeForge buffer: ByteBuffer is a \"binary-string backed buffer\", so let's make our Uint8Array a binary string\n - Convert resulting nodeForge buffer to Uint8Array: it returns a binary string, turn that into a Uint8Array\n\n*/\n\nfunction convertKey (key: JsonWebKey, pub: boolean, msg: Uint8Array | Uint8ArrayList, handle: (msg: string, key: { encrypt(msg: string): string, decrypt(msg: string): string }) => string): Uint8Array {\n const fkey = pub ? jwk2pub(key) : jwk2priv(key)\n const fmsg = uint8ArrayToString(msg instanceof Uint8Array ? msg : msg.subarray(), 'ascii')\n const fomsg = handle(fmsg, fkey)\n return uint8ArrayFromString(fomsg, 'ascii')\n}\n\nexport function encrypt (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n return convertKey(key, true, msg, (msg, key) => key.encrypt(msg))\n}\n\nexport function decrypt (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n return convertKey(key, false, msg, (msg, key) => key.decrypt(msg))\n}\n\nexport function keySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE')\n } else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport 'node-forge/lib/sha512.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport * as crypto from './rsa.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const MAX_KEY_SIZE = 8192\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n encrypt (bytes: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.encrypt(this._key, bytes)\n }\n\n equals (key: any): boolean | boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret (): Uint8Array {\n return crypto.getRandomValues(16)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): RsaPublicKey {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n decrypt (bytes: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.decrypt(this._key, bytes)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected PEM format\n */\n async export (password: string, format = 'pkcs-8'): Promise> {\n if (format === 'pkcs-8') {\n const buffer = new forge.util.ByteBuffer(this.marshal())\n const asn1 = forge.asn1.fromDer(buffer)\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n const options = {\n algorithm: 'aes256',\n count: 10000,\n saltSize: 128 / 8,\n prfAlgorithm: 'sha512'\n }\n return forge.pki.encryptRsaPrivateKey(privateKey, password, options)\n } else if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array): Promise {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array): RsaPublicKey {\n const jwk = crypto.utils.pkixToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey): Promise {\n if (crypto.keySize(jwk) > MAX_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number): Promise {\n if (bits > MAX_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.generateKey(bits)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n","import 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/rsa.js'\nimport { CodeError } from '@libp2p/interface'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bigIntegerToUintBase64url, base64urlToBigInteger } from './../util.js'\n\n// Convert a PKCS#1 in ASN1 DER format to a JWK key\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n // https://tools.ietf.org/html/rfc7518#section-6.3.1\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(privateKey.n),\n e: bigIntegerToUintBase64url(privateKey.e),\n d: bigIntegerToUintBase64url(privateKey.d),\n p: bigIntegerToUintBase64url(privateKey.p),\n q: bigIntegerToUintBase64url(privateKey.q),\n dp: bigIntegerToUintBase64url(privateKey.dP),\n dq: bigIntegerToUintBase64url(privateKey.dQ),\n qi: bigIntegerToUintBase64url(privateKey.qInv),\n alg: 'RS256'\n }\n}\n\n// Convert a JWK key into PKCS#1 in ASN1 DER format\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const asn1 = forge.pki.privateKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e),\n d: base64urlToBigInteger(jwk.d),\n p: base64urlToBigInteger(jwk.p),\n q: base64urlToBigInteger(jwk.q),\n dP: base64urlToBigInteger(jwk.dp),\n dQ: base64urlToBigInteger(jwk.dq),\n qInv: base64urlToBigInteger(jwk.qi)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n\n// Convert a PKCIX in ASN1 DER format to a JWK key\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const publicKey = forge.pki.publicKeyFromAsn1(asn1)\n\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(publicKey.n),\n e: bigIntegerToUintBase64url(publicKey.e)\n }\n}\n\n// Convert a JWK key to PKCIX in ASN1 DER format\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const asn1 = forge.pki.publicKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n","import { CodeError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH')\n }\n return randB(length)\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve = BasicCurve & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType;\n};\n\ntype Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean };\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType extends Group> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n multiply(scalar: bigint): ProjPointType;\n toAffine(iz?: T): AffinePoint;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\n assertValidity(): void;\n hasEvenY(): boolean;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor extends GroupConstructor> {\n new (x: T, y: T, z: T): ProjPointType;\n fromAffine(p: AffinePoint): ProjPointType;\n fromHex(hex: Hex): ProjPointType;\n fromPrivateKey(privateKey: PrivKey): ProjPointType;\n normalizeZ(points: ProjPointType[]): ProjPointType[];\n}\n\nexport type CurvePointsType = BasicWCurve & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint;\n toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts(curve: CurvePointsType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes = {\n CURVE: ReturnType>;\n ProjectivePoint: ProjConstructor;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n let l = data.length;\n if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag');\n if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num: number | bigint) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints(opts: CurvePointsType): CurvePointsRes {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor, point: ProjPointType, _isCompressed: boolean) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num: bigint) {\n if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key)) key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n\n const pointPrecomputes = new Map();\n function assertPrjPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n constructor(\n readonly px: T,\n readonly py: T,\n readonly pz: T\n ) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n private is0() {\n return this.equals(Point.ZERO);\n }\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n: bigint): Point {\n const I = Point.ZERO;\n if (n === _0n) return I;\n assertGE(n); // Will throw on 0\n if (n === _1n) return this;\n const { endo } = CURVE;\n if (!endo) return wnaf.unsafeLadder(this, n);\n\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n assertGE(scalar);\n let n = scalar;\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n // DER-encoded\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType;\n\nexport type CurveType = BasicWCurve & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType;\n };\n};\n\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function isValidFieldElement(num: bigint): boolean {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a: bigint) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return mod.invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n throw new Error(\n `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`\n );\n }\n },\n });\n const numToNByteStr = (num: bigint): string =>\n ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n constructor(\n readonly r: bigint,\n readonly s: bigint,\n readonly recovery?: number\n ) {\n this.assertValidity();\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n assertValidity(): void {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n');\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n if (typeof num !== 'bigint') throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n _sig = Signature.fromCompact(sg);\n }\n } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n } else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n if ((error as Error).message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp: mod.IField, Z: T) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(\n Fp: mod.IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass, CurveType } from './abstract/weierstrass.js';\nimport { CHash } from './abstract/utils.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\nexport const secp256k1 = createCurve(\n {\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType {\n if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!fe(r)) return false;\n const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!ge(s)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n } catch (error) {\n return false;\n }\n}\n\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fp,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n }))();\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n","import { CodeError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { isPromise } from '../util.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign (key: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.sign(p.digest, key).toDERRawBytes()\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.verify(sig, p.digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array): void {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array): void {\n try {\n secp.ProjectivePoint.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\nimport * as crypto from './secp256k1.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Secp256k1PublicKey {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const privateKeyBytes = crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\nimport 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/pbe.js'\nimport { CodeError } from '@libp2p/interface'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport * as Ed25519 from './ed25519-class.js'\nimport generateEphemeralKeyPair from './ephemeral-keys.js'\nimport { importer } from './importer.js'\nimport { keyStretcher } from './key-stretcher.js'\nimport * as keysPBM from './keys.js'\nimport * as RSA from './rsa-class.js'\nimport * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string): CodeError> {\n const supported = Object.keys(supportedKeys).join(' / ')\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE')\n}\n\nfunction typeToKey (type: string): typeof RSA | typeof Ed25519 | typeof Secp256k1 {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise {\n return typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE')\n }\n\n return Ed25519.generateKeyPairFromSeed(seed)\n}\n\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown')\n }\n}\n\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise {\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA')\n }\n}\n\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey (encryptedKey: string, password: string): Promise {\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n // Only rsa supports pem right now\n const key = forge.pki.decryptRsaPrivateKey(encryptedKey, password)\n if (key === null) {\n throw new CodeError('Cannot read the key, most likely the password is wrong or not a RSA key', 'ERR_CANNOT_DECRYPT_PEM')\n }\n let der = forge.asn1.toDer(forge.pki.privateKeyToAsn1(key))\n der = uint8ArrayFromString(der.getBytes(), 'ascii')\n return supportedKeys.rsa.unmarshalRsaPrivateKey(der)\n}\n","import type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = 'RSA' | 'Ed25519' | 'secp256k1'\n\ninterface BasePeerId {\n readonly type: PeerIdType\n readonly multihash: MultihashDigest\n readonly privateKey?: Uint8Array\n readonly publicKey?: Uint8Array\n\n toString(): string\n toCID(): CID\n toBytes(): Uint8Array\n equals(other?: PeerId | Uint8Array | string): boolean\n}\n\nexport interface RSAPeerId extends BasePeerId {\n readonly type: 'RSA'\n readonly publicKey?: Uint8Array\n}\n\nexport interface Ed25519PeerId extends BasePeerId {\n readonly type: 'Ed25519'\n readonly publicKey: Uint8Array\n}\n\nexport interface Secp256k1PeerId extends BasePeerId {\n readonly type: 'secp256k1'\n readonly publicKey: Uint8Array\n}\n\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId\n\nexport const peerIdSymbol = Symbol.for('@libp2p/peer-id')\n\nexport function isPeerId (other: any): other is PeerId {\n return other != null && Boolean(other[peerIdSymbol])\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n","import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, encodeMessage, message } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface NoiseExtensions {\n webtransportCerthashes: Uint8Array[]\n}\n\nexport namespace NoiseExtensions {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.webtransportCerthashes != null) {\n for (const value of obj.webtransportCerthashes) {\n w.uint32(10)\n w.bytes(value)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n webtransportCerthashes: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.webtransportCerthashes.push(reader.bytes())\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, NoiseExtensions.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): NoiseExtensions => {\n return decodeMessage(buf, NoiseExtensions.codec())\n }\n}\n\nexport interface NoiseHandshakePayload {\n identityKey: Uint8Array\n identitySig: Uint8Array\n extensions?: NoiseExtensions\n}\n\nexport namespace NoiseHandshakePayload {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.identityKey != null && obj.identityKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.identityKey)\n }\n\n if ((obj.identitySig != null && obj.identitySig.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.identitySig)\n }\n\n if (obj.extensions != null) {\n w.uint32(34)\n NoiseExtensions.codec().encode(obj.extensions, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n identityKey: uint8ArrayAlloc(0),\n identitySig: uint8ArrayAlloc(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.identityKey = reader.bytes()\n break\n }\n case 2: {\n obj.identitySig = reader.bytes()\n break\n }\n case 4: {\n obj.extensions = NoiseExtensions.codec().decode(reader, reader.uint32())\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, NoiseHandshakePayload.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): NoiseHandshakePayload => {\n return decodeMessage(buf, NoiseHandshakePayload.codec())\n }\n}\n","import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n\n this.code = code\n }\n}\n","import { unmarshalPublicKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { type Uint8ArrayList, isUint8ArrayList } from 'uint8arraylist'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { type NoiseExtensions, NoiseHandshakePayload } from './proto/payload.js'\nimport type { bytes } from './@types/basic.js'\nimport type { PeerId } from '@libp2p/interface'\n\nexport async function getPayload (\n localPeer: PeerId,\n staticPublicKey: bytes,\n extensions?: NoiseExtensions\n): Promise {\n const signedPayload = await signPayload(localPeer, getHandshakePayload(staticPublicKey))\n\n if (localPeer.publicKey == null) {\n throw new Error('PublicKey was missing from local PeerId')\n }\n\n return createHandshakePayload(\n localPeer.publicKey,\n signedPayload,\n extensions\n )\n}\n\nexport function createHandshakePayload (\n libp2pPublicKey: Uint8Array,\n signedPayload: Uint8Array,\n extensions?: NoiseExtensions\n): bytes {\n return NoiseHandshakePayload.encode({\n identityKey: libp2pPublicKey,\n identitySig: signedPayload,\n extensions: extensions ?? { webtransportCerthashes: [] }\n }).subarray()\n}\n\nexport async function signPayload (peerId: PeerId, payload: Uint8Array | Uint8ArrayList): Promise {\n if (peerId.privateKey == null) {\n throw new Error('PrivateKey was missing from PeerId')\n }\n\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n\n return privateKey.sign(payload)\n}\n\nexport async function getPeerIdFromPayload (payload: NoiseHandshakePayload): Promise {\n return peerIdFromKeys(payload.identityKey)\n}\n\nexport function decodePayload (payload: Uint8Array | Uint8ArrayList): NoiseHandshakePayload {\n return NoiseHandshakePayload.decode(payload)\n}\n\nexport function getHandshakePayload (publicKey: Uint8Array | Uint8ArrayList): Uint8Array | Uint8ArrayList {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:')\n\n if (publicKey instanceof Uint8Array) {\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length)\n }\n\n publicKey.prepend(prefix)\n\n return publicKey\n}\n\n/**\n * Verifies signed payload, throws on any irregularities.\n *\n * @param {bytes} noiseStaticKey - owner's noise static key\n * @param {bytes} payload - decoded payload\n * @param {PeerId} remotePeer - owner's libp2p peer ID\n * @returns {Promise} - peer ID of payload owner\n */\nexport async function verifySignedPayload (\n noiseStaticKey: Uint8Array | Uint8ArrayList,\n payload: NoiseHandshakePayload,\n remotePeer: PeerId\n): Promise {\n // Unmarshaling from PublicKey protobuf\n const payloadPeerId = await peerIdFromKeys(payload.identityKey)\n if (!payloadPeerId.equals(remotePeer)) {\n throw new Error(`Payload identity key ${payloadPeerId.toString()} does not match expected remote peer ${remotePeer.toString()}`)\n }\n const generatedPayload = getHandshakePayload(noiseStaticKey)\n\n if (payloadPeerId.publicKey == null) {\n throw new Error('PublicKey was missing from PeerId')\n }\n\n if (payload.identitySig == null) {\n throw new Error('Signature was missing from message')\n }\n\n const publicKey = unmarshalPublicKey(payloadPeerId.publicKey)\n\n const valid = await publicKey.verify(generatedPayload, payload.identitySig)\n\n if (!valid) {\n throw new Error(\"Static key doesn't match to peer that signed payload!\")\n }\n\n return payloadPeerId\n}\n\nexport function isValidPublicKey (pk: Uint8Array | Uint8ArrayList): boolean {\n if (!(pk instanceof Uint8Array) && !(isUint8ArrayList(pk))) {\n return false\n }\n\n if (pk.byteLength !== 32) {\n return false\n }\n\n return true\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { bytes, uint64 } from './@types/basic.js'\n\nexport const MIN_NONCE = 0\n// For performance reasons, the nonce is represented as a JS `number`\n// Although JS `number` can safely represent integers up to 2 ** 53 - 1, we choose to only use\n// 4 bytes to store the data for performance reason.\n// This is a slight deviation from the noise spec, which describes the max nonce as 2 ** 64 - 2\n// The effect is that this implementation will need a new handshake to be performed after fewer messages are exchanged than other implementations with full uint64 nonces.\n// this MAX_NONCE is still a large number of messages, so the practical effect of this is negligible.\nexport const MAX_NONCE = 0xffffffff\n\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed'\n\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n private n: uint64\n private readonly bytes: bytes\n private readonly view: DataView\n\n constructor (n = MIN_NONCE) {\n this.n = n\n this.bytes = uint8ArrayAlloc(12)\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength)\n this.view.setUint32(4, n, true)\n }\n\n increment (): void {\n this.n++\n // Even though we're treating the nonce as 8 bytes, RFC7539 specifies 12 bytes for a nonce.\n this.view.setUint32(4, this.n, true)\n }\n\n getBytes (): bytes {\n return this.bytes\n }\n\n getUint64 (): uint64 {\n return this.n\n }\n\n assertValue (): void {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE)\n }\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { Nonce } from '../nonce.js'\nimport type { bytes, bytes32 } from '../@types/basic.js'\nimport type { CipherState, MessageBuffer, SymmetricState } from '../@types/handshake.js'\nimport type { ICryptoInterface } from '../crypto.js'\nimport type { NoiseComponents } from '../index.js'\nimport type { Logger } from '@libp2p/interface'\n\nexport interface DecryptedResult {\n plaintext: Uint8ArrayList | Uint8Array\n valid: boolean\n}\n\nexport interface SplitState {\n cs1: CipherState\n cs2: CipherState\n}\n\nexport abstract class AbstractHandshake {\n public crypto: ICryptoInterface\n private readonly log: Logger\n\n constructor (components: NoiseComponents, crypto: ICryptoInterface) {\n this.log = components.logger.forComponent('libp2p:noise:abstract-handshake')\n this.crypto = crypto\n }\n\n public encryptWithAd (cs: CipherState, ad: Uint8Array, plaintext: Uint8Array | Uint8ArrayList): Uint8Array | Uint8ArrayList {\n const e = this.encrypt(cs.k, cs.n, ad, plaintext)\n cs.n.increment()\n\n return e\n }\n\n public decryptWithAd (cs: CipherState, ad: Uint8Array, ciphertext: Uint8Array | Uint8ArrayList, dst?: Uint8Array): DecryptedResult {\n const { plaintext, valid } = this.decrypt(cs.k, cs.n, ad, ciphertext, dst)\n if (valid) cs.n.increment()\n\n return { plaintext, valid }\n }\n\n // Cipher state related\n protected hasKey (cs: CipherState): boolean {\n return !this.isEmptyKey(cs.k)\n }\n\n protected createEmptyKey (): bytes32 {\n return uint8ArrayAlloc(32)\n }\n\n protected isEmptyKey (k: bytes32): boolean {\n const emptyKey = this.createEmptyKey()\n return uint8ArrayEquals(emptyKey, k)\n }\n\n protected encrypt (k: bytes32, n: Nonce, ad: Uint8Array, plaintext: Uint8Array | Uint8ArrayList): Uint8Array | Uint8ArrayList {\n n.assertValue()\n\n return this.crypto.chaCha20Poly1305Encrypt(plaintext, n.getBytes(), ad, k)\n }\n\n protected encryptAndHash (ss: SymmetricState, plaintext: bytes): Uint8Array | Uint8ArrayList {\n let ciphertext\n if (this.hasKey(ss.cs)) {\n ciphertext = this.encryptWithAd(ss.cs, ss.h, plaintext)\n } else {\n ciphertext = plaintext\n }\n\n this.mixHash(ss, ciphertext)\n return ciphertext\n }\n\n protected decrypt (k: bytes32, n: Nonce, ad: bytes, ciphertext: Uint8Array | Uint8ArrayList, dst?: Uint8Array): DecryptedResult {\n n.assertValue()\n\n const encryptedMessage = this.crypto.chaCha20Poly1305Decrypt(ciphertext, n.getBytes(), ad, k, dst)\n\n if (encryptedMessage) {\n return {\n plaintext: encryptedMessage,\n valid: true\n }\n } else {\n return {\n plaintext: uint8ArrayAlloc(0),\n valid: false\n }\n }\n }\n\n protected decryptAndHash (ss: SymmetricState, ciphertext: Uint8Array | Uint8ArrayList): DecryptedResult {\n let plaintext: Uint8Array | Uint8ArrayList\n let valid = true\n if (this.hasKey(ss.cs)) {\n ({ plaintext, valid } = this.decryptWithAd(ss.cs, ss.h, ciphertext))\n } else {\n plaintext = ciphertext\n }\n\n this.mixHash(ss, ciphertext)\n return { plaintext, valid }\n }\n\n protected dh (privateKey: bytes32, publicKey: Uint8Array | Uint8ArrayList): bytes32 {\n try {\n const derivedU8 = this.crypto.generateX25519SharedKey(privateKey, publicKey)\n\n if (derivedU8.length === 32) {\n return derivedU8\n }\n\n return derivedU8.subarray(0, 32)\n } catch (e) {\n const err = e as Error\n this.log.error('error deriving shared key', err)\n return uint8ArrayAlloc(32)\n }\n }\n\n protected mixHash (ss: SymmetricState, data: Uint8Array | Uint8ArrayList): void {\n ss.h = this.getHash(ss.h, data)\n }\n\n protected getHash (a: Uint8Array, b: Uint8Array | Uint8ArrayList): Uint8Array {\n const u = this.crypto.hashSHA256(new Uint8ArrayList(a, b))\n return u\n }\n\n protected mixKey (ss: SymmetricState, ikm: bytes32): void {\n const [ck, tempK] = this.crypto.getHKDF(ss.ck, ikm)\n ss.cs = this.initializeKey(tempK)\n ss.ck = ck\n }\n\n protected initializeKey (k: bytes32): CipherState {\n return { k, n: new Nonce() }\n }\n\n // Symmetric state related\n\n protected initializeSymmetric (protocolName: string): SymmetricState {\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8')\n const h = this.hashProtocolName(protocolNameBytes)\n\n const ck = h\n const key = this.createEmptyKey()\n const cs: CipherState = this.initializeKey(key)\n\n return { cs, ck, h }\n }\n\n protected hashProtocolName (protocolName: Uint8Array): bytes32 {\n if (protocolName.length <= 32) {\n const h = uint8ArrayAlloc(32)\n h.set(protocolName)\n return h\n } else {\n return this.getHash(protocolName, uint8ArrayAlloc(0))\n }\n }\n\n protected split (ss: SymmetricState): SplitState {\n const [tempk1, tempk2] = this.crypto.getHKDF(ss.ck, uint8ArrayAlloc(0))\n const cs1 = this.initializeKey(tempk1)\n const cs2 = this.initializeKey(tempk2)\n\n return { cs1, cs2 }\n }\n\n protected writeMessageRegular (cs: CipherState, payload: bytes): MessageBuffer {\n const ciphertext = this.encryptWithAd(cs, uint8ArrayAlloc(0), payload)\n const ne = this.createEmptyKey()\n const ns = uint8ArrayAlloc(0)\n\n return { ne, ns, ciphertext }\n }\n\n protected readMessageRegular (cs: CipherState, message: MessageBuffer): DecryptedResult {\n return this.decryptWithAd(cs, uint8ArrayAlloc(0), message.ciphertext)\n }\n}\n","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport { isValidPublicKey } from '../utils.js'\nimport { AbstractHandshake, type DecryptedResult } from './abstract-handshake.js'\nimport type { bytes32, bytes } from '../@types/basic.js'\nimport type { CipherState, HandshakeState, MessageBuffer, NoiseSession } from '../@types/handshake.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class XX extends AbstractHandshake {\n private initializeInitiator (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = uint8ArrayAlloc(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private initializeResponder (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = uint8ArrayAlloc(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private writeMessageA (hs: HandshakeState, payload: bytes, e?: KeyPair): MessageBuffer {\n const ns = uint8ArrayAlloc(0)\n\n if (e !== undefined) {\n hs.e = e\n } else {\n hs.e = this.crypto.generateX25519KeyPair()\n }\n\n const ne = hs.e.publicKey\n\n this.mixHash(hs.ss, ne)\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageB (hs: HandshakeState, payload: bytes): MessageBuffer {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageC (hs: HandshakeState, payload: bytes): { messageBuffer: MessageBuffer, cs1: CipherState, cs2: CipherState, h: bytes } {\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n const ne = this.createEmptyKey()\n const messageBuffer: MessageBuffer = { ne, ns, ciphertext }\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, messageBuffer, cs1, cs2 }\n }\n\n private readMessageA (hs: HandshakeState, message: MessageBuffer): DecryptedResult {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n return this.decryptAndHash(hs.ss, message.ciphertext)\n }\n\n private readMessageB (hs: HandshakeState, message: MessageBuffer): DecryptedResult {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n return { plaintext, valid: (valid1 && valid2) }\n }\n\n private readMessageC (hs: HandshakeState, message: MessageBuffer): { h: bytes, plaintext: Uint8Array | Uint8ArrayList, valid: boolean, cs1: CipherState, cs2: CipherState } {\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, plaintext, valid: (valid1 && valid2), cs1, cs2 }\n }\n\n public initSession (initiator: boolean, prologue: bytes32, s: KeyPair): NoiseSession {\n const psk = this.createEmptyKey()\n const rs = uint8ArrayAlloc(32) // no static key yet\n let hs\n\n if (initiator) {\n hs = this.initializeInitiator(prologue, s, rs, psk)\n } else {\n hs = this.initializeResponder(prologue, s, rs, psk)\n }\n\n return {\n hs,\n i: initiator,\n mc: 0\n }\n }\n\n public sendMessage (session: NoiseSession, message: bytes, ephemeral?: KeyPair): MessageBuffer {\n let messageBuffer: MessageBuffer\n if (session.mc === 0) {\n messageBuffer = this.writeMessageA(session.hs, message, ephemeral)\n } else if (session.mc === 1) {\n messageBuffer = this.writeMessageB(session.hs, message)\n } else if (session.mc === 2) {\n const { h, messageBuffer: resultingBuffer, cs1, cs2 } = this.writeMessageC(session.hs, message)\n messageBuffer = resultingBuffer\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n } else if (session.mc > 2) {\n if (session.i) {\n if (!session.cs1) {\n throw new Error('CS1 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs1, message)\n } else {\n if (!session.cs2) {\n throw new Error('CS2 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs2, message)\n }\n } else {\n throw new Error('Session invalid.')\n }\n\n session.mc++\n return messageBuffer\n }\n\n public recvMessage (session: NoiseSession, message: MessageBuffer): DecryptedResult {\n let plaintext: Uint8Array | Uint8ArrayList = uint8ArrayAlloc(0)\n let valid = false\n if (session.mc === 0) {\n ({ plaintext, valid } = this.readMessageA(session.hs, message))\n } else if (session.mc === 1) {\n ({ plaintext, valid } = this.readMessageB(session.hs, message))\n } else if (session.mc === 2) {\n const { h, plaintext: resultingPlaintext, valid: resultingValid, cs1, cs2 } = this.readMessageC(session.hs, message)\n plaintext = resultingPlaintext\n valid = resultingValid\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n }\n session.mc++\n return { plaintext, valid }\n }\n}\n","import { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { DUMP_SESSION_KEYS } from './constants.js'\nimport type { NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport type { Logger } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function logLocalStaticKeys (s: KeyPair, keyLogger: Logger): void {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return\n }\n\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`)\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`)\n}\n\nexport function logLocalEphemeralKeys (e: KeyPair | undefined, keyLogger: Logger): void {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return\n }\n\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`)\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`)\n } else {\n keyLogger('Missing local ephemeral keys.')\n }\n}\n\nexport function logRemoteStaticKey (rs: Uint8Array | Uint8ArrayList, keyLogger: Logger): void {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return\n }\n\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs.subarray(), 'hex')}`)\n}\n\nexport function logRemoteEphemeralKey (re: Uint8Array | Uint8ArrayList, keyLogger: Logger): void {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return\n }\n\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re.subarray(), 'hex')}`)\n}\n\nexport function logCipherState (session: NoiseSession, keyLogger: Logger): void {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return\n }\n\n if (session.cs1 && session.cs2) {\n keyLogger(`CIPHER_STATE_1 ${session.cs1.n.getUint64()} ${uint8ArrayToString(session.cs1.k, 'hex')}`)\n keyLogger(`CIPHER_STATE_2 ${session.cs2.n.getUint64()} ${uint8ArrayToString(session.cs2.k, 'hex')}`)\n } else {\n keyLogger('Missing cipher state.')\n }\n}\n","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport { decode0, decode1, decode2, encode0, encode1, encode2 } from './encoder.js'\nimport { InvalidCryptoExchangeError, UnexpectedPeerError } from './errors.js'\nimport { XX } from './handshakes/xx.js'\nimport {\n logLocalStaticKeys,\n logLocalEphemeralKeys,\n logRemoteEphemeralKey,\n logRemoteStaticKey,\n logCipherState\n} from './logger.js'\nimport {\n decodePayload,\n getPeerIdFromPayload,\n verifySignedPayload\n} from './utils.js'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { CipherState, NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport type { NoiseComponents } from './index.js'\nimport type { NoiseExtensions } from './proto/payload.js'\nimport type { Logger, PeerId } from '@libp2p/interface'\nimport type { LengthPrefixedStream } from 'it-length-prefixed-stream'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class XXHandshake implements IHandshake {\n public isInitiator: boolean\n public session: NoiseSession\n public remotePeer!: PeerId\n public remoteExtensions: NoiseExtensions = { webtransportCerthashes: [] }\n\n protected payload: bytes\n protected connection: LengthPrefixedStream\n protected xx: XX\n protected staticKeypair: KeyPair\n\n private readonly prologue: bytes32\n private readonly log: Logger\n\n constructor (\n components: NoiseComponents,\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: LengthPrefixedStream,\n remotePeer?: PeerId,\n handshake?: XX\n ) {\n this.log = components.logger.forComponent('libp2p:noise:xxhandshake')\n this.isInitiator = isInitiator\n this.payload = payload\n this.prologue = prologue\n this.staticKeypair = staticKeypair\n this.connection = connection\n if (remotePeer) {\n this.remotePeer = remotePeer\n }\n this.xx = handshake ?? new XX(components, crypto)\n this.session = this.xx.initSession(this.isInitiator, this.prologue, this.staticKeypair)\n }\n\n // stage 0\n public async propose (): Promise {\n logLocalStaticKeys(this.session.hs.s, this.log)\n if (this.isInitiator) {\n this.log.trace('Stage 0 - Initiator starting to send first message.')\n const messageBuffer = this.xx.sendMessage(this.session, uint8ArrayAlloc(0))\n await this.connection.write(encode0(messageBuffer))\n this.log.trace('Stage 0 - Initiator finished sending first message.')\n logLocalEphemeralKeys(this.session.hs.e, this.log)\n } else {\n this.log.trace('Stage 0 - Responder waiting to receive first message...')\n const receivedMessageBuffer = decode0((await this.connection.read()).subarray())\n const { valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 0 validation fail')\n }\n this.log.trace('Stage 0 - Responder received first message.')\n logRemoteEphemeralKey(this.session.hs.re, this.log)\n }\n }\n\n // stage 1\n public async exchange (): Promise {\n if (this.isInitiator) {\n this.log.trace('Stage 1 - Initiator waiting to receive first message from responder...')\n const receivedMessageBuffer = decode1((await this.connection.read()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 1 validation fail')\n }\n this.log.trace('Stage 1 - Initiator received the message.')\n logRemoteEphemeralKey(this.session.hs.re, this.log)\n logRemoteStaticKey(this.session.hs.rs, this.log)\n\n this.log.trace(\"Initiator going to check remote's signature...\")\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteNoiseExtension(decodedPayload.extensions)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n this.log.trace('All good with the signature!')\n } else {\n this.log.trace('Stage 1 - Responder sending out first message with signed payload and static key.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n await this.connection.write(encode1(messageBuffer))\n this.log.trace('Stage 1 - Responder sent the second handshake message with signed payload.')\n logLocalEphemeralKeys(this.session.hs.e, this.log)\n }\n }\n\n // stage 2\n public async finish (): Promise {\n if (this.isInitiator) {\n this.log.trace('Stage 2 - Initiator sending third handshake message.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n await this.connection.write(encode2(messageBuffer))\n this.log.trace('Stage 2 - Initiator sent message with signed payload.')\n } else {\n this.log.trace('Stage 2 - Responder waiting for third handshake message...')\n const receivedMessageBuffer = decode2((await this.connection.read()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 2 validation fail')\n }\n this.log.trace('Stage 2 - Responder received the message, finished handshake.')\n\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteNoiseExtension(decodedPayload.extensions)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n }\n logCipherState(this.session, this.log)\n }\n\n public encrypt (plaintext: Uint8Array | Uint8ArrayList, session: NoiseSession): Uint8Array | Uint8ArrayList {\n const cs = this.getCS(session)\n\n return this.xx.encryptWithAd(cs, uint8ArrayAlloc(0), plaintext)\n }\n\n public decrypt (ciphertext: Uint8Array | Uint8ArrayList, session: NoiseSession, dst?: Uint8Array): { plaintext: Uint8Array | Uint8ArrayList, valid: boolean } {\n const cs = this.getCS(session, false)\n\n return this.xx.decryptWithAd(cs, uint8ArrayAlloc(0), ciphertext, dst)\n }\n\n public getRemoteStaticKey (): Uint8Array | Uint8ArrayList {\n return this.session.hs.rs\n }\n\n private getCS (session: NoiseSession, encryption = true): CipherState {\n if (!session.cs1 || !session.cs2) {\n throw new InvalidCryptoExchangeError('Handshake not completed properly, cipher state does not exist.')\n }\n\n if (this.isInitiator) {\n return encryption ? session.cs1 : session.cs2\n } else {\n return encryption ? session.cs2 : session.cs1\n }\n }\n\n protected setRemoteNoiseExtension (e: NoiseExtensions | null | undefined): void {\n if (e) {\n this.remoteExtensions = e\n }\n }\n}\n","import { decode } from 'it-length-prefixed'\nimport { lpStream, type LengthPrefixedStream } from 'it-length-prefixed-stream'\nimport { duplexPair } from 'it-pair/duplex'\nimport { pipe } from 'it-pipe'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js'\nimport { defaultCrypto } from './crypto/index.js'\nimport { decryptStream, encryptStream } from './crypto/streaming.js'\nimport { uint16BEDecode, uint16BEEncode } from './encoder.js'\nimport { XXHandshake } from './handshake-xx.js'\nimport { type MetricsRegistry, registerMetrics } from './metrics.js'\nimport { getPayload } from './utils.js'\nimport type { bytes } from './@types/basic.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { INoiseConnection, KeyPair } from './@types/libp2p.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport type { NoiseComponents } from './index.js'\nimport type { NoiseExtensions } from './proto/payload.js'\nimport type { MultiaddrConnection, SecuredConnection, PeerId } from '@libp2p/interface'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\ninterface HandshakeParams {\n connection: LengthPrefixedStream\n isInitiator: boolean\n localPeer: PeerId\n remotePeer?: PeerId\n}\n\nexport interface NoiseInit {\n /**\n * x25519 private key, reuse for faster handshakes\n */\n staticNoiseKey?: bytes\n extensions?: NoiseExtensions\n crypto?: ICryptoInterface\n prologueBytes?: Uint8Array\n}\n\nexport class Noise implements INoiseConnection {\n public protocol = '/noise'\n public crypto: ICryptoInterface\n\n private readonly prologue: Uint8Array\n private readonly staticKeys: KeyPair\n private readonly extensions?: NoiseExtensions\n private readonly metrics?: MetricsRegistry\n private readonly components: NoiseComponents\n\n constructor (components: NoiseComponents, init: NoiseInit = {}) {\n const { staticNoiseKey, extensions, crypto, prologueBytes } = init\n const { metrics } = components\n\n this.components = components\n this.crypto = crypto ?? defaultCrypto\n this.extensions = extensions\n this.metrics = metrics ? registerMetrics(metrics) : undefined\n\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKeys = this.crypto.generateX25519KeyPairFromSeed(staticNoiseKey)\n } else {\n this.staticKeys = this.crypto.generateX25519KeyPair()\n }\n this.prologue = prologueBytes ?? uint8ArrayAlloc(0)\n }\n\n /**\n * Encrypt outgoing data to the remote party (handshake as initiator)\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer\n * @param {Stream} connection - streaming iterable duplex that will be encrypted\n * @param {PeerId} remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer.\n * @returns {Promise>}\n */\n public async secureOutbound > = MultiaddrConnection> (localPeer: PeerId, connection: Stream, remotePeer?: PeerId): Promise> {\n const wrappedConnection = lpStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: true,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n connection.source = conn.source\n connection.sink = conn.sink\n\n return {\n conn: connection,\n remoteExtensions: handshake.remoteExtensions,\n remotePeer: handshake.remotePeer\n }\n }\n\n /**\n * Decrypt incoming data (handshake as responder).\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer.\n * @param {Stream} connection - streaming iterable duplex that will be encrypted.\n * @param {PeerId} remotePeer - optional PeerId of the initiating peer, if known. This may only exist during transport upgrades.\n * @returns {Promise>}\n */\n public async secureInbound > = MultiaddrConnection> (localPeer: PeerId, connection: Stream, remotePeer?: PeerId): Promise> {\n const wrappedConnection = lpStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: false,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n connection.source = conn.source\n connection.sink = conn.sink\n\n return {\n conn: connection,\n remotePeer: handshake.remotePeer,\n remoteExtensions: handshake.remoteExtensions\n }\n }\n\n /**\n * If Noise pipes supported, tries IK handshake first with XX as fallback if it fails.\n * If noise pipes disabled or remote peer static key is unknown, use XX.\n *\n * @param {HandshakeParams} params\n */\n private async performHandshake (params: HandshakeParams): Promise {\n const payload = await getPayload(params.localPeer, this.staticKeys.publicKey, this.extensions)\n\n // run XX handshake\n return this.performXXHandshake(params, payload)\n }\n\n private async performXXHandshake (\n params: HandshakeParams,\n payload: bytes\n ): Promise {\n const { isInitiator, remotePeer, connection } = params\n const handshake = new XXHandshake(\n this.components,\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n remotePeer\n )\n\n try {\n await handshake.propose()\n await handshake.exchange()\n await handshake.finish()\n this.metrics?.xxHandshakeSuccesses.increment()\n } catch (e: unknown) {\n this.metrics?.xxHandshakeErrors.increment()\n if (e instanceof Error) {\n e.message = `Error occurred during XX handshake: ${e.message}`\n throw e\n }\n }\n\n return handshake\n }\n\n private async createSecureConnection (\n connection: LengthPrefixedStream>>,\n handshake: IHandshake\n ): Promise>> {\n // Create encryption box/unbox wrapper\n const [secure, user] = duplexPair()\n const network = connection.unwrap()\n\n await pipe(\n secure, // write to wrapper\n encryptStream(handshake, this.metrics), // encrypt data + prefix with message length\n network, // send to the remote peer\n (source) => decode(source, { lengthDecoder: uint16BEDecode }), // read message length prefix\n decryptStream(handshake, this.metrics), // decrypt the incoming data\n secure // pipe to the wrapper\n )\n\n return user\n }\n}\n","import type { Counter, Metrics } from '@libp2p/interface'\n\nexport type MetricsRegistry = Record\n\nexport function registerMetrics (metrics: Metrics): MetricsRegistry {\n return {\n xxHandshakeSuccesses: metrics.registerCounter(\n 'libp2p_noise_xxhandshake_successes_total', {\n help: 'Total count of noise xxHandshakes successes_'\n }),\n\n xxHandshakeErrors: metrics.registerCounter(\n 'libp2p_noise_xxhandshake_error_total', {\n help: 'Total count of noise xxHandshakes errors'\n }),\n\n encryptedPackets: metrics.registerCounter(\n 'libp2p_noise_encrypted_packets_total', {\n help: 'Total count of noise encrypted packets successfully'\n }),\n\n decryptedPackets: metrics.registerCounter(\n 'libp2p_noise_decrypted_packets_total', {\n help: 'Total count of noise decrypted packets'\n }),\n\n decryptErrors: metrics.registerCounter(\n 'libp2p_noise_decrypt_errors_total', {\n help: 'Total count of noise decrypt errors'\n })\n }\n}\n","import { pair } from './index.js'\nimport type { Duplex, Source } from 'it-stream-types'\n\n/**\n * Two duplex streams that are attached to each other\n */\nexport function duplexPair (): [Duplex, Source, Promise>, Duplex, Source, Promise>] {\n const a = pair()\n const b = pair()\n return [\n {\n source: a.source,\n sink: b.sink\n },\n {\n source: b.source,\n sink: a.sink\n }\n ]\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js'\nimport { uint16BEEncode } from '../encoder.js'\nimport type { IHandshake } from '../@types/handshake-interface.js'\nimport type { MetricsRegistry } from '../metrics.js'\nimport type { Transform } from 'it-stream-types'\n\nconst CHACHA_TAG_LENGTH = 16\n\n// Returns generator that encrypts payload from the user\nexport function encryptStream (handshake: IHandshake, metrics?: MetricsRegistry): Transform> {\n return async function * (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG\n if (end > chunk.length) {\n end = chunk.length\n }\n\n let data: Uint8Array | Uint8ArrayList\n\n if (chunk instanceof Uint8Array) {\n data = handshake.encrypt(chunk.subarray(i, end), handshake.session)\n } else {\n data = handshake.encrypt(chunk.sublist(i, end), handshake.session)\n }\n\n metrics?.encryptedPackets.increment()\n\n yield new Uint8ArrayList(uint16BEEncode(data.byteLength), data)\n }\n }\n }\n}\n\n// Decrypt received payload to the user\nexport function decryptStream (handshake: IHandshake, metrics?: MetricsRegistry): Transform, AsyncGenerator> {\n return async function * (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES\n if (end > chunk.length) {\n end = chunk.length\n }\n\n if (end - CHACHA_TAG_LENGTH < i) {\n throw new Error('Invalid chunk')\n }\n\n const encrypted = chunk.sublist(i, end)\n // memory allocation is not cheap so reuse the encrypted Uint8Array\n // see https://github.com/ChainSafe/js-libp2p-noise/pull/242#issue-1422126164\n // this is ok because chacha20 reads bytes one by one and don't reread after that\n // it's also tested in https://github.com/ChainSafe/as-chacha20poly1305/pull/1/files#diff-25252846b58979dcaf4e41d47b3eadd7e4f335e7fb98da6c049b1f9cd011f381R48\n const dst = chunk.subarray(i, end - CHACHA_TAG_LENGTH)\n const { plaintext: decrypted, valid } = handshake.decrypt(encrypted, handshake.session, dst)\n if (!valid) {\n metrics?.decryptErrors.increment()\n throw new Error('Failed to validate decrypted chunk')\n }\n metrics?.decryptedPackets.increment()\n yield decrypted\n }\n }\n }\n}\n","import { Noise } from './noise.js'\nimport type { NoiseInit } from './noise.js'\nimport type { NoiseExtensions } from './proto/payload.js'\nimport type { ComponentLogger, ConnectionEncrypter, Metrics } from '@libp2p/interface'\nexport type { ICryptoInterface } from './crypto.js'\nexport { pureJsCrypto } from './crypto/js.js'\n\nexport interface NoiseComponents {\n logger: ComponentLogger\n metrics?: Metrics\n}\n\nexport function noise (init: NoiseInit = {}): (components: NoiseComponents) => ConnectionEncrypter {\n return (components: NoiseComponents) => new Noise(components, init)\n}\n","import type { TypedEventTarget } from '../event-target.js'\nimport type { PeerInfo } from '../peer-info/index.js'\n\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerDiscovery instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerDiscovery, PeerDiscovery } from '@libp2p/peer-discovery'\n *\n * class MyPeerDiscoverer implements PeerDiscovery {\n * get [peerDiscovery] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery')\n\n/**\n * Implementers of this interface can provide a PeerDiscovery implementation to\n * interested callers.\n */\nexport interface PeerDiscoveryProvider {\n [peerDiscoverySymbol]: PeerDiscovery\n}\n\nexport interface PeerDiscoveryEvents {\n 'peer': CustomEvent\n}\n\nexport interface PeerDiscovery extends TypedEventTarget {}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","\n/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n public readonly code: string\n public readonly type: string\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.code = AbortError.code\n this.type = AbortError.type\n }\n\n static readonly code = 'ABORT_ERR'\n\n static readonly type = 'aborted'\n}\n\nexport class CodeError = Record> extends Error {\n public readonly props: T\n\n constructor (\n message: string,\n public readonly code: string,\n props?: T\n ) {\n super(message)\n\n this.name = props?.name ?? 'CodeError'\n this.props = props ?? {} as T // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\n","// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n function encode (source) {\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","const empty = new Uint8Array(0)\n\n/**\n * @param {Uint8Array} d\n */\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n\n/**\n * @param {string} hex\n */\nconst fromHex = hex => {\n const hexes = hex.match(/../g)\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\n/**\n * @param {Uint8Array} aa\n * @param {Uint8Array} bb\n */\nconst equals = (aa, bb) => {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o\n * @returns {Uint8Array}\n */\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {any} o\n * @returns {o is ArrayBuffer|ArrayBufferView}\n */\nconst isBinary = o =>\n o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nconst fromString = str => (new TextEncoder()).encode(str)\n\n/**\n * @param {Uint8Array} b\n * @returns {string}\n */\nconst toString = b => (new TextDecoder()).decode(b)\n\nexport { equals, coerce, isBinary, fromHex, toHex, fromString, toString, empty }\n","import basex from '../../vendor/base-x.js'\nimport { coerce } from '../bytes.js'\n// Linter can't see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseEncoder}\n * @implements {API.BaseEncoder}\n */\nclass Encoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n */\n constructor (name, prefix, baseEncode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {API.Multibase}\n */\n encode (bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * @template {string} Prefix\n */\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.UnibaseDecoder}\n * @implements {API.BaseDecoder}\n */\nclass Decoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(text:string) => Uint8Array} baseDecode\n */\n constructor (name, prefix, baseDecode) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n /** @private */\n this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))\n this.baseDecode = baseDecode\n }\n\n /**\n * @param {string} text\n */\n decode (text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n}\n\n/**\n * @template {string} Prefix\n * @typedef {Record>} Decoders\n */\n\n/**\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.CombobaseDecoder}\n */\nclass ComposedDecoder {\n /**\n * @param {Decoders} decoders\n */\n constructor (decoders) {\n this.decoders = decoders\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n\n /**\n * @param {string} input\n * @returns {Uint8Array}\n */\n decode (input) {\n const prefix = /** @type {Prefix} */ (input[0])\n const decoder = this.decoders[prefix]\n if (decoder) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\n/**\n * @template {string} L\n * @template {string} R\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} left\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} right\n * @returns {ComposedDecoder}\n */\nexport const or = (left, right) => new ComposedDecoder(/** @type {Decoders} */({\n ...(left.decoders || { [/** @type API.UnibaseDecoder */(left).prefix]: left }),\n ...(right.decoders || { [/** @type API.UnibaseDecoder */(right).prefix]: right })\n}))\n\n/**\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseCodec}\n * @implements {API.MultibaseEncoder}\n * @implements {API.MultibaseDecoder}\n * @implements {API.BaseCodec}\n * @implements {API.BaseEncoder}\n * @implements {API.BaseDecoder}\n */\nexport class Codec {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n * @param {(text:string) => Uint8Array} baseDecode\n */\n constructor (name, prefix, baseEncode, baseDecode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n /**\n * @param {Uint8Array} input\n */\n encode (input) {\n return this.encoder.encode(input)\n }\n\n /**\n * @param {string} input\n */\n decode (input) {\n return this.decoder.decode(input)\n }\n}\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {(bytes:Uint8Array) => string} options.encode\n * @param {(input:string) => Uint8Array} options.decode\n * @returns {Codec}\n */\nexport const from = ({ name, prefix, encode, decode }) =>\n new Codec(name, prefix, encode, decode)\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @returns {Codec}\n */\nexport const baseX = ({ prefix, name, alphabet }) => {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n /**\n * @param {string} text\n */\n decode: text => coerce(decode(text))\n })\n}\n\n/**\n * @param {string} string\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @param {string} name\n * @returns {Uint8Array}\n */\nconst decode = (string, alphabet, bitsPerChar, name) => {\n // Build the character lookup table:\n /** @type {Record} */\n const codes = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\n/**\n * @param {Uint8Array} data\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @returns {string}\n */\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * bitsPerChar) & 7) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n *\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @param {number} options.bitsPerChar\n */\nexport const rfc4648 = ({ name, prefix, bitsPerChar, alphabet }) => {\n return from({\n prefix,\n name,\n encode (input) {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input) {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","var encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from '../vendor/varint.js'\n\n/**\n * @param {Uint8Array} data\n * @param {number} [offset=0]\n * @returns {[number, number]}\n */\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\n/**\n * @param {number} int\n * @param {Uint8Array} target\n * @param {number} [offset=0]\n */\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset)\n return target\n}\n\n/**\n * @param {number} int\n * @returns {number}\n */\nexport const encodingLength = (int) => {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\n\n/**\n * Creates a multihash digest.\n *\n * @template {number} Code\n * @param {Code} code\n * @param {Uint8Array} digest\n */\nexport const create = (code, digest) => {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n *\n * @param {Uint8Array} multihash\n * @returns {MultihashDigest}\n */\nexport const decode = (multihash) => {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * @param {MultihashDigest} a\n * @param {unknown} b\n * @returns {b is MultihashDigest}\n */\nexport const equals = (a, b) => {\n if (a === b) {\n return true\n } else {\n const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * @typedef {import('./interface.js').MultihashDigest} MultihashDigest\n */\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n *\n * @template {number} Code\n * @template {number} Size\n * @class\n * @implements {MultihashDigest}\n */\nexport class Digest {\n /**\n * Creates a multihash digest.\n *\n * @param {Code} code\n * @param {Size} size\n * @param {Uint8Array} digest\n * @param {Uint8Array} bytes\n */\n constructor (code, size, digest, bytes) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from \"./link/interface.js\"\nimport * as varint from './varint.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\n/**\n * @template {API.Link} T\n * @template {string} Prefix\n * @param {T} link\n * @param {API.MultibaseEncoder} [base]\n * @returns {API.ToString}\n */\nexport const format = (link, base) => {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder<\"z\">} */ (base) || base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder} */ (base || base32.encoder)\n )\n }\n}\n\n/**\n * @template {API.UnknownLink} Link\n * @param {Link} link\n * @returns {API.LinkJSON}\n */\nexport const toJSON = (link) => ({\n '/': format(link)\n})\n\n/**\n * @template {API.UnknownLink} Link\n * @param {API.LinkJSON} json\n */\nexport const fromJSON = (json) =>\n CID.parse(json['/'])\n\n/** @type {WeakMap>} */\nconst cache = new WeakMap()\n\n/**\n * @param {API.UnknownLink} cid\n * @returns {Map}\n */\nconst baseCache = cid => {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\n/**\n * @template {unknown} [Data=unknown]\n * @template {number} [Format=number]\n * @template {number} [Alg=number]\n * @template {API.Version} [Version=API.Version]\n * @implements {API.Link}\n */\n\nexport class CID {\n /**\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content.\n * @param {Uint8Array} bytes\n */\n constructor (version, code, multihash, bytes) {\n /** @readonly */\n this.code = code\n /** @readonly */\n this.version = version\n /** @readonly */\n this.multihash = multihash\n /** @readonly */\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n /** @readonly */\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID () {\n return this\n }\n\n // ArrayBufferView\n get byteOffset () {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength () {\n return this.bytes.byteLength\n }\n\n /**\n * @returns {CID}\n */\n toV0 () {\n switch (this.version) {\n case 0: {\n return /** @type {CID} */ (this)\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return /** @type {CID} */ (\n CID.createV0(\n /** @type {API.MultihashDigest} */ (multihash)\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @returns {CID}\n */\n toV1 () {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return /** @type {CID} */ (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return /** @type {CID} */ (this)\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @param {unknown} other\n * @returns {other is CID}\n */\n equals (other) {\n return CID.equals(this, other)\n }\n\n /**\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {API.Link} self\n * @param {unknown} other\n * @returns {other is CID}\n */\n static equals (self, other) {\n const unknown =\n /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (\n other\n )\n return (\n unknown &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n /**\n * @param {API.MultibaseEncoder} [base]\n * @returns {string}\n */\n toString (base) {\n return format(this, base)\n }\n\n /**\n * @returns {API.LinkJSON}\n */\n toJSON () {\n return { '/': format(this) }\n }\n\n link () {\n return this\n }\n\n get [Symbol.toStringTag] () {\n return 'CID'\n }\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @template {unknown} U\n * @param {API.Link|U} input\n * @returns {CID|null}\n */\n static asCID (input) {\n if (input == null) {\n return null\n }\n\n const value = /** @type {any} */ (input)\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n /** @type {API.MultihashDigest} */ (multihash),\n bytes || encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest =\n /** @type {API.MultihashDigest} */\n (Digest.decode(multihash))\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} digest - (Multi)hash of the of the content.\n * @returns {CID}\n */\n static create (version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n *\n * @template {unknown} [T=unknown]\n * @param {API.MultihashDigest} digest - Multihash.\n * @returns {CID}\n */\n static createV0 (digest) {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @param {Code} code - Content encoding format code.\n * @param {API.MultihashDigest} digest - Miltihash of the content.\n * @returns {CID}\n */\n static createV1 (code, digest) {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ByteView>} bytes\n * @returns {CID}\n */\n static decode (bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n *\n * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} bytes\n * @returns {[CID, Uint8Array]}\n */\n static decodeFirst (bytes) {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(/** @type {API.MultihashDigest} */ (digest))\n : CID.createV1(specs.codec, digest)\n return [/** @type {CID} */(cid), bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n *\n * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} initialBytes\n * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}\n */\n static inspectBytes (initialBytes) {\n let offset = 0\n const next = () => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = /** @type {V} */ (next())\n let codec = /** @type {C} */ (DAG_PB_CODE)\n if (/** @type {number} */(version) === 18) {\n // CIDv0\n version = /** @type {V} */ (0)\n offset = 0\n } else {\n codec = /** @type {C} */ (next())\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = /** @type {A} */ (next()) // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n *\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {CID}\n */\n static parse (source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {[Prefix, API.ByteView>]}\n */\nconst parseCIDtoBytes = (source, base) => {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base || base58btc\n return [\n /** @type {Prefix} */ (base58btc.prefix),\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base || base58btc\n return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base || base32\n return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [/** @type {Prefix} */(source[0]), base.decode(source)]\n }\n }\n}\n\n/**\n *\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder<'z'>} base\n */\nconst toStringV0 = (bytes, cache, base) => {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder} base\n */\nconst toStringV1 = (bytes, cache, base) => {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\n/**\n * @param {API.Version} version\n * @param {number} code\n * @param {Uint8Array} multihash\n * @returns {Uint8Array}\n */\nconst encodeCID = (version, code, multihash) => {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n function encode (source) {\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","const empty = new Uint8Array(0)\n\n/**\n * @param {Uint8Array} d\n */\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n\n/**\n * @param {string} hex\n */\nconst fromHex = hex => {\n const hexes = hex.match(/../g)\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\n/**\n * @param {Uint8Array} aa\n * @param {Uint8Array} bb\n */\nconst equals = (aa, bb) => {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o\n * @returns {Uint8Array}\n */\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {any} o\n * @returns {o is ArrayBuffer|ArrayBufferView}\n */\nconst isBinary = o =>\n o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nconst fromString = str => (new TextEncoder()).encode(str)\n\n/**\n * @param {Uint8Array} b\n * @returns {string}\n */\nconst toString = b => (new TextDecoder()).decode(b)\n\nexport { equals, coerce, isBinary, fromHex, toHex, fromString, toString, empty }\n","import basex from '../../vendor/base-x.js'\nimport { coerce } from '../bytes.js'\n// Linter can't see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseEncoder}\n * @implements {API.BaseEncoder}\n */\nclass Encoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n */\n constructor (name, prefix, baseEncode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {API.Multibase}\n */\n encode (bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * @template {string} Prefix\n */\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.UnibaseDecoder}\n * @implements {API.BaseDecoder}\n */\nclass Decoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(text:string) => Uint8Array} baseDecode\n */\n constructor (name, prefix, baseDecode) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n /** @private */\n this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))\n this.baseDecode = baseDecode\n }\n\n /**\n * @param {string} text\n */\n decode (text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n}\n\n/**\n * @template {string} Prefix\n * @typedef {Record>} Decoders\n */\n\n/**\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.CombobaseDecoder}\n */\nclass ComposedDecoder {\n /**\n * @param {Decoders} decoders\n */\n constructor (decoders) {\n this.decoders = decoders\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n\n /**\n * @param {string} input\n * @returns {Uint8Array}\n */\n decode (input) {\n const prefix = /** @type {Prefix} */ (input[0])\n const decoder = this.decoders[prefix]\n if (decoder) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\n/**\n * @template {string} L\n * @template {string} R\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} left\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} right\n * @returns {ComposedDecoder}\n */\nexport const or = (left, right) => new ComposedDecoder(/** @type {Decoders} */({\n ...(left.decoders || { [/** @type API.UnibaseDecoder */(left).prefix]: left }),\n ...(right.decoders || { [/** @type API.UnibaseDecoder */(right).prefix]: right })\n}))\n\n/**\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseCodec}\n * @implements {API.MultibaseEncoder}\n * @implements {API.MultibaseDecoder}\n * @implements {API.BaseCodec}\n * @implements {API.BaseEncoder}\n * @implements {API.BaseDecoder}\n */\nexport class Codec {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n * @param {(text:string) => Uint8Array} baseDecode\n */\n constructor (name, prefix, baseEncode, baseDecode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n /**\n * @param {Uint8Array} input\n */\n encode (input) {\n return this.encoder.encode(input)\n }\n\n /**\n * @param {string} input\n */\n decode (input) {\n return this.decoder.decode(input)\n }\n}\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {(bytes:Uint8Array) => string} options.encode\n * @param {(input:string) => Uint8Array} options.decode\n * @returns {Codec}\n */\nexport const from = ({ name, prefix, encode, decode }) =>\n new Codec(name, prefix, encode, decode)\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @returns {Codec}\n */\nexport const baseX = ({ prefix, name, alphabet }) => {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n /**\n * @param {string} text\n */\n decode: text => coerce(decode(text))\n })\n}\n\n/**\n * @param {string} string\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @param {string} name\n * @returns {Uint8Array}\n */\nconst decode = (string, alphabet, bitsPerChar, name) => {\n // Build the character lookup table:\n /** @type {Record} */\n const codes = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\n/**\n * @param {Uint8Array} data\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @returns {string}\n */\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * bitsPerChar) & 7) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n *\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @param {number} options.bitsPerChar\n */\nexport const rfc4648 = ({ name, prefix, bitsPerChar, alphabet }) => {\n return from({\n prefix,\n name,\n encode (input) {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input) {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])))\nconst alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])))\n\n/**\n * @param {Uint8Array} data\n * @returns {string}\n */\nfunction encode (data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nfunction decode (str) {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[/** @type {number} */ (char.codePointAt(0))]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","// @ts-check\n\nimport { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","// @ts-check\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => textEncoder.encode(JSON.stringify(node))\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => JSON.parse(textDecoder.decode(data))\n","// @ts-check\n\nimport { coerce } from '../bytes.js'\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nexport const name = 'raw'\nexport const code = 0x55\n\n/**\n * @param {Uint8Array} node\n * @returns {ByteView}\n */\nexport const encode = (node) => coerce(node)\n\n/**\n * @param {ByteView} data\n * @returns {Uint8Array}\n */\nexport const decode = (data) => coerce(data)\n","var encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from '../vendor/varint.js'\n\n/**\n * @param {Uint8Array} data\n * @param {number} [offset=0]\n * @returns {[number, number]}\n */\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\n/**\n * @param {number} int\n * @param {Uint8Array} target\n * @param {number} [offset=0]\n */\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset)\n return target\n}\n\n/**\n * @param {number} int\n * @returns {number}\n */\nexport const encodingLength = (int) => {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\n\n/**\n * Creates a multihash digest.\n *\n * @template {number} Code\n * @param {Code} code\n * @param {Uint8Array} digest\n */\nexport const create = (code, digest) => {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n *\n * @param {Uint8Array} multihash\n * @returns {MultihashDigest}\n */\nexport const decode = (multihash) => {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * @param {MultihashDigest} a\n * @param {unknown} b\n * @returns {b is MultihashDigest}\n */\nexport const equals = (a, b) => {\n if (a === b) {\n return true\n } else {\n const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * @typedef {import('./interface.js').MultihashDigest} MultihashDigest\n */\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n *\n * @template {number} Code\n * @template {number} Size\n * @class\n * @implements {MultihashDigest}\n */\nexport class Digest {\n /**\n * Creates a multihash digest.\n *\n * @param {Code} code\n * @param {Size} size\n * @param {Uint8Array} digest\n * @param {Uint8Array} bytes\n */\n constructor (code, size, digest, bytes) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\n/** @type {(input:Uint8Array) => Uint8Array} */\nconst encode = coerce\n\n/**\n * @param {Uint8Array} input\n * @returns {Digest.Digest}\n */\nconst digest = (input) => Digest.create(code, encode(input))\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\n\n/**\n * @template {string} Name\n * @template {number} Code\n * @param {object} options\n * @param {Name} options.name\n * @param {Code} options.code\n * @param {(input: Uint8Array) => Await} options.encode\n */\nexport const from = ({ name, code, encode }) => new Hasher(name, code, encode)\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n *\n * @template {string} Name\n * @template {number} Code\n * @class\n * @implements {MultihashHasher}\n */\nexport class Hasher {\n /**\n *\n * @param {Name} name\n * @param {Code} code\n * @param {(input: Uint8Array) => Await} encode\n */\n constructor (name, code, encode) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n /**\n * @param {Uint8Array} input\n * @returns {Await>}\n */\n digest (input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * @template {number} Alg\n * @typedef {import('./interface.js').MultihashHasher} MultihashHasher\n */\n\n/**\n * @template T\n * @typedef {Promise|T} Await\n */\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\n/**\n * @param {AlgorithmIdentifier} name\n */\nconst sha = name =>\n /**\n * @param {Uint8Array} data\n */\n async data => new Uint8Array(await crypto.subtle.digest(name, data))\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from \"./link/interface.js\"\nimport * as varint from './varint.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\n/**\n * @template {API.Link} T\n * @template {string} Prefix\n * @param {T} link\n * @param {API.MultibaseEncoder} [base]\n * @returns {API.ToString}\n */\nexport const format = (link, base) => {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder<\"z\">} */ (base) || base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder} */ (base || base32.encoder)\n )\n }\n}\n\n/**\n * @template {API.UnknownLink} Link\n * @param {Link} link\n * @returns {API.LinkJSON}\n */\nexport const toJSON = (link) => ({\n '/': format(link)\n})\n\n/**\n * @template {API.UnknownLink} Link\n * @param {API.LinkJSON} json\n */\nexport const fromJSON = (json) =>\n CID.parse(json['/'])\n\n/** @type {WeakMap>} */\nconst cache = new WeakMap()\n\n/**\n * @param {API.UnknownLink} cid\n * @returns {Map}\n */\nconst baseCache = cid => {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\n/**\n * @template {unknown} [Data=unknown]\n * @template {number} [Format=number]\n * @template {number} [Alg=number]\n * @template {API.Version} [Version=API.Version]\n * @implements {API.Link}\n */\n\nexport class CID {\n /**\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content.\n * @param {Uint8Array} bytes\n */\n constructor (version, code, multihash, bytes) {\n /** @readonly */\n this.code = code\n /** @readonly */\n this.version = version\n /** @readonly */\n this.multihash = multihash\n /** @readonly */\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n /** @readonly */\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID () {\n return this\n }\n\n // ArrayBufferView\n get byteOffset () {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength () {\n return this.bytes.byteLength\n }\n\n /**\n * @returns {CID}\n */\n toV0 () {\n switch (this.version) {\n case 0: {\n return /** @type {CID} */ (this)\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return /** @type {CID} */ (\n CID.createV0(\n /** @type {API.MultihashDigest} */ (multihash)\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @returns {CID}\n */\n toV1 () {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return /** @type {CID} */ (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return /** @type {CID} */ (this)\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @param {unknown} other\n * @returns {other is CID}\n */\n equals (other) {\n return CID.equals(this, other)\n }\n\n /**\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {API.Link} self\n * @param {unknown} other\n * @returns {other is CID}\n */\n static equals (self, other) {\n const unknown =\n /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (\n other\n )\n return (\n unknown &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n /**\n * @param {API.MultibaseEncoder} [base]\n * @returns {string}\n */\n toString (base) {\n return format(this, base)\n }\n\n /**\n * @returns {API.LinkJSON}\n */\n toJSON () {\n return { '/': format(this) }\n }\n\n link () {\n return this\n }\n\n get [Symbol.toStringTag] () {\n return 'CID'\n }\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @template {unknown} U\n * @param {API.Link|U} input\n * @returns {CID|null}\n */\n static asCID (input) {\n if (input == null) {\n return null\n }\n\n const value = /** @type {any} */ (input)\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n /** @type {API.MultihashDigest} */ (multihash),\n bytes || encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest =\n /** @type {API.MultihashDigest} */\n (Digest.decode(multihash))\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} digest - (Multi)hash of the of the content.\n * @returns {CID}\n */\n static create (version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n *\n * @template {unknown} [T=unknown]\n * @param {API.MultihashDigest} digest - Multihash.\n * @returns {CID}\n */\n static createV0 (digest) {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @param {Code} code - Content encoding format code.\n * @param {API.MultihashDigest} digest - Miltihash of the content.\n * @returns {CID}\n */\n static createV1 (code, digest) {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ByteView>} bytes\n * @returns {CID}\n */\n static decode (bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n *\n * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} bytes\n * @returns {[CID, Uint8Array]}\n */\n static decodeFirst (bytes) {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(/** @type {API.MultihashDigest} */ (digest))\n : CID.createV1(specs.codec, digest)\n return [/** @type {CID} */(cid), bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n *\n * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} initialBytes\n * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}\n */\n static inspectBytes (initialBytes) {\n let offset = 0\n const next = () => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = /** @type {V} */ (next())\n let codec = /** @type {C} */ (DAG_PB_CODE)\n if (/** @type {number} */(version) === 18) {\n // CIDv0\n version = /** @type {V} */ (0)\n offset = 0\n } else {\n codec = /** @type {C} */ (next())\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = /** @type {A} */ (next()) // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n *\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {CID}\n */\n static parse (source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {[Prefix, API.ByteView>]}\n */\nconst parseCIDtoBytes = (source, base) => {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base || base58btc\n return [\n /** @type {Prefix} */ (base58btc.prefix),\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base || base58btc\n return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base || base32\n return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [/** @type {Prefix} */(source[0]), base.decode(source)]\n }\n }\n}\n\n/**\n *\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder<'z'>} base\n */\nconst toStringV0 = (bytes, cache, base) => {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder} base\n */\nconst toStringV1 = (bytes, cache, base) => {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\n/**\n * @param {API.Version} version\n * @param {number} code\n * @param {Uint8Array} multihash\n * @returns {Uint8Array}\n */\nconst encodeCID = (version, code, multihash) => {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","// @ts-check\n\nimport * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nconst bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nconst hashes = { ...sha2, ...identity }\nconst codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes, hashes, bases, codecs }\n","/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array {\n if (globalThis.Buffer != null) {\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n }\n\n return buf\n}\n","import { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n if (globalThis.Buffer?.alloc != null) {\n return asUint8Array(globalThis.Buffer.alloc(size))\n }\n\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n if (globalThis.Buffer?.allocUnsafe != null) {\n return asUint8Array(globalThis.Buffer.allocUnsafe(size))\n }\n\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport { allocUnsafe } from '../alloc.js'\nimport type { MultibaseCodec } from 'multiformats'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8')\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { allocUnsafe } from './alloc.js'\nimport { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed ArrayLikes\n */\nexport function concat (arrays: Array>, length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n",null,null,"import { parseIP } from \"@chainsafe/is-ip/parse\";\nimport { allFF, deepEqual } from \"./util.js\";\n\nexport const IPv4Len = 4;\nexport const IPv6Len = 16;\n\nexport const maxIPv6Octet = parseInt(\"0xFFFF\", 16);\nexport const ipv4Prefix = new Uint8Array([\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255,\n]);\n\nexport interface IpNetRaw {\n network: Uint8Array;\n mask: Uint8Array;\n}\n\nexport function maskIp(ip: Uint8Array, mask: Uint8Array): Uint8Array {\n if (mask.length === IPv6Len && ip.length === IPv4Len && allFF(mask, 0, 11)) {\n mask = mask.slice(12);\n }\n if (\n mask.length === IPv4Len &&\n ip.length === IPv6Len &&\n deepEqual(ip, ipv4Prefix, 0, 11)\n ) {\n ip = ip.slice(12);\n }\n const n = ip.length;\n if (n != mask.length) {\n throw new Error(\"Failed to mask ip\");\n }\n const out = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n out[i] = ip[i] & mask[i];\n }\n return out;\n}\n\nexport function containsIp(\n net: IpNetRaw,\n ip: Uint8Array | number[] | string\n): boolean {\n if (typeof ip === \"string\") {\n ip = parseIP(ip)!;\n }\n if (ip == null) throw new Error(\"Invalid ip\");\n if (ip.length !== net.network.length) {\n return false;\n }\n for (let i = 0; i < ip.length; i++) {\n if ((net.network[i] & net.mask[i]) !== (ip[i] & net.mask[i])) {\n return false;\n }\n }\n return true;\n}\n\nexport function iPv4FromIPv6(ip: Uint8Array): Uint8Array {\n if (!isIPv4mappedIPv6(ip)) {\n throw new Error(\"Must have 0xffff prefix\");\n }\n return ip.slice(12);\n}\n\nexport function isIPv4mappedIPv6(ip: Uint8Array | number[]): boolean {\n return deepEqual(ip, ipv4Prefix, 0, 11);\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])))\nconst alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])))\n\n/**\n * @param {Uint8Array} data\n * @returns {string}\n */\nfunction encode (data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nfunction decode (str) {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[/** @type {number} */ (char.codePointAt(0))]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","// @ts-check\n\nimport { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","// @ts-check\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => textEncoder.encode(JSON.stringify(node))\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => JSON.parse(textDecoder.decode(data))\n","// @ts-check\n\nimport { coerce } from '../bytes.js'\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nexport const name = 'raw'\nexport const code = 0x55\n\n/**\n * @param {Uint8Array} node\n * @returns {ByteView}\n */\nexport const encode = (node) => coerce(node)\n\n/**\n * @param {ByteView} data\n * @returns {Uint8Array}\n */\nexport const decode = (data) => coerce(data)\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\n/** @type {(input:Uint8Array) => Uint8Array} */\nconst encode = coerce\n\n/**\n * @param {Uint8Array} input\n * @returns {Digest.Digest}\n */\nconst digest = (input) => Digest.create(code, encode(input))\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\n\n/**\n * @template {string} Name\n * @template {number} Code\n * @param {object} options\n * @param {Name} options.name\n * @param {Code} options.code\n * @param {(input: Uint8Array) => Await} options.encode\n */\nexport const from = ({ name, code, encode }) => new Hasher(name, code, encode)\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n *\n * @template {string} Name\n * @template {number} Code\n * @class\n * @implements {MultihashHasher}\n */\nexport class Hasher {\n /**\n *\n * @param {Name} name\n * @param {Code} code\n * @param {(input: Uint8Array) => Await} encode\n */\n constructor (name, code, encode) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n /**\n * @param {Uint8Array} input\n * @returns {Await>}\n */\n digest (input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * @template {number} Alg\n * @typedef {import('./interface.js').MultihashHasher} MultihashHasher\n */\n\n/**\n * @template T\n * @typedef {Promise|T} Await\n */\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\n/**\n * @param {AlgorithmIdentifier} name\n */\nconst sha = name =>\n /**\n * @param {Uint8Array} data\n */\n async data => new Uint8Array(await crypto.subtle.digest(name, data))\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","// @ts-check\n\nimport * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nconst bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nconst hashes = { ...sha2, ...identity }\nconst codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes, hashes, bases, codecs }\n","import { asUint8Array } from './util/as-uint8array.js'\nimport bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return asUint8Array(globalThis.Buffer.from(string, 'utf-8'))\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n",null,"import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16)\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n","import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [777, V, 'memory']\n]\n\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\n}\n\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol (proto: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n","/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport { IpNet } from '@chainsafe/netmask'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport varint from 'varint'\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf)\n case 42: // ipv6zone\n return bytes2str(buf)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf)\n\n case 421: // ipfs\n return bytes2mh(buf)\n case 444: // onion\n return bytes2onion(buf)\n case 445: // onion3\n return bytes2onion(buf)\n case 466: // certhash\n return bytes2mb(buf)\n default:\n return uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str)\n case 41: // ipv6\n return ip2bytes(str)\n case 42: // ipv6zone\n return str2bytes(str)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str)\n\n case 421: // ipfs\n return mh2bytes(str)\n case 444: // onion\n return onion2bytes(str)\n case 445: // onion3\n return onion32bytes(str)\n case 466: // certhash\n return mb2bytes(str)\n default:\n return uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value\n }\n if (code === ipcidrProtocol.code) {\n mask = value\n }\n })\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr')\n }\n return new IpNet(addr, mask)\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length)\n if (ipString == null) {\n throw new Error('ipBuff is required')\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ipString\n}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.decode.bytes)\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\n\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length))\n return uint8ArrayConcat([size, mh], size.length + mh.length)\n}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\n const mb = anybaseDecoder.decode(mbstr)\n const size = Uint8Array.from(varint.encode(mb.length))\n return uint8ArrayConcat([size, mb], size.length + mb.length)\n}\nfunction bytes2mb (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.decode.bytes)\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.decode.bytes)\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.slice(0, buf.length - 2)\n const portBytes = buf.slice(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n","import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport varint from 'varint'\nimport { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\nexport interface MultiaddrParts {\n bytes: Uint8Array\n string: string\n tuples: Tuple[]\n stringTuples: StringTuple[]\n path: string | null\n}\n\nexport function stringToMultiaddrParts (str: string): MultiaddrParts {\n str = cleanPath(str)\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n const parts = str.split('/').slice(1)\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n }\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([proto.code])\n stringTuples.push([proto.code])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'))\n tuples.push([proto.code, convertToBytes(proto.code, path)])\n stringTuples.push([proto.code, path])\n break\n }\n\n const bytes = convertToBytes(proto.code, parts[p])\n tuples.push([proto.code, bytes])\n stringTuples.push([proto.code, convertToString(proto.code, bytes)])\n }\n\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n }\n}\n\nexport function bytesToMultiaddrParts (bytes: Uint8Array): MultiaddrParts {\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, bytes.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n stringTuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = bytes.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n const stringAddr = convertToString(code, addr)\n stringTuples.push([code, stringAddr])\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr\n break\n }\n }\n\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n }\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n }))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr)\n return size + (varint.decode.bytes ?? 0)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a Multiaddr in JavaScript\n *\n * @example\n *\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')\n * ```\n */\n\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, type MultiaddrParts, tuplesToBytes } from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A Resolver is a function that takes a {@link Multiaddr} and resolves it into one\n * or more string representations of that {@link Multiaddr}.\n */\nexport interface Resolver { (addr: Multiaddr, options?: AbortOptions): Promise }\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\nconst symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js'\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString: () => string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON: () => string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions: () => MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos: () => Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes: () => number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames: () => string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples: () => Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples: () => StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate: (addr: MultiaddrInput) => Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate: (addr: Multiaddr | string) => Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode: (code: number) => Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId: () => string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath: () => string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals: (addr: { bytes: Uint8Array }) => boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve: (options?: AbortOptions) => Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress: () => NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress: (addr?: Multiaddr) => boolean\n}\n\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\n if (addr == null) {\n throw new Error('requires node address object')\n }\n if (transport == null) {\n throw new Error('requires transport protocol')\n }\n let ip: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\n\n host = parts[0]\n const zone = parts[1]\n ip = `/ip6zone/${zone}/ip6`\n }\n break\n default:\n throw Error('Invalid addr family, should be 4 or 6.')\n }\n return new DefaultMultiaddr('/' + [ip, host, transport, addr.port].join('/'))\n}\n\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName (addr: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nclass DefaultMultiaddr implements Multiaddr {\n public bytes: Uint8Array\n #string: string\n #tuples: Tuple[]\n #stringTuples: StringTuple[]\n #path: string | null\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n let parts: MultiaddrParts\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr)\n } else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`)\n }\n parts = stringToMultiaddrParts(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes)\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n\n this.bytes = parts.bytes\n this.#string = parts.string\n this.#tuples = parts.tuples\n this.#stringTuples = parts.stringTuples\n this.#path = parts.path\n }\n\n toString (): string {\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\n const tcp = getProtocol('tcp')\n const udp = getProtocol('udp')\n const ip4 = getProtocol('ip4')\n const ip6 = getProtocol('ip6')\n const dns6 = getProtocol('dns6')\n const ip6zone = getProtocol('ip6zone')\n\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\n\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name\n port = 443\n host = `${value ?? ''}${zone}`\n family = code === dns6.code ? 6 : 4\n }\n\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\n\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name\n host = `${value ?? ''}${zone}`\n family = code === ip6.code ? 6 : 4\n }\n }\n\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".')\n }\n\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n return this.#tuples.map(([code]) => code)\n }\n\n protoNames (): string[] {\n return this.#tuples.map(([code]) => getProtocol(code).name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new DefaultMultiaddr(addr)\n return new DefaultMultiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`)\n }\n return new DefaultMultiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new DefaultMultiaddr(tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n let tuples: Array<[number, string | undefined]> = []\n\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name])\n }\n\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = []\n }\n })\n\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc')\n }\n\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n return this.#path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: AbortOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const addresses = await resolver(this, options)\n return addresses.map((a) => new DefaultMultiaddr(a))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`)\n }\n\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\n\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false\n }\n return true\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.#string})`\n }\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new DefaultMultiaddr(addr)\n}\n\nexport { getProtocol as protocols }\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","import { multiaddr } from '@multiformats/multiaddr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\nexport const QUICV1 = and(UDP, base('quic-v1'))\n\nconst _WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSockets = or(\n and(_WebSockets, base('p2p')),\n _WebSockets\n)\n\nconst _WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss')),\n and(TCP, base('tls'), base('ws')),\n and(DNS, base('tls'), base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(_WebSocketsSecure, base('p2p')),\n _WebSocketsSecure\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nconst _WebRTCDirect = and(UDP, base('webrtc-direct'), base('certhash'))\nexport const WebRTCDirect = or(\n and(_WebRTCDirect, base('p2p')),\n _WebRTCDirect\n)\n\nconst _WebTransport = and(QUICV1, base('webtransport'), base('certhash'), base('certhash'))\nexport const WebTransport = or(\n and(_WebTransport, base('p2p')),\n _WebTransport\n)\n\n/**\n * @deprecated\n */\nexport const P2PWebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\n/**\n * @deprecated\n */\nexport const P2PWebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n _WebSockets,\n _WebSocketsSecure,\n HTTP,\n HTTPS,\n P2PWebRTCStar,\n P2PWebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS,\n WebRTCDirect,\n WebTransport\n)\n\n// Unlike ws-star, stardust can run over any transport thus removing the requirement for websockets (but don't even think about running a stardust server over webrtc-star ;) )\nexport const Stardust = or(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n P2PWebRTCStar,\n P2PWebRTCDirect,\n WebRTCDirect,\n WebTransport,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = (): Mafmt => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\nexport const WebRTC = or(\n and(Circuit, base('webrtc'), base('p2p')),\n and(Circuit, base('webrtc')),\n and(Reliable, base('webrtc'), base('p2p')),\n and(Reliable, base('webrtc')),\n base('webrtc')\n)\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction): (a: string | Uint8Array | Multiaddr) => boolean {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n let out = null\n args.some((arg) => {\n const res = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n if (res != null) {\n out = res\n return true\n }\n return false\n })\n\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma: Multiaddr\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches,\n partialMatch\n }\n}\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16)\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n","import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [777, V, 'memory']\n]\n\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\n}\n\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol (proto: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n","/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport { IpNet } from '@chainsafe/netmask'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf)\n case 42: // ipv6zone\n return bytes2str(buf)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf)\n\n case 421: // ipfs\n return bytes2mh(buf)\n case 444: // onion\n return bytes2onion(buf)\n case 445: // onion3\n return bytes2onion(buf)\n case 466: // certhash\n return bytes2mb(buf)\n default:\n return uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str)\n case 41: // ipv6\n return ip2bytes(str)\n case 42: // ipv6zone\n return str2bytes(str)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str)\n\n case 421: // ipfs\n return mh2bytes(str)\n case 444: // onion\n return onion2bytes(str)\n case 445: // onion3\n return onion32bytes(str)\n case 466: // certhash\n return mb2bytes(str)\n default:\n return uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value\n }\n if (code === ipcidrProtocol.code) {\n mask = value\n }\n })\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr')\n }\n return new IpNet(addr, mask)\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length)\n if (ipString == null) {\n throw new Error('ipBuff is required')\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ipString\n}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.encodingLength(size))\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\n\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length))\n return uint8ArrayConcat([size, mh], size.length + mh.length)\n}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\n const mb = anybaseDecoder.decode(mbstr)\n const size = Uint8Array.from(varint.encode(mb.length))\n return uint8ArrayConcat([size, mb], size.length + mb.length)\n}\nfunction bytes2mb (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.encodingLength(size))\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.encodingLength(size))\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.slice(0, buf.length - 2)\n const portBytes = buf.slice(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n","import * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\nexport interface MultiaddrParts {\n bytes: Uint8Array\n string: string\n tuples: Tuple[]\n stringTuples: StringTuple[]\n path: string | null\n}\n\nexport function stringToMultiaddrParts (str: string): MultiaddrParts {\n str = cleanPath(str)\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n const parts = str.split('/').slice(1)\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n }\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([proto.code])\n stringTuples.push([proto.code])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'))\n tuples.push([proto.code, convertToBytes(proto.code, path)])\n stringTuples.push([proto.code, path])\n break\n }\n\n const bytes = convertToBytes(proto.code, parts[p])\n tuples.push([proto.code, bytes])\n stringTuples.push([proto.code, convertToString(proto.code, bytes)])\n }\n\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n }\n}\n\nexport function bytesToMultiaddrParts (bytes: Uint8Array): MultiaddrParts {\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, bytes.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n stringTuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = bytes.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n const stringAddr = convertToString(code, addr)\n stringTuples.push([code, stringAddr])\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr\n break\n }\n }\n\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n }\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n }))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr))\n return size + varint.encodingLength(size)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a Multiaddr in JavaScript\n *\n * @example\n *\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, type MultiaddrParts, tuplesToBytes } from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport { isMultiaddr, multiaddr, resolvers } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, MultiaddrObject, Protocol, StringTuple, Tuple, NodeAddress, ResolveOptions } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n public bytes: Uint8Array\n #string: string\n #tuples: Tuple[]\n #stringTuples: StringTuple[]\n #path: string | null\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n let parts: MultiaddrParts\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr)\n } else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`)\n }\n parts = stringToMultiaddrParts(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes)\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n\n this.bytes = parts.bytes\n this.#string = parts.string\n this.#tuples = parts.tuples\n this.#stringTuples = parts.stringTuples\n this.#path = parts.path\n }\n\n toString (): string {\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\n const tcp = getProtocol('tcp')\n const udp = getProtocol('udp')\n const ip4 = getProtocol('ip4')\n const ip6 = getProtocol('ip6')\n const dns6 = getProtocol('dns6')\n const ip6zone = getProtocol('ip6zone')\n\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\n\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name\n port = 443\n host = `${value ?? ''}${zone}`\n family = code === dns6.code ? 6 : 4\n }\n\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\n\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name\n host = `${value ?? ''}${zone}`\n family = code === ip6.code ? 6 : 4\n }\n }\n\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".')\n }\n\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n return this.#tuples.map(([code]) => code)\n }\n\n protoNames (): string[] {\n return this.#tuples.map(([code]) => getProtocol(code).name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new Multiaddr(addr)\n return new Multiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`)\n }\n return new Multiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr(tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n let tuples: Array<[number, string | undefined]> = []\n\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name])\n }\n\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = []\n }\n })\n\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc')\n }\n\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n return this.#path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: ResolveOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const result = await resolver(this, options)\n\n return result.map(str => multiaddr(str))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`)\n }\n\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\n\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false\n }\n return true\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.#string})`\n }\n}\n","/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddr } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddr)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(await ma.resolve(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\n\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Resolver } from './resolvers/index.js'\nimport type { DNS } from '@multiformats/dns'\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\n\nexport type { Resolver }\n\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js'\n\nexport interface ResolveOptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions(): MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos(): Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes(): number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames(): string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples(): Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples(): StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId(): string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath(): string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve(options?: ResolveOptions): Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress(): NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress(addr?: Multiaddr): boolean\n}\n\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\n if (addr == null) {\n throw new Error('requires node address object')\n }\n if (transport == null) {\n throw new Error('requires transport protocol')\n }\n let ip: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\n\n host = parts[0]\n const zone = parts[1]\n ip = `/ip6zone/${zone}/ip6`\n }\n break\n default:\n throw Error('Invalid addr family, should be 4 or 6.')\n }\n return new MultiaddrClass('/' + [ip, host, transport, addr.port].join('/'))\n}\n\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName (addr: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\nexport { getProtocol as protocols }\n","/**\n * @packageDocumentation\n *\n * The configured bootstrap peers will be discovered after the configured timeout. This will ensure there are some peers in the peer store for the node to use to discover other peers.\n *\n * They will be tagged with a tag with the name `'bootstrap'` tag, the value `50` and it will expire after two minutes which means the nodes connections may be closed if the maximum number of connections is reached.\n *\n * Clients that need constant connections to bootstrap nodes (e.g. browsers) can set the TTL to `Infinity`.\n *\n * @example Configuring a list of bootstrap nodes\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { bootstrap } from '@libp2p/bootstrap'\n *\n * const libp2p = await createLibp2p({\n * peerDiscovery: [\n * bootstrap({\n * list: [\n * // a list of bootstrap peer multiaddrs to connect to on node startup\n * '/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa'\n * ]\n * })\n * ]\n * })\n *\n * libp2p.addEventListener('peer:discovery', (evt) => {\n * console.log('found peer: ', evt.detail.toString())\n * })\n * ```\n */\n\nimport { TypedEventEmitter, peerDiscoverySymbol } from '@libp2p/interface'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { P2P } from '@multiformats/mafmt'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport type { ComponentLogger, Logger, PeerDiscovery, PeerDiscoveryEvents, PeerInfo, PeerStore, Startable } from '@libp2p/interface'\n\nconst DEFAULT_BOOTSTRAP_TAG_NAME = 'bootstrap'\nconst DEFAULT_BOOTSTRAP_TAG_VALUE = 50\nconst DEFAULT_BOOTSTRAP_TAG_TTL = 120000\nconst DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT = 1000\n\nexport interface BootstrapInit {\n /**\n * The list of peer addresses in multi-address format\n */\n list: string[]\n\n /**\n * How long to wait before discovering bootstrap nodes\n */\n timeout?: number\n\n /**\n * Tag a bootstrap peer with this name before \"discovering\" it (default: 'bootstrap')\n */\n tagName?: string\n\n /**\n * The bootstrap peer tag will have this value (default: 50)\n */\n tagValue?: number\n\n /**\n * Cause the bootstrap peer tag to be removed after this number of ms (default: 2 minutes)\n */\n tagTTL?: number\n}\n\nexport interface BootstrapComponents {\n peerStore: PeerStore\n logger: ComponentLogger\n}\n\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends TypedEventEmitter implements PeerDiscovery, Startable {\n static tag = 'bootstrap'\n\n private readonly log: Logger\n private timer?: ReturnType\n private readonly list: PeerInfo[]\n private readonly timeout: number\n private readonly components: BootstrapComponents\n private readonly _init: BootstrapInit\n\n constructor (components: BootstrapComponents, options: BootstrapInit = { list: [] }) {\n if (options.list == null || options.list.length === 0) {\n throw new Error('Bootstrap requires a list of peer addresses')\n }\n super()\n\n this.components = components\n this.log = components.logger.forComponent('libp2p:bootstrap')\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT\n this.list = []\n\n for (const candidate of options.list) {\n if (!P2P.matches(candidate)) {\n this.log.error('Invalid multiaddr')\n continue\n }\n\n const ma = multiaddr(candidate)\n const peerIdStr = ma.getPeerId()\n\n if (peerIdStr == null) {\n this.log.error('Invalid bootstrap multiaddr without peer id')\n continue\n }\n\n const peerData: PeerInfo = {\n id: peerIdFromString(peerIdStr),\n multiaddrs: [ma]\n }\n\n this.list.push(peerData)\n }\n\n this._init = options\n }\n\n readonly [peerDiscoverySymbol] = this\n\n readonly [Symbol.toStringTag] = '@libp2p/bootstrap'\n\n isStarted (): boolean {\n return Boolean(this.timer)\n }\n\n /**\n * Start emitting events\n */\n start (): void {\n if (this.isStarted()) {\n return\n }\n\n this.log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout)\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n this.log.error(err)\n })\n }, this.timeout)\n }\n\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers (): Promise {\n if (this.timer == null) {\n return\n }\n\n for (const peerData of this.list) {\n await this.components.peerStore.merge(peerData.id, {\n tags: {\n [this._init.tagName ?? DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._init.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._init.tagTTL ?? DEFAULT_BOOTSTRAP_TAG_TTL\n }\n }\n })\n\n // check we are still running\n if (this.timer == null) {\n return\n }\n\n this.safeDispatchEvent('peer', { detail: peerData })\n }\n }\n\n /**\n * Stop emitting events\n */\n stop (): void {\n if (this.timer != null) {\n clearTimeout(this.timer)\n }\n\n this.timer = undefined\n }\n}\n\nexport function bootstrap (init: BootstrapInit): (components: BootstrapComponents) => PeerDiscovery {\n return (components: BootstrapComponents) => new Bootstrap(components, init)\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16)\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n","import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [777, V, 'memory']\n]\n\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\n}\n\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol (proto: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n","/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport { IpNet } from '@chainsafe/netmask'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf)\n case 42: // ipv6zone\n return bytes2str(buf)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf)\n\n case 421: // ipfs\n return bytes2mh(buf)\n case 444: // onion\n return bytes2onion(buf)\n case 445: // onion3\n return bytes2onion(buf)\n case 466: // certhash\n return bytes2mb(buf)\n default:\n return uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str)\n case 41: // ipv6\n return ip2bytes(str)\n case 42: // ipv6zone\n return str2bytes(str)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str)\n\n case 421: // ipfs\n return mh2bytes(str)\n case 444: // onion\n return onion2bytes(str)\n case 445: // onion3\n return onion32bytes(str)\n case 466: // certhash\n return mb2bytes(str)\n default:\n return uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value\n }\n if (code === ipcidrProtocol.code) {\n mask = value\n }\n })\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr')\n }\n return new IpNet(addr, mask)\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length)\n if (ipString == null) {\n throw new Error('ipBuff is required')\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ipString\n}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.encodingLength(size))\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\n\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length))\n return uint8ArrayConcat([size, mh], size.length + mh.length)\n}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\n const mb = anybaseDecoder.decode(mbstr)\n const size = Uint8Array.from(varint.encode(mb.length))\n return uint8ArrayConcat([size, mb], size.length + mb.length)\n}\nfunction bytes2mb (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.encodingLength(size))\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.encodingLength(size))\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.slice(0, buf.length - 2)\n const portBytes = buf.slice(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n","import * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\nexport interface MultiaddrParts {\n bytes: Uint8Array\n string: string\n tuples: Tuple[]\n stringTuples: StringTuple[]\n path: string | null\n}\n\nexport function stringToMultiaddrParts (str: string): MultiaddrParts {\n str = cleanPath(str)\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n const parts = str.split('/').slice(1)\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n }\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([proto.code])\n stringTuples.push([proto.code])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'))\n tuples.push([proto.code, convertToBytes(proto.code, path)])\n stringTuples.push([proto.code, path])\n break\n }\n\n const bytes = convertToBytes(proto.code, parts[p])\n tuples.push([proto.code, bytes])\n stringTuples.push([proto.code, convertToString(proto.code, bytes)])\n }\n\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n }\n}\n\nexport function bytesToMultiaddrParts (bytes: Uint8Array): MultiaddrParts {\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, bytes.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n stringTuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = bytes.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n const stringAddr = convertToString(code, addr)\n stringTuples.push([code, stringAddr])\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr\n break\n }\n }\n\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n }\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n }))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr))\n return size + varint.encodingLength(size)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a Multiaddr in JavaScript\n *\n * @example\n *\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, type MultiaddrParts, tuplesToBytes } from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport { isMultiaddr, multiaddr, resolvers } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, MultiaddrObject, Protocol, StringTuple, Tuple, NodeAddress, ResolveOptions } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n public bytes: Uint8Array\n #string: string\n #tuples: Tuple[]\n #stringTuples: StringTuple[]\n #path: string | null\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n let parts: MultiaddrParts\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr)\n } else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`)\n }\n parts = stringToMultiaddrParts(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes)\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n\n this.bytes = parts.bytes\n this.#string = parts.string\n this.#tuples = parts.tuples\n this.#stringTuples = parts.stringTuples\n this.#path = parts.path\n }\n\n toString (): string {\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\n const tcp = getProtocol('tcp')\n const udp = getProtocol('udp')\n const ip4 = getProtocol('ip4')\n const ip6 = getProtocol('ip6')\n const dns6 = getProtocol('dns6')\n const ip6zone = getProtocol('ip6zone')\n\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\n\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name\n port = 443\n host = `${value ?? ''}${zone}`\n family = code === dns6.code ? 6 : 4\n }\n\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\n\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name\n host = `${value ?? ''}${zone}`\n family = code === ip6.code ? 6 : 4\n }\n }\n\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".')\n }\n\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n return this.#tuples.map(([code]) => code)\n }\n\n protoNames (): string[] {\n return this.#tuples.map(([code]) => getProtocol(code).name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new Multiaddr(addr)\n return new Multiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`)\n }\n return new Multiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr(tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n let tuples: Array<[number, string | undefined]> = []\n\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name])\n }\n\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = []\n }\n })\n\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc')\n }\n\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n return this.#path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: ResolveOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const result = await resolver(this, options)\n\n return result.map(str => multiaddr(str))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`)\n }\n\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\n\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false\n }\n return true\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.#string})`\n }\n}\n","/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddr } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddr)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(await ma.resolve(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\n\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Resolver } from './resolvers/index.js'\nimport type { DNS } from '@multiformats/dns'\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\n\nexport type { Resolver }\n\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js'\n\nexport interface ResolveOptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions(): MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos(): Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes(): number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames(): string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples(): Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples(): StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId(): string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath(): string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve(options?: ResolveOptions): Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress(): NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress(addr?: Multiaddr): boolean\n}\n\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\n if (addr == null) {\n throw new Error('requires node address object')\n }\n if (transport == null) {\n throw new Error('requires transport protocol')\n }\n let ip: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\n\n host = parts[0]\n const zone = parts[1]\n ip = `/ip6zone/${zone}/ip6`\n }\n break\n default:\n throw Error('Invalid addr family, should be 4 or 6.')\n }\n return new MultiaddrClass('/' + [ip, host, transport, addr.port].join('/'))\n}\n\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName (addr: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\nexport { getProtocol as protocols }\n","// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1])\n","const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n","import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.peerId)\n }\n\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16)\n w.uint64(obj.seq)\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(26)\n PeerRecord.AddressInfo.codec().encode(value, w)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.peerId = reader.bytes()\n break\n case 2:\n obj.seq = reader.uint64()\n break\n case 3:\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n","import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n\n this.code = code\n }\n}\n","import { peerIdFromBytes } from '@libp2p/peer-id'\nimport { arrayEquals } from '@libp2p/utils/array-equals'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport {\n ENVELOPE_DOMAIN_PEER_RECORD,\n ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n} from './consts.js'\nimport { PeerRecord as Protobuf } from './peer-record.js'\nimport type { PeerId } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecordInit {\n peerId: PeerId\n\n /**\n * Addresses of the associated peer.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Monotonically-increasing sequence counter that's used to order PeerRecords in time.\n */\n seqNumber?: bigint\n}\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n const peerRecord = Protobuf.decode(buf)\n const peerId = peerIdFromBytes(peerRecord.peerId)\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => multiaddr(a.multiaddr))\n const seqNumber = peerRecord.seq\n\n return new PeerRecord({ peerId, multiaddrs, seqNumber })\n }\n\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n\n public peerId: PeerId\n public multiaddrs: Multiaddr[]\n public seqNumber: bigint\n public domain = PeerRecord.DOMAIN\n public codec = PeerRecord.CODEC\n private marshaled?: Uint8Array\n\n constructor (init: PeerRecordInit) {\n const { peerId, multiaddrs, seqNumber } = init\n\n this.peerId = peerId\n this.multiaddrs = multiaddrs ?? []\n this.seqNumber = seqNumber ?? BigInt(Date.now())\n }\n\n /**\n * Marshal a record to be used in an envelope\n */\n marshal (): Uint8Array {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Returns true if `this` record equals the `other`\n */\n equals (other: unknown): boolean {\n if (!(other instanceof PeerRecord)) {\n return false\n }\n\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false\n }\n\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false\n }\n\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false\n }\n\n return true\n }\n}\n","/**\n * @packageDocumentation\n *\n * Provides strategies ensure arrays are equivalent.\n *\n * @example\n *\n * ```typescript\n * import { arrayEquals } from '@libp2p/utils/array-equals'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n * const ma1 = multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * const ma2 = multiaddr('/ip4/82.41.53.1/tcp/9000')\n *\n * console.info(arrayEquals([ma1], [ma1])) // true\n * console.info(arrayEquals([ma1], [ma2])) // false\n * ```\n */\n\n/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals (a: any[], b: any[]): boolean {\n const sort = (a: any, b: any): number => a.toString().localeCompare(b.toString())\n\n if (a.length !== b.length) {\n return false\n }\n\n b.sort(sort)\n\n return a.sort(sort).every((item, index) => b[index].equals(item))\n}\n","import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n\nexport function isPromise (thing: any): thing is Promise {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n","import { ed25519 as ed } from '@noble/curves/ed25519'\nimport type { Uint8ArrayKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32\nconst PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed (seed: Uint8Array): Uint8ArrayKeyPair {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw)\n}\n\nexport function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH)\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i]\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i]\n }\n return privateKey\n}\n","/* eslint-env browser */\n\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get (win = globalThis) {\n const nativeCrypto = win.crypto\n\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n 'Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n","import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\n\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' }\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions): AESCipher {\n const algorithm = opts?.algorithm ?? 'AES-GCM'\n let keyLength = opts?.keyLength ?? 16\n const nonceLength = opts?.nonceLength ?? 12\n const digest = opts?.digest ?? 'SHA-256'\n const saltLength = opts?.saltLength ?? 16\n const iterations = opts?.iterations ?? 32767\n\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n }\n } else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt'])\n }\n\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data)\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)])\n }\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = data.subarray(0, saltLength)\n const nonce = data.subarray(saltLength, saltLength + nonceLength)\n const ciphertext = data.subarray(saltLength + nonceLength)\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt'])\n }\n } else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt'])\n }\n\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext)\n return new Uint8Array(plaintext)\n }\n\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n","import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\nimport type { Multibase } from 'multiformats'\n\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter (privateKey: Uint8Array, password: string): Promise> {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = (): Codec => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { isPromise } from '../util.js'\nimport * as crypto from './ed25519.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Ed25519PublicKey {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id (): Promise {\n const encoding = identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n }\n\n bytes = ensureKey(bytes, crypto.privateKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const { privateKey, publicKey } = crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array): Promise {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE')\n }\n return key\n}\n","import { CodeError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport * as utils from './rsa-utils.js'\nimport type { JWKKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport { utils }\n\nexport async function generateKey (bits: number): Promise {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey): Promise {\n return webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\nexport function keySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE')\n } else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n","import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { hmac } from './hmac.js';\nimport { Hash, CHash, Input, createView, toBytes, checkOpts, asyncLoop } from './utils.js';\n\n// PBKDF (RFC 2898)\nexport type Pbkdf2Opt = {\n c: number; // Iterations\n dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key\n asyncTick?: number; // Maximum time in ms for which async function can block execution\n};\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: Input, _salt: Input, _opts: Pbkdf2Opt) {\n assertHash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n assertNumber(c);\n assertNumber(dkLen);\n assertNumber(asyncTick);\n if (c < 1) throw new Error('PBKDF2: iterations (c) should be >= 1');\n const password = toBytes(_password);\n const salt = toBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output>(\n PRF: Hash,\n PRFSalt: Hash,\n DK: Uint8Array,\n prfW: Hash,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n u.fill(0);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n */\nexport function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\nexport async function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","/*!\n Copyright (c) Peculiar Ventures, LLC\n*/\n\nfunction getUTCDate(date) {\r\n return new Date(date.getTime() + (date.getTimezoneOffset() * 60000));\r\n}\r\nfunction getParametersValue(parameters, name, defaultValue) {\r\n var _a;\r\n if ((parameters instanceof Object) === false) {\r\n return defaultValue;\r\n }\r\n return (_a = parameters[name]) !== null && _a !== void 0 ? _a : defaultValue;\r\n}\r\nfunction bufferToHexCodes(inputBuffer, inputOffset = 0, inputLength = (inputBuffer.byteLength - inputOffset), insertSpace = false) {\r\n let result = \"\";\r\n for (const item of (new Uint8Array(inputBuffer, inputOffset, inputLength))) {\r\n const str = item.toString(16).toUpperCase();\r\n if (str.length === 1) {\r\n result += \"0\";\r\n }\r\n result += str;\r\n if (insertSpace) {\r\n result += \" \";\r\n }\r\n }\r\n return result.trim();\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof ArrayBuffer)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be \\\"ArrayBuffer\\\"\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\r\nfunction utilFromBase(inputBuffer, inputBase) {\r\n let result = 0;\r\n if (inputBuffer.length === 1) {\r\n return inputBuffer[0];\r\n }\r\n for (let i = (inputBuffer.length - 1); i >= 0; i--) {\r\n result += inputBuffer[(inputBuffer.length - 1) - i] * Math.pow(2, inputBase * i);\r\n }\r\n return result;\r\n}\r\nfunction utilToBase(value, base, reserved = (-1)) {\r\n const internalReserved = reserved;\r\n let internalValue = value;\r\n let result = 0;\r\n let biggest = Math.pow(2, base);\r\n for (let i = 1; i < 8; i++) {\r\n if (value < biggest) {\r\n let retBuf;\r\n if (internalReserved < 0) {\r\n retBuf = new ArrayBuffer(i);\r\n result = i;\r\n }\r\n else {\r\n if (internalReserved < i) {\r\n return (new ArrayBuffer(0));\r\n }\r\n retBuf = new ArrayBuffer(internalReserved);\r\n result = internalReserved;\r\n }\r\n const retView = new Uint8Array(retBuf);\r\n for (let j = (i - 1); j >= 0; j--) {\r\n const basis = Math.pow(2, j * base);\r\n retView[result - j - 1] = Math.floor(internalValue / basis);\r\n internalValue -= (retView[result - j - 1]) * basis;\r\n }\r\n return retBuf;\r\n }\r\n biggest *= Math.pow(2, base);\r\n }\r\n return new ArrayBuffer(0);\r\n}\r\nfunction utilConcatBuf(...buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const buffer of buffers) {\r\n outputLength += buffer.byteLength;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const buffer of buffers) {\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retBuf;\r\n}\r\nfunction utilConcatView(...views) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const view of views) {\r\n outputLength += view.length;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const view of views) {\r\n retView.set(view, prevLength);\r\n prevLength += view.length;\r\n }\r\n return retView;\r\n}\r\nfunction utilDecodeTC() {\r\n const buf = new Uint8Array(this.valueHex);\r\n if (this.valueHex.byteLength >= 2) {\r\n const condition1 = (buf[0] === 0xFF) && (buf[1] & 0x80);\r\n const condition2 = (buf[0] === 0x00) && ((buf[1] & 0x80) === 0x00);\r\n if (condition1 || condition2) {\r\n this.warnings.push(\"Needlessly long format\");\r\n }\r\n }\r\n const bigIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const bigIntView = new Uint8Array(bigIntBuffer);\r\n for (let i = 0; i < this.valueHex.byteLength; i++) {\r\n bigIntView[i] = 0;\r\n }\r\n bigIntView[0] = (buf[0] & 0x80);\r\n const bigInt = utilFromBase(bigIntView, 8);\r\n const smallIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const smallIntView = new Uint8Array(smallIntBuffer);\r\n for (let j = 0; j < this.valueHex.byteLength; j++) {\r\n smallIntView[j] = buf[j];\r\n }\r\n smallIntView[0] &= 0x7F;\r\n const smallInt = utilFromBase(smallIntView, 8);\r\n return (smallInt - bigInt);\r\n}\r\nfunction utilEncodeTC(value) {\r\n const modValue = (value < 0) ? (value * (-1)) : value;\r\n let bigInt = 128;\r\n for (let i = 1; i < 8; i++) {\r\n if (modValue <= bigInt) {\r\n if (value < 0) {\r\n const smallInt = bigInt - modValue;\r\n const retBuf = utilToBase(smallInt, 8, i);\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] |= 0x80;\r\n return retBuf;\r\n }\r\n let retBuf = utilToBase(modValue, 8, i);\r\n let retView = new Uint8Array(retBuf);\r\n if (retView[0] & 0x80) {\r\n const tempBuf = retBuf.slice(0);\r\n const tempView = new Uint8Array(tempBuf);\r\n retBuf = new ArrayBuffer(retBuf.byteLength + 1);\r\n retView = new Uint8Array(retBuf);\r\n for (let k = 0; k < tempBuf.byteLength; k++) {\r\n retView[k + 1] = tempView[k];\r\n }\r\n retView[0] = 0x00;\r\n }\r\n return retBuf;\r\n }\r\n bigInt *= Math.pow(2, 8);\r\n }\r\n return (new ArrayBuffer(0));\r\n}\r\nfunction isEqualBuffer(inputBuffer1, inputBuffer2) {\r\n if (inputBuffer1.byteLength !== inputBuffer2.byteLength) {\r\n return false;\r\n }\r\n const view1 = new Uint8Array(inputBuffer1);\r\n const view2 = new Uint8Array(inputBuffer2);\r\n for (let i = 0; i < view1.length; i++) {\r\n if (view1[i] !== view2[i]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction padNumber(inputNumber, fullLength) {\r\n const str = inputNumber.toString(10);\r\n if (fullLength < str.length) {\r\n return \"\";\r\n }\r\n const dif = fullLength - str.length;\r\n const padding = new Array(dif);\r\n for (let i = 0; i < dif; i++) {\r\n padding[i] = \"0\";\r\n }\r\n const paddingString = padding.join(\"\");\r\n return paddingString.concat(str);\r\n}\r\nconst base64Template = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\r\nconst base64UrlTemplate = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=\";\r\nfunction toBase64(input, useUrlTemplate = false, skipPadding = false, skipLeadingZeros = false) {\r\n let i = 0;\r\n let flag1 = 0;\r\n let flag2 = 0;\r\n let output = \"\";\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n if (skipLeadingZeros) {\r\n let nonZeroPosition = 0;\r\n for (let i = 0; i < input.length; i++) {\r\n if (input.charCodeAt(i) !== 0) {\r\n nonZeroPosition = i;\r\n break;\r\n }\r\n }\r\n input = input.slice(nonZeroPosition);\r\n }\r\n while (i < input.length) {\r\n const chr1 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag1 = 1;\r\n }\r\n const chr2 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag2 = 1;\r\n }\r\n const chr3 = input.charCodeAt(i++);\r\n const enc1 = chr1 >> 2;\r\n const enc2 = ((chr1 & 0x03) << 4) | (chr2 >> 4);\r\n let enc3 = ((chr2 & 0x0F) << 2) | (chr3 >> 6);\r\n let enc4 = chr3 & 0x3F;\r\n if (flag1 === 1) {\r\n enc3 = enc4 = 64;\r\n }\r\n else {\r\n if (flag2 === 1) {\r\n enc4 = 64;\r\n }\r\n }\r\n if (skipPadding) {\r\n if (enc3 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}`;\r\n }\r\n else {\r\n if (enc4 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}`;\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n return output;\r\n}\r\nfunction fromBase64(input, useUrlTemplate = false, cutTailZeros = false) {\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n function indexOf(toSearch) {\r\n for (let i = 0; i < 64; i++) {\r\n if (template.charAt(i) === toSearch)\r\n return i;\r\n }\r\n return 64;\r\n }\r\n function test(incoming) {\r\n return ((incoming === 64) ? 0x00 : incoming);\r\n }\r\n let i = 0;\r\n let output = \"\";\r\n while (i < input.length) {\r\n const enc1 = indexOf(input.charAt(i++));\r\n const enc2 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc3 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc4 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const chr1 = (test(enc1) << 2) | (test(enc2) >> 4);\r\n const chr2 = ((test(enc2) & 0x0F) << 4) | (test(enc3) >> 2);\r\n const chr3 = ((test(enc3) & 0x03) << 6) | test(enc4);\r\n output += String.fromCharCode(chr1);\r\n if (enc3 !== 64) {\r\n output += String.fromCharCode(chr2);\r\n }\r\n if (enc4 !== 64) {\r\n output += String.fromCharCode(chr3);\r\n }\r\n }\r\n if (cutTailZeros) {\r\n const outputLength = output.length;\r\n let nonZeroStart = (-1);\r\n for (let i = (outputLength - 1); i >= 0; i--) {\r\n if (output.charCodeAt(i) !== 0) {\r\n nonZeroStart = i;\r\n break;\r\n }\r\n }\r\n if (nonZeroStart !== (-1)) {\r\n output = output.slice(0, nonZeroStart + 1);\r\n }\r\n else {\r\n output = \"\";\r\n }\r\n }\r\n return output;\r\n}\r\nfunction arrayBufferToString(buffer) {\r\n let resultString = \"\";\r\n const view = new Uint8Array(buffer);\r\n for (const element of view) {\r\n resultString += String.fromCharCode(element);\r\n }\r\n return resultString;\r\n}\r\nfunction stringToArrayBuffer(str) {\r\n const stringLength = str.length;\r\n const resultBuffer = new ArrayBuffer(stringLength);\r\n const resultView = new Uint8Array(resultBuffer);\r\n for (let i = 0; i < stringLength; i++) {\r\n resultView[i] = str.charCodeAt(i);\r\n }\r\n return resultBuffer;\r\n}\r\nconst log2 = Math.log(2);\r\nfunction nearestPowerOf2(length) {\r\n const base = (Math.log(length) / log2);\r\n const floor = Math.floor(base);\r\n const round = Math.round(base);\r\n return ((floor === round) ? floor : round);\r\n}\r\nfunction clearProps(object, propsArray) {\r\n for (const prop of propsArray) {\r\n delete object[prop];\r\n }\r\n}\n\nexport { arrayBufferToString, bufferToHexCodes, checkBufferParams, clearProps, fromBase64, getParametersValue, getUTCDate, isEqualBuffer, nearestPowerOf2, padNumber, stringToArrayBuffer, toBase64, utilConcatBuf, utilConcatView, utilDecodeTC, utilEncodeTC, utilFromBase, utilToBase };\n","/*!\n * Copyright (c) 2014, GMO GlobalSign\n * Copyright (c) 2015-2022, Peculiar Ventures\n * All rights reserved.\n * \n * Author 2014-2019, Yury Strozhevsky\n * \n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * * Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * \n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\nimport * as pvtsutils from 'pvtsutils';\nimport * as pvutils from 'pvutils';\n\nfunction assertBigInt() {\r\n if (typeof BigInt === \"undefined\") {\r\n throw new Error(\"BigInt is not defined. Your environment doesn't implement BigInt.\");\r\n }\r\n}\r\nfunction concat(buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n outputLength += buffer.byteLength;\r\n }\r\n const retView = new Uint8Array(outputLength);\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retView.buffer;\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof Uint8Array)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be 'Uint8Array'\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\n\nclass ViewWriter {\r\n constructor() {\r\n this.items = [];\r\n }\r\n write(buf) {\r\n this.items.push(buf);\r\n }\r\n final() {\r\n return concat(this.items);\r\n }\r\n}\n\nconst powers2 = [new Uint8Array([1])];\r\nconst digitsString = \"0123456789\";\r\nconst NAME = \"name\";\r\nconst VALUE_HEX_VIEW = \"valueHexView\";\r\nconst IS_HEX_ONLY = \"isHexOnly\";\r\nconst ID_BLOCK = \"idBlock\";\r\nconst TAG_CLASS = \"tagClass\";\r\nconst TAG_NUMBER = \"tagNumber\";\r\nconst IS_CONSTRUCTED = \"isConstructed\";\r\nconst FROM_BER = \"fromBER\";\r\nconst TO_BER = \"toBER\";\r\nconst LOCAL = \"local\";\r\nconst EMPTY_STRING = \"\";\r\nconst EMPTY_BUFFER = new ArrayBuffer(0);\r\nconst EMPTY_VIEW = new Uint8Array(0);\r\nconst END_OF_CONTENT_NAME = \"EndOfContent\";\r\nconst OCTET_STRING_NAME = \"OCTET STRING\";\r\nconst BIT_STRING_NAME = \"BIT STRING\";\n\nfunction HexBlock(BaseClass) {\r\n var _a;\r\n return _a = class Some extends BaseClass {\r\n constructor(...args) {\r\n var _a;\r\n super(...args);\r\n const params = args[0] || {};\r\n this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = params.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;\r\n }\r\n get valueHex() {\r\n return this.valueHexView.slice().buffer;\r\n }\r\n set valueHex(value) {\r\n this.valueHexView = new Uint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const endLength = inputOffset + inputLength;\r\n this.valueHexView = view.subarray(inputOffset, endLength);\r\n if (!this.valueHexView.length) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n this.blockLength = inputLength;\r\n return endLength;\r\n }\r\n toBER(sizeOnly = false) {\r\n if (!this.isHexOnly) {\r\n this.error = \"Flag 'isHexOnly' is not set, abort\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength);\r\n }\r\n return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength)\r\n ? this.valueHexView.buffer\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isHexOnly: this.isHexOnly,\r\n valueHex: pvtsutils.Convert.ToHex(this.valueHexView),\r\n };\r\n }\r\n },\r\n _a.NAME = \"hexBlock\",\r\n _a;\r\n}\n\nclass LocalBaseBlock {\r\n constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) {\r\n this.blockLength = blockLength;\r\n this.error = error;\r\n this.warnings = warnings;\r\n this.valueBeforeDecodeView = pvtsutils.BufferSourceConverter.toUint8Array(valueBeforeDecode);\r\n }\r\n static blockName() {\r\n return this.NAME;\r\n }\r\n get valueBeforeDecode() {\r\n return this.valueBeforeDecodeView.slice().buffer;\r\n }\r\n set valueBeforeDecode(value) {\r\n this.valueBeforeDecodeView = new Uint8Array(value);\r\n }\r\n toJSON() {\r\n return {\r\n blockName: this.constructor.NAME,\r\n blockLength: this.blockLength,\r\n error: this.error,\r\n warnings: this.warnings,\r\n valueBeforeDecode: pvtsutils.Convert.ToHex(this.valueBeforeDecodeView),\r\n };\r\n }\r\n}\r\nLocalBaseBlock.NAME = \"baseBlock\";\n\nclass ValueBlock extends LocalBaseBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n toBER(sizeOnly, writer) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n}\r\nValueBlock.NAME = \"valueBlock\";\n\nclass LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ idBlock = {}, } = {}) {\r\n var _a, _b, _c, _d;\r\n super();\r\n if (idBlock) {\r\n this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = idBlock.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;\r\n this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;\r\n this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;\r\n this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;\r\n }\r\n else {\r\n this.tagClass = -1;\r\n this.tagNumber = -1;\r\n this.isConstructed = false;\r\n }\r\n }\r\n toBER(sizeOnly = false) {\r\n let firstOctet = 0;\r\n switch (this.tagClass) {\r\n case 1:\r\n firstOctet |= 0x00;\r\n break;\r\n case 2:\r\n firstOctet |= 0x40;\r\n break;\r\n case 3:\r\n firstOctet |= 0x80;\r\n break;\r\n case 4:\r\n firstOctet |= 0xC0;\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (this.isConstructed)\r\n firstOctet |= 0x20;\r\n if (this.tagNumber < 31 && !this.isHexOnly) {\r\n const retView = new Uint8Array(1);\r\n if (!sizeOnly) {\r\n let number = this.tagNumber;\r\n number &= 0x1F;\r\n firstOctet |= number;\r\n retView[0] = firstOctet;\r\n }\r\n return retView.buffer;\r\n }\r\n if (!this.isHexOnly) {\r\n const encodedBuf = pvutils.utilToBase(this.tagNumber, 7);\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const size = encodedBuf.byteLength;\r\n const retView = new Uint8Array(size + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n for (let i = 0; i < (size - 1); i++)\r\n retView[i + 1] = encodedView[i] | 0x80;\r\n retView[size] = encodedView[size - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.byteLength + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n const curView = this.valueHexView;\r\n for (let i = 0; i < (curView.length - 1); i++)\r\n retView[i + 1] = curView[i] | 0x80;\r\n retView[this.valueHexView.byteLength] = curView[curView.length - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n const tagClassMask = intBuffer[0] & 0xC0;\r\n switch (tagClassMask) {\r\n case 0x00:\r\n this.tagClass = (1);\r\n break;\r\n case 0x40:\r\n this.tagClass = (2);\r\n break;\r\n case 0x80:\r\n this.tagClass = (3);\r\n break;\r\n case 0xC0:\r\n this.tagClass = (4);\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return -1;\r\n }\r\n this.isConstructed = (intBuffer[0] & 0x20) === 0x20;\r\n this.isHexOnly = false;\r\n const tagNumberMask = intBuffer[0] & 0x1F;\r\n if (tagNumberMask !== 0x1F) {\r\n this.tagNumber = (tagNumberMask);\r\n this.blockLength = 1;\r\n }\r\n else {\r\n let count = 1;\r\n let intTagNumberBuffer = this.valueHexView = new Uint8Array(255);\r\n let tagNumberBufferMaxLength = 255;\r\n while (intBuffer[count] & 0x80) {\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n count++;\r\n if (count >= intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (count === tagNumberBufferMaxLength) {\r\n tagNumberBufferMaxLength += 255;\r\n const tempBufferView = new Uint8Array(tagNumberBufferMaxLength);\r\n for (let i = 0; i < intTagNumberBuffer.length; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength);\r\n }\r\n }\r\n this.blockLength = (count + 1);\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n const tempBufferView = new Uint8Array(count);\r\n for (let i = 0; i < count; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(count);\r\n intTagNumberBuffer.set(tempBufferView);\r\n if (this.blockLength <= 9)\r\n this.tagNumber = pvutils.utilFromBase(intTagNumberBuffer, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Tag too long, represented as hex-coded\");\r\n }\r\n }\r\n if (((this.tagClass === 1)) &&\r\n (this.isConstructed)) {\r\n switch (this.tagNumber) {\r\n case 1:\r\n case 2:\r\n case 5:\r\n case 6:\r\n case 9:\r\n case 13:\r\n case 14:\r\n case 23:\r\n case 24:\r\n case 31:\r\n case 32:\r\n case 33:\r\n case 34:\r\n this.error = \"Constructed encoding used for primitive type\";\r\n return -1;\r\n }\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n tagClass: this.tagClass,\r\n tagNumber: this.tagNumber,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalIdentificationBlock.NAME = \"identificationBlock\";\n\nclass LocalLengthBlock extends LocalBaseBlock {\r\n constructor({ lenBlock = {}, } = {}) {\r\n var _a, _b, _c;\r\n super();\r\n this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;\r\n this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;\r\n this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n if (intBuffer[0] === 0xFF) {\r\n this.error = \"Length block 0xFF is reserved by standard\";\r\n return -1;\r\n }\r\n this.isIndefiniteForm = intBuffer[0] === 0x80;\r\n if (this.isIndefiniteForm) {\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n this.longFormUsed = !!(intBuffer[0] & 0x80);\r\n if (this.longFormUsed === false) {\r\n this.length = (intBuffer[0]);\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n const count = intBuffer[0] & 0x7F;\r\n if (count > 8) {\r\n this.error = \"Too big integer\";\r\n return -1;\r\n }\r\n if ((count + 1) > intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n const lenOffset = inputOffset + 1;\r\n const lengthBufferView = view.subarray(lenOffset, lenOffset + count);\r\n if (lengthBufferView[count - 1] === 0x00)\r\n this.warnings.push(\"Needlessly long encoded length\");\r\n this.length = pvutils.utilFromBase(lengthBufferView, 8);\r\n if (this.longFormUsed && (this.length <= 127))\r\n this.warnings.push(\"Unnecessary usage of long length form\");\r\n this.blockLength = count + 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly = false) {\r\n let retBuf;\r\n let retView;\r\n if (this.length > 127)\r\n this.longFormUsed = true;\r\n if (this.isIndefiniteForm) {\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = 0x80;\r\n }\r\n return retBuf;\r\n }\r\n if (this.longFormUsed) {\r\n const encodedBuf = pvutils.utilToBase(this.length, 8);\r\n if (encodedBuf.byteLength > 127) {\r\n this.error = \"Too big length\";\r\n return (EMPTY_BUFFER);\r\n }\r\n retBuf = new ArrayBuffer(encodedBuf.byteLength + 1);\r\n if (sizeOnly)\r\n return retBuf;\r\n const encodedView = new Uint8Array(encodedBuf);\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = encodedBuf.byteLength | 0x80;\r\n for (let i = 0; i < encodedBuf.byteLength; i++)\r\n retView[i + 1] = encodedView[i];\r\n return retBuf;\r\n }\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = this.length;\r\n }\r\n return retBuf;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n longFormUsed: this.longFormUsed,\r\n length: this.length,\r\n };\r\n }\r\n}\r\nLocalLengthBlock.NAME = \"lengthBlock\";\n\nconst typeStore = {};\n\nclass BaseBlock extends LocalBaseBlock {\r\n constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) {\r\n super(parameters);\r\n this.name = name;\r\n this.optional = optional;\r\n if (primitiveSchema) {\r\n this.primitiveSchema = primitiveSchema;\r\n }\r\n this.idBlock = new LocalIdentificationBlock(parameters);\r\n this.lenBlock = new LocalLengthBlock(parameters);\r\n this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n if (!writer) {\r\n prepareIndefiniteForm(this);\r\n }\r\n const idBlockBuf = this.idBlock.toBER(sizeOnly);\r\n _writer.write(idBlockBuf);\r\n if (this.lenBlock.isIndefiniteForm) {\r\n _writer.write(new Uint8Array([0x80]).buffer);\r\n this.valueBlock.toBER(sizeOnly, _writer);\r\n _writer.write(new ArrayBuffer(2));\r\n }\r\n else {\r\n const valueBlockBuf = this.valueBlock.toBER(sizeOnly);\r\n this.lenBlock.length = valueBlockBuf.byteLength;\r\n const lenBlockBuf = this.lenBlock.toBER(sizeOnly);\r\n _writer.write(lenBlockBuf);\r\n _writer.write(valueBlockBuf);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n idBlock: this.idBlock.toJSON(),\r\n lenBlock: this.lenBlock.toJSON(),\r\n valueBlock: this.valueBlock.toJSON(),\r\n name: this.name,\r\n optional: this.optional,\r\n };\r\n if (this.primitiveSchema)\r\n object.primitiveSchema = this.primitiveSchema.toJSON();\r\n return object;\r\n }\r\n toString(encoding = \"ascii\") {\r\n if (encoding === \"ascii\") {\r\n return this.onAsciiEncoding();\r\n }\r\n return pvtsutils.Convert.ToHex(this.toBER());\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`;\r\n }\r\n isEqual(other) {\r\n if (this === other) {\r\n return true;\r\n }\r\n if (!(other instanceof this.constructor)) {\r\n return false;\r\n }\r\n const thisRaw = this.toBER();\r\n const otherRaw = other.toBER();\r\n return pvutils.isEqualBuffer(thisRaw, otherRaw);\r\n }\r\n}\r\nBaseBlock.NAME = \"BaseBlock\";\r\nfunction prepareIndefiniteForm(baseBlock) {\r\n if (baseBlock instanceof typeStore.Constructed) {\r\n for (const value of baseBlock.valueBlock.value) {\r\n if (prepareIndefiniteForm(value)) {\r\n baseBlock.lenBlock.isIndefiniteForm = true;\r\n }\r\n }\r\n }\r\n return !!baseBlock.lenBlock.isIndefiniteForm;\r\n}\n\nclass BaseStringBlock extends BaseBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {\r\n super(parameters, stringValueBlockType);\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n this.fromBuffer(this.valueBlock.valueHexView);\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : '${this.valueBlock.value}'`;\r\n }\r\n}\r\nBaseStringBlock.NAME = \"BaseStringBlock\";\n\nclass LocalPrimitiveValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ isHexOnly = true, ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = isHexOnly;\r\n }\r\n}\r\nLocalPrimitiveValueBlock.NAME = \"PrimitiveValueBlock\";\n\nvar _a$w;\r\nclass Primitive extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalPrimitiveValueBlock);\r\n this.idBlock.isConstructed = false;\r\n }\r\n}\r\n_a$w = Primitive;\r\n(() => {\r\n typeStore.Primitive = _a$w;\r\n})();\r\nPrimitive.NAME = \"PRIMITIVE\";\n\nfunction localChangeType(inputObject, newType) {\r\n if (inputObject instanceof newType) {\r\n return inputObject;\r\n }\r\n const newObject = new newType();\r\n newObject.idBlock = inputObject.idBlock;\r\n newObject.lenBlock = inputObject.lenBlock;\r\n newObject.warnings = inputObject.warnings;\r\n newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView;\r\n return newObject;\r\n}\r\nfunction localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) {\r\n const incomingOffset = inputOffset;\r\n let returnObject = new BaseBlock({}, ValueBlock);\r\n const baseBlock = new LocalBaseBlock();\r\n if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) {\r\n returnObject.error = baseBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength);\r\n if (!intBuffer.length) {\r\n returnObject.error = \"Zero buffer length\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.idBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.idBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.idBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.idBlock.blockLength;\r\n resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.lenBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.lenBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.lenBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.lenBlock.blockLength;\r\n if (!returnObject.idBlock.isConstructed &&\r\n returnObject.lenBlock.isIndefiniteForm) {\r\n returnObject.error = \"Indefinite length form used for primitive encoding form\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let newASN1Type = BaseBlock;\r\n switch (returnObject.idBlock.tagClass) {\r\n case 1:\r\n if ((returnObject.idBlock.tagNumber >= 37) &&\r\n (returnObject.idBlock.isHexOnly === false)) {\r\n returnObject.error = \"UNIVERSAL 37 and upper tags are reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n switch (returnObject.idBlock.tagNumber) {\r\n case 0:\r\n if ((returnObject.idBlock.isConstructed) &&\r\n (returnObject.lenBlock.length > 0)) {\r\n returnObject.error = \"Type [UNIVERSAL 0] is reserved\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n newASN1Type = typeStore.EndOfContent;\r\n break;\r\n case 1:\r\n newASN1Type = typeStore.Boolean;\r\n break;\r\n case 2:\r\n newASN1Type = typeStore.Integer;\r\n break;\r\n case 3:\r\n newASN1Type = typeStore.BitString;\r\n break;\r\n case 4:\r\n newASN1Type = typeStore.OctetString;\r\n break;\r\n case 5:\r\n newASN1Type = typeStore.Null;\r\n break;\r\n case 6:\r\n newASN1Type = typeStore.ObjectIdentifier;\r\n break;\r\n case 10:\r\n newASN1Type = typeStore.Enumerated;\r\n break;\r\n case 12:\r\n newASN1Type = typeStore.Utf8String;\r\n break;\r\n case 13:\r\n newASN1Type = typeStore.RelativeObjectIdentifier;\r\n break;\r\n case 14:\r\n newASN1Type = typeStore.TIME;\r\n break;\r\n case 15:\r\n returnObject.error = \"[UNIVERSAL 15] is reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n case 16:\r\n newASN1Type = typeStore.Sequence;\r\n break;\r\n case 17:\r\n newASN1Type = typeStore.Set;\r\n break;\r\n case 18:\r\n newASN1Type = typeStore.NumericString;\r\n break;\r\n case 19:\r\n newASN1Type = typeStore.PrintableString;\r\n break;\r\n case 20:\r\n newASN1Type = typeStore.TeletexString;\r\n break;\r\n case 21:\r\n newASN1Type = typeStore.VideotexString;\r\n break;\r\n case 22:\r\n newASN1Type = typeStore.IA5String;\r\n break;\r\n case 23:\r\n newASN1Type = typeStore.UTCTime;\r\n break;\r\n case 24:\r\n newASN1Type = typeStore.GeneralizedTime;\r\n break;\r\n case 25:\r\n newASN1Type = typeStore.GraphicString;\r\n break;\r\n case 26:\r\n newASN1Type = typeStore.VisibleString;\r\n break;\r\n case 27:\r\n newASN1Type = typeStore.GeneralString;\r\n break;\r\n case 28:\r\n newASN1Type = typeStore.UniversalString;\r\n break;\r\n case 29:\r\n newASN1Type = typeStore.CharacterString;\r\n break;\r\n case 30:\r\n newASN1Type = typeStore.BmpString;\r\n break;\r\n case 31:\r\n newASN1Type = typeStore.DATE;\r\n break;\r\n case 32:\r\n newASN1Type = typeStore.TimeOfDay;\r\n break;\r\n case 33:\r\n newASN1Type = typeStore.DateTime;\r\n break;\r\n case 34:\r\n newASN1Type = typeStore.Duration;\r\n break;\r\n default: {\r\n const newObject = returnObject.idBlock.isConstructed\r\n ? new typeStore.Constructed()\r\n : new typeStore.Primitive();\r\n newObject.idBlock = returnObject.idBlock;\r\n newObject.lenBlock = returnObject.lenBlock;\r\n newObject.warnings = returnObject.warnings;\r\n returnObject = newObject;\r\n }\r\n }\r\n break;\r\n case 2:\r\n case 3:\r\n case 4:\r\n default: {\r\n newASN1Type = returnObject.idBlock.isConstructed\r\n ? typeStore.Constructed\r\n : typeStore.Primitive;\r\n }\r\n }\r\n returnObject = localChangeType(returnObject, newASN1Type);\r\n resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length);\r\n returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength);\r\n return {\r\n offset: resultOffset,\r\n result: returnObject\r\n };\r\n}\r\nfunction fromBER(inputBuffer) {\r\n if (!inputBuffer.byteLength) {\r\n const result = new BaseBlock({}, ValueBlock);\r\n result.error = \"Input buffer has zero length\";\r\n return {\r\n offset: -1,\r\n result\r\n };\r\n }\r\n return localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength);\r\n}\n\nfunction checkLen(indefiniteLength, length) {\r\n if (indefiniteLength) {\r\n return 1;\r\n }\r\n return length;\r\n}\r\nclass LocalConstructedValueBlock extends ValueBlock {\r\n constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.isIndefiniteForm = isIndefiniteForm;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (this.valueBeforeDecodeView.length === 0) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n let currentOffset = inputOffset;\r\n while (checkLen(this.isIndefiniteForm, inputLength) > 0) {\r\n const returnObject = localFromBER(view, currentOffset, inputLength);\r\n if (returnObject.offset === -1) {\r\n this.error = returnObject.result.error;\r\n this.warnings.concat(returnObject.result.warnings);\r\n return -1;\r\n }\r\n currentOffset = returnObject.offset;\r\n this.blockLength += returnObject.result.blockLength;\r\n inputLength -= returnObject.result.blockLength;\r\n this.value.push(returnObject.result);\r\n if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) {\r\n break;\r\n }\r\n }\r\n if (this.isIndefiniteForm) {\r\n if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) {\r\n this.value.pop();\r\n }\r\n else {\r\n this.warnings.push(\"No EndOfContent block encoded\");\r\n }\r\n }\r\n return currentOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n for (let i = 0; i < this.value.length; i++) {\r\n this.value[i].toBER(sizeOnly, _writer);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n value: [],\r\n };\r\n for (const value of this.value) {\r\n object.value.push(value.toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalConstructedValueBlock.NAME = \"ConstructedValueBlock\";\n\nvar _a$v;\r\nclass Constructed extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalConstructedValueBlock);\r\n this.idBlock.isConstructed = true;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n const values = [];\r\n for (const value of this.valueBlock.value) {\r\n values.push(value.toString(\"ascii\").split(\"\\n\").map(o => ` ${o}`).join(\"\\n\"));\r\n }\r\n const blockName = this.idBlock.tagClass === 3\r\n ? `[${this.idBlock.tagNumber}]`\r\n : this.constructor.NAME;\r\n return values.length\r\n ? `${blockName} :\\n${values.join(\"\\n\")}`\r\n : `${blockName} :`;\r\n }\r\n}\r\n_a$v = Constructed;\r\n(() => {\r\n typeStore.Constructed = _a$v;\r\n})();\r\nConstructed.NAME = \"CONSTRUCTED\";\n\nclass LocalEndOfContentValueBlock extends ValueBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n return inputOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return EMPTY_BUFFER;\r\n }\r\n}\r\nLocalEndOfContentValueBlock.override = \"EndOfContentValueBlock\";\n\nvar _a$u;\r\nclass EndOfContent extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalEndOfContentValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 0;\r\n }\r\n}\r\n_a$u = EndOfContent;\r\n(() => {\r\n typeStore.EndOfContent = _a$u;\r\n})();\r\nEndOfContent.NAME = END_OF_CONTENT_NAME;\n\nvar _a$t;\r\nclass Null extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, ValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 5;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (this.lenBlock.length > 0)\r\n this.warnings.push(\"Non-zero length of value block for Null type\");\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n this.blockLength += inputLength;\r\n if ((inputOffset + inputLength) > inputBuffer.byteLength) {\r\n this.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return -1;\r\n }\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuf = new ArrayBuffer(2);\r\n if (!sizeOnly) {\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] = 0x05;\r\n retView[1] = 0x00;\r\n }\r\n if (writer) {\r\n writer.write(retBuf);\r\n }\r\n return retBuf;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME}`;\r\n }\r\n}\r\n_a$t = Null;\r\n(() => {\r\n typeStore.Null = _a$t;\r\n})();\r\nNull.NAME = \"NULL\";\n\nclass LocalBooleanValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n if (parameters.valueHex) {\r\n this.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(parameters.valueHex);\r\n }\r\n else {\r\n this.valueHexView = new Uint8Array(1);\r\n }\r\n if (value) {\r\n this.value = value;\r\n }\r\n }\r\n get value() {\r\n for (const octet of this.valueHexView) {\r\n if (octet > 0) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n set value(value) {\r\n this.valueHexView[0] = value ? 0xFF : 0x00;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (inputLength > 1)\r\n this.warnings.push(\"Boolean value encoded in more then 1 octet\");\r\n this.isHexOnly = true;\r\n pvutils.utilDecodeTC.call(this);\r\n this.blockLength = inputLength;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER() {\r\n return this.valueHexView.slice();\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalBooleanValueBlock.NAME = \"BooleanValueBlock\";\n\nvar _a$s;\r\nclass Boolean extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalBooleanValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 1;\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.getValue}`;\r\n }\r\n}\r\n_a$s = Boolean;\r\n(() => {\r\n typeStore.Boolean = _a$s;\r\n})();\r\nBoolean.NAME = \"BOOLEAN\";\n\nclass LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.isConstructed = isConstructed;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = 0;\r\n if (this.isConstructed) {\r\n this.isHexOnly = false;\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (let i = 0; i < this.value.length; i++) {\r\n const currentBlockName = this.value[i].constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== OCTET_STRING_NAME) {\r\n this.error = \"OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n }\r\n else {\r\n this.isHexOnly = true;\r\n resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n this.blockLength = inputLength;\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed)\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.byteLength)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalOctetStringValueBlock.NAME = \"OctetStringValueBlock\";\n\nvar _a$r;\r\nclass OctetString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalOctetStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 4;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n if (inputLength === 0) {\r\n if (this.idBlock.error.length === 0)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (this.lenBlock.error.length === 0)\r\n this.blockLength += this.lenBlock.blockLength;\r\n return inputOffset;\r\n }\r\n if (!this.valueBlock.isConstructed) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n const buf = view.subarray(inputOffset, inputOffset + inputLength);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === inputLength) {\r\n this.valueBlock.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueHexView)}`;\r\n }\r\n getValue() {\r\n if (!this.idBlock.isConstructed) {\r\n return this.valueBlock.valueHexView.slice().buffer;\r\n }\r\n const array = [];\r\n for (const content of this.valueBlock.value) {\r\n if (content instanceof OctetString) {\r\n array.push(content.valueBlock.valueHexView);\r\n }\r\n }\r\n return pvtsutils.BufferSourceConverter.concat(array);\r\n }\r\n}\r\n_a$r = OctetString;\r\n(() => {\r\n typeStore.OctetString = _a$r;\r\n})();\r\nOctetString.NAME = OCTET_STRING_NAME;\n\nclass LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.unusedBits = unusedBits;\r\n this.isConstructed = isConstructed;\r\n this.blockLength = this.valueHexView.byteLength;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n let resultOffset = -1;\r\n if (this.isConstructed) {\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (const value of this.value) {\r\n const currentBlockName = value.constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== BIT_STRING_NAME) {\r\n this.error = \"BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n const valueBlock = value.valueBlock;\r\n if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) {\r\n this.error = \"Using of \\\"unused bits\\\" inside constructive BIT STRING allowed for least one only\";\r\n return -1;\r\n }\r\n this.unusedBits = valueBlock.unusedBits;\r\n }\r\n return resultOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.unusedBits = intBuffer[0];\r\n if (this.unusedBits > 7) {\r\n this.error = \"Unused bits for BitString must be in range 0-7\";\r\n return -1;\r\n }\r\n if (!this.unusedBits) {\r\n const buf = intBuffer.subarray(1);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === (inputLength - 1)) {\r\n this.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n this.valueHexView = intBuffer.subarray(1);\r\n this.blockLength = intBuffer.length;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed) {\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength + 1);\r\n }\r\n if (!this.valueHexView.byteLength) {\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.length + 1);\r\n retView[0] = this.unusedBits;\r\n retView.set(this.valueHexView, 1);\r\n return retView.buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n unusedBits: this.unusedBits,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalBitStringValueBlock.NAME = \"BitStringValueBlock\";\n\nvar _a$q;\r\nclass BitString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalBitStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 3;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n else {\r\n const bits = [];\r\n const valueHex = this.valueBlock.valueHexView;\r\n for (const byte of valueHex) {\r\n bits.push(byte.toString(2).padStart(8, \"0\"));\r\n }\r\n const bitsStr = bits.join(\"\");\r\n return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;\r\n }\r\n }\r\n}\r\n_a$q = BitString;\r\n(() => {\r\n typeStore.BitString = _a$q;\r\n})();\r\nBitString.NAME = BIT_STRING_NAME;\n\nvar _a$p;\r\nfunction viewAdd(first, second) {\r\n const c = new Uint8Array([0]);\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n let firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value = 0;\r\n const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength;\r\n let counter = 0;\r\n for (let i = max; i >= 0; i--, counter++) {\r\n switch (true) {\r\n case (counter < secondViewCopy.length):\r\n value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0];\r\n break;\r\n default:\r\n value = firstViewCopy[firstViewCopyLength - counter] + c[0];\r\n }\r\n c[0] = value / 10;\r\n switch (true) {\r\n case (counter >= firstViewCopy.length):\r\n firstViewCopy = pvutils.utilConcatView(new Uint8Array([value % 10]), firstViewCopy);\r\n break;\r\n default:\r\n firstViewCopy[firstViewCopyLength - counter] = value % 10;\r\n }\r\n }\r\n if (c[0] > 0)\r\n firstViewCopy = pvutils.utilConcatView(c, firstViewCopy);\r\n return firstViewCopy;\r\n}\r\nfunction power2(n) {\r\n if (n >= powers2.length) {\r\n for (let p = powers2.length; p <= n; p++) {\r\n const c = new Uint8Array([0]);\r\n let digits = (powers2[p - 1]).slice(0);\r\n for (let i = (digits.length - 1); i >= 0; i--) {\r\n const newValue = new Uint8Array([(digits[i] << 1) + c[0]]);\r\n c[0] = newValue[0] / 10;\r\n digits[i] = newValue[0] % 10;\r\n }\r\n if (c[0] > 0)\r\n digits = pvutils.utilConcatView(c, digits);\r\n powers2.push(digits);\r\n }\r\n }\r\n return powers2[n];\r\n}\r\nfunction viewSub(first, second) {\r\n let b = 0;\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n const firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value;\r\n let counter = 0;\r\n for (let i = secondViewCopyLength; i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b;\r\n switch (true) {\r\n case (value < 0):\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n break;\r\n default:\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n }\r\n }\r\n if (b > 0) {\r\n for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - b;\r\n if (value < 0) {\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n }\r\n else {\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n break;\r\n }\r\n }\r\n }\r\n return firstViewCopy.slice();\r\n}\r\nclass LocalIntegerValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n this._valueDec = 0;\r\n if (parameters.valueHex) {\r\n this.setValueHex();\r\n }\r\n if (value !== undefined) {\r\n this.valueDec = value;\r\n }\r\n }\r\n setValueHex() {\r\n if (this.valueHexView.length >= 4) {\r\n this.warnings.push(\"Too big Integer for decoding, hex only\");\r\n this.isHexOnly = true;\r\n this._valueDec = 0;\r\n }\r\n else {\r\n this.isHexOnly = false;\r\n if (this.valueHexView.length > 0) {\r\n this._valueDec = pvutils.utilDecodeTC.call(this);\r\n }\r\n }\r\n }\r\n set valueDec(v) {\r\n this._valueDec = v;\r\n this.isHexOnly = false;\r\n this.valueHexView = new Uint8Array(pvutils.utilEncodeTC(v));\r\n }\r\n get valueDec() {\r\n return this._valueDec;\r\n }\r\n fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) {\r\n const offset = this.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (offset === -1)\r\n return offset;\r\n const view = this.valueHexView;\r\n if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) {\r\n this.valueHexView = view.subarray(1);\r\n }\r\n else {\r\n if (expectedLength !== 0) {\r\n if (view.length < expectedLength) {\r\n if ((expectedLength - view.length) > 1)\r\n expectedLength = view.length + 1;\r\n this.valueHexView = view.subarray(expectedLength - view.length);\r\n }\r\n }\r\n }\r\n return offset;\r\n }\r\n toDER(sizeOnly = false) {\r\n const view = this.valueHexView;\r\n switch (true) {\r\n case ((view[0] & 0x80) !== 0):\r\n {\r\n const updatedView = new Uint8Array(this.valueHexView.length + 1);\r\n updatedView[0] = 0x00;\r\n updatedView.set(view, 1);\r\n this.valueHexView = updatedView;\r\n }\r\n break;\r\n case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)):\r\n {\r\n this.valueHexView = this.valueHexView.subarray(1);\r\n }\r\n break;\r\n }\r\n return this.toBER(sizeOnly);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1) {\r\n return resultOffset;\r\n }\r\n this.setValueHex();\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.length)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n toString() {\r\n const firstBit = (this.valueHexView.length * 8) - 1;\r\n let digits = new Uint8Array((this.valueHexView.length * 8) / 3);\r\n let bitNumber = 0;\r\n let currentByte;\r\n const asn1View = this.valueHexView;\r\n let result = \"\";\r\n let flag = false;\r\n for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) {\r\n currentByte = asn1View[byteNumber];\r\n for (let i = 0; i < 8; i++) {\r\n if ((currentByte & 1) === 1) {\r\n switch (bitNumber) {\r\n case firstBit:\r\n digits = viewSub(power2(bitNumber), digits);\r\n result = \"-\";\r\n break;\r\n default:\r\n digits = viewAdd(digits, power2(bitNumber));\r\n }\r\n }\r\n bitNumber++;\r\n currentByte >>= 1;\r\n }\r\n }\r\n for (let i = 0; i < digits.length; i++) {\r\n if (digits[i])\r\n flag = true;\r\n if (flag)\r\n result += digitsString.charAt(digits[i]);\r\n }\r\n if (flag === false)\r\n result += digitsString.charAt(0);\r\n return result;\r\n }\r\n}\r\n_a$p = LocalIntegerValueBlock;\r\nLocalIntegerValueBlock.NAME = \"IntegerValueBlock\";\r\n(() => {\r\n Object.defineProperty(_a$p.prototype, \"valueHex\", {\r\n set: function (v) {\r\n this.valueHexView = new Uint8Array(v);\r\n this.setValueHex();\r\n },\r\n get: function () {\r\n return this.valueHexView.slice().buffer;\r\n },\r\n });\r\n})();\n\nvar _a$o;\r\nclass Integer extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalIntegerValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 2;\r\n }\r\n toBigInt() {\r\n assertBigInt();\r\n return BigInt(this.valueBlock.toString());\r\n }\r\n static fromBigInt(value) {\r\n assertBigInt();\r\n const bigIntValue = BigInt(value);\r\n const writer = new ViewWriter();\r\n const hex = bigIntValue.toString(16).replace(/^-/, \"\");\r\n const view = new Uint8Array(pvtsutils.Convert.FromHex(hex));\r\n if (bigIntValue < 0) {\r\n const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0));\r\n first[0] |= 0x80;\r\n const firstInt = BigInt(`0x${pvtsutils.Convert.ToHex(first)}`);\r\n const secondInt = firstInt + bigIntValue;\r\n const second = pvtsutils.BufferSourceConverter.toUint8Array(pvtsutils.Convert.FromHex(secondInt.toString(16)));\r\n second[0] |= 0x80;\r\n writer.write(second);\r\n }\r\n else {\r\n if (view[0] & 0x80) {\r\n writer.write(new Uint8Array([0]));\r\n }\r\n writer.write(view);\r\n }\r\n const res = new Integer({\r\n valueHex: writer.final(),\r\n });\r\n return res;\r\n }\r\n convertToDER() {\r\n const integer = new Integer({ valueHex: this.valueBlock.valueHexView });\r\n integer.valueBlock.toDER();\r\n return integer;\r\n }\r\n convertFromDER() {\r\n return new Integer({\r\n valueHex: this.valueBlock.valueHexView[0] === 0\r\n ? this.valueBlock.valueHexView.subarray(1)\r\n : this.valueBlock.valueHexView,\r\n });\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString()}`;\r\n }\r\n}\r\n_a$o = Integer;\r\n(() => {\r\n typeStore.Integer = _a$o;\r\n})();\r\nInteger.NAME = \"INTEGER\";\n\nvar _a$n;\r\nclass Enumerated extends Integer {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 10;\r\n }\r\n}\r\n_a$n = Enumerated;\r\n(() => {\r\n typeStore.Enumerated = _a$n;\r\n})();\r\nEnumerated.NAME = \"ENUMERATED\";\n\nclass LocalSidValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n this.isFirstSid = isFirstSid;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++) {\r\n tempView[i] = this.valueHexView[i];\r\n }\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n set valueBigInt(value) {\r\n assertBigInt();\r\n let bits = BigInt(value).toString(2);\r\n while (bits.length % 7) {\r\n bits = \"0\" + bits;\r\n }\r\n const bytes = new Uint8Array(bits.length / 7);\r\n for (let i = 0; i < bytes.length; i++) {\r\n bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0);\r\n }\r\n this.fromBER(bytes.buffer, 0, bytes.length);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n if (this.isFirstSid) {\r\n let sidValue = this.valueDec;\r\n if (this.valueDec <= 39)\r\n result = \"0.\";\r\n else {\r\n if (this.valueDec <= 79) {\r\n result = \"1.\";\r\n sidValue -= 40;\r\n }\r\n else {\r\n result = \"2.\";\r\n sidValue -= 80;\r\n }\r\n }\r\n result += sidValue.toString();\r\n }\r\n else\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n isFirstSid: this.isFirstSid,\r\n };\r\n }\r\n}\r\nLocalSidValueBlock.NAME = \"sidBlock\";\n\nclass LocalObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n if (this.value.length === 0)\r\n sidBlock.isFirstSid = true;\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n let flag = false;\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n if (flag) {\r\n const sidBlock = this.value[0];\r\n let plus = 0;\r\n switch (sidBlock.valueDec) {\r\n case 0:\r\n break;\r\n case 1:\r\n plus = 40;\r\n break;\r\n case 2:\r\n plus = 80;\r\n break;\r\n default:\r\n this.value = [];\r\n return;\r\n }\r\n const parsedSID = parseInt(sid, 10);\r\n if (isNaN(parsedSID))\r\n return;\r\n sidBlock.valueDec = parsedSID + plus;\r\n flag = false;\r\n }\r\n else {\r\n const sidBlock = new LocalSidValueBlock();\r\n if (sid > Number.MAX_SAFE_INTEGER) {\r\n assertBigInt();\r\n const sidValue = BigInt(sid);\r\n sidBlock.valueBigInt = sidValue;\r\n }\r\n else {\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return;\r\n }\r\n if (!this.value.length) {\r\n sidBlock.isFirstSid = true;\r\n flag = true;\r\n }\r\n this.value.push(sidBlock);\r\n }\r\n } while (pos2 !== -1);\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n if (this.value[i].isFirstSid)\r\n result = `2.{${sidStr} - 80}`;\r\n else\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++) {\r\n object.sidArray.push(this.value[i].toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalObjectIdentifierValueBlock.NAME = \"ObjectIdentifierValueBlock\";\n\nvar _a$m;\r\nclass ObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 6;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$m = ObjectIdentifier;\r\n(() => {\r\n typeStore.ObjectIdentifier = _a$m;\r\n})();\r\nObjectIdentifier.NAME = \"OBJECT IDENTIFIER\";\n\nclass LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ valueDec = 0, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (inputLength === 0)\r\n return inputOffset;\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength))\r\n return -1;\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++)\r\n tempView[i] = this.valueHexView[i];\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView.buffer;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n}\r\nLocalRelativeSidValueBlock.NAME = \"relativeSidBlock\";\n\nclass LocalRelativeObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return true;\r\n this.value.push(sidBlock);\r\n } while (pos2 !== -1);\r\n return true;\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++)\r\n object.sidArray.push(this.value[i].toJSON());\r\n return object;\r\n }\r\n}\r\nLocalRelativeObjectIdentifierValueBlock.NAME = \"RelativeObjectIdentifierValueBlock\";\n\nvar _a$l;\r\nclass RelativeObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalRelativeObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 13;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$l = RelativeObjectIdentifier;\r\n(() => {\r\n typeStore.RelativeObjectIdentifier = _a$l;\r\n})();\r\nRelativeObjectIdentifier.NAME = \"RelativeObjectIdentifier\";\n\nvar _a$k;\r\nclass Sequence extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 16;\r\n }\r\n}\r\n_a$k = Sequence;\r\n(() => {\r\n typeStore.Sequence = _a$k;\r\n})();\r\nSequence.NAME = \"SEQUENCE\";\n\nvar _a$j;\r\nclass Set extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 17;\r\n }\r\n}\r\n_a$j = Set;\r\n(() => {\r\n typeStore.Set = _a$j;\r\n})();\r\nSet.NAME = \"SET\";\n\nclass LocalStringValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = true;\r\n this.value = EMPTY_STRING;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalStringValueBlock.NAME = \"StringValueBlock\";\n\nclass LocalSimpleStringValueBlock extends LocalStringValueBlock {\r\n}\r\nLocalSimpleStringValueBlock.NAME = \"SimpleStringValueBlock\";\n\nclass LocalSimpleStringBlock extends BaseStringBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters, LocalSimpleStringValueBlock);\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLen = inputString.length;\r\n const view = this.valueBlock.valueHexView = new Uint8Array(strLen);\r\n for (let i = 0; i < strLen; i++)\r\n view[i] = inputString.charCodeAt(i);\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalSimpleStringBlock.NAME = \"SIMPLE STRING\";\n\nclass LocalUtf8StringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n try {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf8String(inputBuffer);\r\n }\r\n catch (ex) {\r\n this.warnings.push(`Error during \"decodeURIComponent\": ${ex}, using raw string`);\r\n this.valueBlock.value = pvtsutils.Convert.ToBinary(inputBuffer);\r\n }\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf8String(inputString));\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUtf8StringValueBlock.NAME = \"Utf8StringValueBlock\";\n\nvar _a$i;\r\nclass Utf8String extends LocalUtf8StringValueBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 12;\r\n }\r\n}\r\n_a$i = Utf8String;\r\n(() => {\r\n typeStore.Utf8String = _a$i;\r\n})();\r\nUtf8String.NAME = \"UTF8String\";\n\nclass LocalBmpStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf16String(inputBuffer);\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.value = inputString;\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf16String(inputString));\r\n }\r\n}\r\nLocalBmpStringValueBlock.NAME = \"BmpStringValueBlock\";\n\nvar _a$h;\r\nclass BmpString extends LocalBmpStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 30;\r\n }\r\n}\r\n_a$h = BmpString;\r\n(() => {\r\n typeStore.BmpString = _a$h;\r\n})();\r\nBmpString.NAME = \"BMPString\";\n\nclass LocalUniversalStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0);\r\n const valueView = new Uint8Array(copyBuffer);\r\n for (let i = 0; i < valueView.length; i += 4) {\r\n valueView[i] = valueView[i + 3];\r\n valueView[i + 1] = valueView[i + 2];\r\n valueView[i + 2] = 0x00;\r\n valueView[i + 3] = 0x00;\r\n }\r\n this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLength = inputString.length;\r\n const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4);\r\n for (let i = 0; i < strLength; i++) {\r\n const codeBuf = pvutils.utilToBase(inputString.charCodeAt(i), 8);\r\n const codeView = new Uint8Array(codeBuf);\r\n if (codeView.length > 4)\r\n continue;\r\n const dif = 4 - codeView.length;\r\n for (let j = (codeView.length - 1); j >= 0; j--)\r\n valueHexView[i * 4 + j + dif] = codeView[j];\r\n }\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUniversalStringValueBlock.NAME = \"UniversalStringValueBlock\";\n\nvar _a$g;\r\nclass UniversalString extends LocalUniversalStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 28;\r\n }\r\n}\r\n_a$g = UniversalString;\r\n(() => {\r\n typeStore.UniversalString = _a$g;\r\n})();\r\nUniversalString.NAME = \"UniversalString\";\n\nvar _a$f;\r\nclass NumericString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 18;\r\n }\r\n}\r\n_a$f = NumericString;\r\n(() => {\r\n typeStore.NumericString = _a$f;\r\n})();\r\nNumericString.NAME = \"NumericString\";\n\nvar _a$e;\r\nclass PrintableString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 19;\r\n }\r\n}\r\n_a$e = PrintableString;\r\n(() => {\r\n typeStore.PrintableString = _a$e;\r\n})();\r\nPrintableString.NAME = \"PrintableString\";\n\nvar _a$d;\r\nclass TeletexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 20;\r\n }\r\n}\r\n_a$d = TeletexString;\r\n(() => {\r\n typeStore.TeletexString = _a$d;\r\n})();\r\nTeletexString.NAME = \"TeletexString\";\n\nvar _a$c;\r\nclass VideotexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 21;\r\n }\r\n}\r\n_a$c = VideotexString;\r\n(() => {\r\n typeStore.VideotexString = _a$c;\r\n})();\r\nVideotexString.NAME = \"VideotexString\";\n\nvar _a$b;\r\nclass IA5String extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 22;\r\n }\r\n}\r\n_a$b = IA5String;\r\n(() => {\r\n typeStore.IA5String = _a$b;\r\n})();\r\nIA5String.NAME = \"IA5String\";\n\nvar _a$a;\r\nclass GraphicString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 25;\r\n }\r\n}\r\n_a$a = GraphicString;\r\n(() => {\r\n typeStore.GraphicString = _a$a;\r\n})();\r\nGraphicString.NAME = \"GraphicString\";\n\nvar _a$9;\r\nclass VisibleString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 26;\r\n }\r\n}\r\n_a$9 = VisibleString;\r\n(() => {\r\n typeStore.VisibleString = _a$9;\r\n})();\r\nVisibleString.NAME = \"VisibleString\";\n\nvar _a$8;\r\nclass GeneralString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 27;\r\n }\r\n}\r\n_a$8 = GeneralString;\r\n(() => {\r\n typeStore.GeneralString = _a$8;\r\n})();\r\nGeneralString.NAME = \"GeneralString\";\n\nvar _a$7;\r\nclass CharacterString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 29;\r\n }\r\n}\r\n_a$7 = CharacterString;\r\n(() => {\r\n typeStore.CharacterString = _a$7;\r\n})();\r\nCharacterString.NAME = \"CharacterString\";\n\nvar _a$6;\r\nclass UTCTime extends VisibleString {\r\n constructor({ value, valueDate, ...parameters } = {}) {\r\n super(parameters);\r\n this.year = 0;\r\n this.month = 0;\r\n this.day = 0;\r\n this.hour = 0;\r\n this.minute = 0;\r\n this.second = 0;\r\n if (value) {\r\n this.fromString(value);\r\n this.valueBlock.valueHexView = new Uint8Array(value.length);\r\n for (let i = 0; i < value.length; i++)\r\n this.valueBlock.valueHexView[i] = value.charCodeAt(i);\r\n }\r\n if (valueDate) {\r\n this.fromDate(valueDate);\r\n this.valueBlock.valueHexView = new Uint8Array(this.toBuffer());\r\n }\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 23;\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.fromString(String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer)));\r\n }\r\n toBuffer() {\r\n const str = this.toString();\r\n const buffer = new ArrayBuffer(str.length);\r\n const view = new Uint8Array(buffer);\r\n for (let i = 0; i < str.length; i++)\r\n view[i] = str.charCodeAt(i);\r\n return buffer;\r\n }\r\n fromDate(inputDate) {\r\n this.year = inputDate.getUTCFullYear();\r\n this.month = inputDate.getUTCMonth() + 1;\r\n this.day = inputDate.getUTCDate();\r\n this.hour = inputDate.getUTCHours();\r\n this.minute = inputDate.getUTCMinutes();\r\n this.second = inputDate.getUTCSeconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second)));\r\n }\r\n fromString(inputString) {\r\n const parser = /(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z/ig;\r\n const parserArray = parser.exec(inputString);\r\n if (parserArray === null) {\r\n this.error = \"Wrong input string for conversion\";\r\n return;\r\n }\r\n const year = parseInt(parserArray[1], 10);\r\n if (year >= 50)\r\n this.year = 1900 + year;\r\n else\r\n this.year = 2000 + year;\r\n this.month = parseInt(parserArray[2], 10);\r\n this.day = parseInt(parserArray[3], 10);\r\n this.hour = parseInt(parserArray[4], 10);\r\n this.minute = parseInt(parserArray[5], 10);\r\n this.second = parseInt(parserArray[6], 10);\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = new Array(7);\r\n outputArray[0] = pvutils.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2);\r\n outputArray[1] = pvutils.padNumber(this.month, 2);\r\n outputArray[2] = pvutils.padNumber(this.day, 2);\r\n outputArray[3] = pvutils.padNumber(this.hour, 2);\r\n outputArray[4] = pvutils.padNumber(this.minute, 2);\r\n outputArray[5] = pvutils.padNumber(this.second, 2);\r\n outputArray[6] = \"Z\";\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.toDate().toISOString()}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n year: this.year,\r\n month: this.month,\r\n day: this.day,\r\n hour: this.hour,\r\n minute: this.minute,\r\n second: this.second,\r\n };\r\n }\r\n}\r\n_a$6 = UTCTime;\r\n(() => {\r\n typeStore.UTCTime = _a$6;\r\n})();\r\nUTCTime.NAME = \"UTCTime\";\n\nvar _a$5;\r\nclass GeneralizedTime extends UTCTime {\r\n constructor(parameters = {}) {\r\n var _b;\r\n super(parameters);\r\n (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 24;\r\n }\r\n fromDate(inputDate) {\r\n super.fromDate(inputDate);\r\n this.millisecond = inputDate.getUTCMilliseconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)));\r\n }\r\n fromString(inputString) {\r\n let isUTC = false;\r\n let timeString = \"\";\r\n let dateTimeString = \"\";\r\n let fractionPart = 0;\r\n let parser;\r\n let hourDifference = 0;\r\n let minuteDifference = 0;\r\n if (inputString[inputString.length - 1] === \"Z\") {\r\n timeString = inputString.substring(0, inputString.length - 1);\r\n isUTC = true;\r\n }\r\n else {\r\n const number = new Number(inputString[inputString.length - 1]);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n timeString = inputString;\r\n }\r\n if (isUTC) {\r\n if (timeString.indexOf(\"+\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n if (timeString.indexOf(\"-\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n else {\r\n let multiplier = 1;\r\n let differencePosition = timeString.indexOf(\"+\");\r\n let differenceString = \"\";\r\n if (differencePosition === -1) {\r\n differencePosition = timeString.indexOf(\"-\");\r\n multiplier = -1;\r\n }\r\n if (differencePosition !== -1) {\r\n differenceString = timeString.substring(differencePosition + 1);\r\n timeString = timeString.substring(0, differencePosition);\r\n if ((differenceString.length !== 2) && (differenceString.length !== 4))\r\n throw new Error(\"Wrong input string for conversion\");\r\n let number = parseInt(differenceString.substring(0, 2), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n hourDifference = multiplier * number;\r\n if (differenceString.length === 4) {\r\n number = parseInt(differenceString.substring(2, 4), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n minuteDifference = multiplier * number;\r\n }\r\n }\r\n }\r\n let fractionPointPosition = timeString.indexOf(\".\");\r\n if (fractionPointPosition === -1)\r\n fractionPointPosition = timeString.indexOf(\",\");\r\n if (fractionPointPosition !== -1) {\r\n const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`);\r\n if (isNaN(fractionPartCheck.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n fractionPart = fractionPartCheck.valueOf();\r\n dateTimeString = timeString.substring(0, fractionPointPosition);\r\n }\r\n else\r\n dateTimeString = timeString;\r\n switch (true) {\r\n case (dateTimeString.length === 8):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n break;\r\n case (dateTimeString.length === 10):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.minute = Math.floor(fractionResult);\r\n fractionResult = 60 * (fractionResult - this.minute);\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 12):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 14):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n const fractionResult = 1000 * fractionPart;\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n const parserArray = parser.exec(dateTimeString);\r\n if (parserArray === null)\r\n throw new Error(\"Wrong input string for conversion\");\r\n for (let j = 1; j < parserArray.length; j++) {\r\n switch (j) {\r\n case 1:\r\n this.year = parseInt(parserArray[j], 10);\r\n break;\r\n case 2:\r\n this.month = parseInt(parserArray[j], 10);\r\n break;\r\n case 3:\r\n this.day = parseInt(parserArray[j], 10);\r\n break;\r\n case 4:\r\n this.hour = parseInt(parserArray[j], 10) + hourDifference;\r\n break;\r\n case 5:\r\n this.minute = parseInt(parserArray[j], 10) + minuteDifference;\r\n break;\r\n case 6:\r\n this.second = parseInt(parserArray[j], 10);\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n }\r\n if (isUTC === false) {\r\n const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\r\n this.year = tempDate.getUTCFullYear();\r\n this.month = tempDate.getUTCMonth();\r\n this.day = tempDate.getUTCDay();\r\n this.hour = tempDate.getUTCHours();\r\n this.minute = tempDate.getUTCMinutes();\r\n this.second = tempDate.getUTCSeconds();\r\n this.millisecond = tempDate.getUTCMilliseconds();\r\n }\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = [];\r\n outputArray.push(pvutils.padNumber(this.year, 4));\r\n outputArray.push(pvutils.padNumber(this.month, 2));\r\n outputArray.push(pvutils.padNumber(this.day, 2));\r\n outputArray.push(pvutils.padNumber(this.hour, 2));\r\n outputArray.push(pvutils.padNumber(this.minute, 2));\r\n outputArray.push(pvutils.padNumber(this.second, 2));\r\n if (this.millisecond !== 0) {\r\n outputArray.push(\".\");\r\n outputArray.push(pvutils.padNumber(this.millisecond, 3));\r\n }\r\n outputArray.push(\"Z\");\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n millisecond: this.millisecond,\r\n };\r\n }\r\n}\r\n_a$5 = GeneralizedTime;\r\n(() => {\r\n typeStore.GeneralizedTime = _a$5;\r\n})();\r\nGeneralizedTime.NAME = \"GeneralizedTime\";\n\nvar _a$4;\r\nclass DATE extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 31;\r\n }\r\n}\r\n_a$4 = DATE;\r\n(() => {\r\n typeStore.DATE = _a$4;\r\n})();\r\nDATE.NAME = \"DATE\";\n\nvar _a$3;\r\nclass TimeOfDay extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 32;\r\n }\r\n}\r\n_a$3 = TimeOfDay;\r\n(() => {\r\n typeStore.TimeOfDay = _a$3;\r\n})();\r\nTimeOfDay.NAME = \"TimeOfDay\";\n\nvar _a$2;\r\nclass DateTime extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 33;\r\n }\r\n}\r\n_a$2 = DateTime;\r\n(() => {\r\n typeStore.DateTime = _a$2;\r\n})();\r\nDateTime.NAME = \"DateTime\";\n\nvar _a$1;\r\nclass Duration extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 34;\r\n }\r\n}\r\n_a$1 = Duration;\r\n(() => {\r\n typeStore.Duration = _a$1;\r\n})();\r\nDuration.NAME = \"Duration\";\n\nvar _a;\r\nclass TIME extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 14;\r\n }\r\n}\r\n_a = TIME;\r\n(() => {\r\n typeStore.TIME = _a;\r\n})();\r\nTIME.NAME = \"TIME\";\n\nclass Any {\r\n constructor({ name = EMPTY_STRING, optional = false, } = {}) {\r\n this.name = name;\r\n this.optional = optional;\r\n }\r\n}\n\nclass Choice extends Any {\r\n constructor({ value = [], ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n }\r\n}\n\nclass Repeated extends Any {\r\n constructor({ value = new Any(), local = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.local = local;\r\n }\r\n}\n\nclass RawData {\r\n constructor({ data = EMPTY_VIEW } = {}) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(data);\r\n }\r\n get data() {\r\n return this.dataView.slice().buffer;\r\n }\r\n set data(value) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const endLength = inputOffset + inputLength;\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);\r\n return endLength;\r\n }\r\n toBER(sizeOnly) {\r\n return this.dataView.slice().buffer;\r\n }\r\n}\n\nfunction compareSchema(root, inputData, inputSchema) {\r\n if (inputSchema instanceof Choice) {\r\n for (let j = 0; j < inputSchema.value.length; j++) {\r\n const result = compareSchema(root, inputData, inputSchema.value[j]);\r\n if (result.verified) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n }\r\n {\r\n const _result = {\r\n verified: false,\r\n result: {\r\n error: \"Wrong values for Choice type\"\r\n },\r\n };\r\n if (inputSchema.hasOwnProperty(NAME))\r\n _result.name = inputSchema.name;\r\n return _result;\r\n }\r\n }\r\n if (inputSchema instanceof Any) {\r\n if (inputSchema.hasOwnProperty(NAME))\r\n root[inputSchema.name] = inputData;\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((root instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong root object\" }\r\n };\r\n }\r\n if ((inputData instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 data\" }\r\n };\r\n }\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((ID_BLOCK in inputSchema) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((FROM_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((TO_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const encodedId = inputSchema.idBlock.toBER(false);\r\n if (encodedId.byteLength === 0) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error encoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength);\r\n if (decodedOffset === -1) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error decoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (!(IS_HEX_ONLY in inputSchema.idBlock)) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly) {\r\n if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const schemaView = inputSchema.idBlock.valueHexView;\r\n const asn1View = inputData.idBlock.valueHexView;\r\n if (schemaView.length !== asn1View.length) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < schemaView.length; i++) {\r\n if (schemaView[i] !== asn1View[1]) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n }\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n root[inputSchema.name] = inputData;\r\n }\r\n if (inputSchema instanceof typeStore.Constructed) {\r\n let admission = 0;\r\n let result = {\r\n verified: false,\r\n result: {\r\n error: \"Unknown error\",\r\n }\r\n };\r\n let maxLength = inputSchema.valueBlock.value.length;\r\n if (maxLength > 0) {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n maxLength = inputData.valueBlock.value.length;\r\n }\r\n }\r\n if (maxLength === 0) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((inputData.valueBlock.value.length === 0) &&\r\n (inputSchema.valueBlock.value.length !== 0)) {\r\n let _optional = true;\r\n for (let i = 0; i < inputSchema.valueBlock.value.length; i++)\r\n _optional = _optional && (inputSchema.valueBlock.value[i].optional || false);\r\n if (_optional) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n root.error = \"Inconsistent object length\";\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < maxLength; i++) {\r\n if ((i - admission) >= inputData.valueBlock.value.length) {\r\n if (inputSchema.valueBlock.value[i].optional === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n root.error = \"Inconsistent length between ASN.1 data and schema\";\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n }\r\n else {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[0].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) {\r\n let arrayRoot = {};\r\n if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local))\r\n arrayRoot = inputData;\r\n else\r\n arrayRoot = root;\r\n if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === \"undefined\")\r\n arrayRoot[inputSchema.valueBlock.value[0].name] = [];\r\n arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]);\r\n }\r\n }\r\n else {\r\n result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[i].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (result.verified === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.primitiveSchema &&\r\n (VALUE_HEX_VIEW in inputData.valueBlock)) {\r\n const asn1 = localFromBER(inputData.valueBlock.valueHexView);\r\n if (asn1.offset === -1) {\r\n const _result = {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return compareSchema(root, asn1.result, inputSchema.primitiveSchema);\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n}\r\nfunction verifySchema(inputBuffer, inputSchema) {\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema type\" }\r\n };\r\n }\r\n const asn1 = localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n if (asn1.offset === -1) {\r\n return {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n }\r\n return compareSchema(asn1.result, asn1.result, inputSchema);\r\n}\n\nexport { Any, BaseBlock, BaseStringBlock, BitString, BmpString, Boolean, CharacterString, Choice, Constructed, DATE, DateTime, Duration, EndOfContent, Enumerated, GeneralString, GeneralizedTime, GraphicString, HexBlock, IA5String, Integer, Null, NumericString, ObjectIdentifier, OctetString, Primitive, PrintableString, RawData, RelativeObjectIdentifier, Repeated, Sequence, Set, TIME, TeletexString, TimeOfDay, UTCTime, UniversalString, Utf8String, ValueBlock, VideotexString, ViewWriter, VisibleString, compareSchema, fromBER, verifySchema };\n","import { CodeError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH')\n }\n return randB(length)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2'\nimport { sha512 } from '@noble/hashes/sha512'\nimport * as asn1js from 'asn1js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport { type RsaPrivateKey, unmarshalRsaPrivateKey } from './rsa-class.js'\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value\n\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n }\n\n return key\n}\n\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value\n\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n }\n}\n\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\nfunction bnToBuf (bn: bigint): Uint8Array {\n let hex = bn.toString(16)\n\n if (hex.length % 2 > 0) {\n hex = `0${hex}`\n }\n\n const len = hex.length / 2\n const u8 = new Uint8Array(len)\n\n let i = 0\n let j = 0\n\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16)\n i += 1\n j += 2\n }\n\n return u8\n}\n\nfunction bufToBn (u8: Uint8Array): bigint {\n const hex: string[] = []\n\n u8.forEach(function (i) {\n let h = i.toString(16)\n\n if (h.length % 2 > 0) {\n h = `0${h}`\n }\n\n hex.push(h)\n })\n\n return BigInt('0x' + hex.join(''))\n}\n\nconst SALT_LENGTH = 16\nconst KEY_SIZE = 32\nconst ITERATIONS = 10000\n\nexport async function exportToPem (privateKey: RsaPrivateKey, password: string): Promise {\n const crypto = webcrypto.get()\n\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n })\n\n const keyBuf = keyWrapper.toBER()\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength)\n const salt = randomBytes(SALT_LENGTH)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n }\n )\n\n const iv = randomBytes(16)\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt'])\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr)\n\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n })\n\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n })\n\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n })\n\n const finalWrapperBuf = finalWrapper.toBER()\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength)\n\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n')\n}\n\nexport async function importFromPem (pem: string, password: string): Promise {\n const crypto = webcrypto.get()\n let plaintext: Uint8Array\n\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n const {\n iv,\n salt,\n iterations,\n keySize,\n cipherText\n } = findEncryptedPEMData(result)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: iterations,\n dkLen: keySize\n }\n )\n\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt'])\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText))\n\n const { result: decryptedResult } = asn1js.fromBER(decrypted)\n plaintext = findPEMData(decryptedResult)\n } else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n plaintext = findPEMData(result)\n } else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS')\n }\n\n return unmarshalRsaPrivateKey(plaintext)\n}\n\nfunction findEncryptedPEMData (root: any): { cipherText: Uint8Array, iv: Uint8Array, salt: Uint8Array, iterations: number, keySize: number } {\n const encryptionAlgorithm = root.valueBlock.value[0]\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString()\n\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS')\n }\n\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0]\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString()\n\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS')\n }\n\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1]\n\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue())\n\n let iterations = ITERATIONS\n let keySize = KEY_SIZE\n\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number((pbkdf2Params.valueBlock.value[1] as asn1js.Integer).toBigInt())\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt())\n } else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS')\n }\n\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1]\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString()\n\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n } else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS')\n }\n\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue())\n\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n }\n}\n\nfunction findPEMData (seq: any): Uint8Array {\n return toUint8Array(seq.valueBlock.value[2].getValue())\n}\n\nfunction toUint8Array (buf: ArrayBuffer): Uint8Array {\n return new Uint8Array(buf, 0, buf.byteLength)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport * as crypto from './rsa.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const MAX_RSA_KEY_SIZE = 8192\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean | boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret (): Uint8Array {\n return crypto.getRandomValues(16)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): RsaPublicKey {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export (password: string, format = 'pkcs-8'): Promise> {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password)\n } else if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array): Promise {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array): RsaPublicKey {\n const jwk = crypto.utils.pkixToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey): Promise {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number): Promise {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.generateKey(bits)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { isPromise } from '../util.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign (key: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.sign(p.digest, key).toDERRawBytes()\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.verify(sig, p.digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array): void {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array): void {\n try {\n secp.ProjectivePoint.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\nimport * as crypto from './secp256k1.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Secp256k1PublicKey {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const privateKeyBytes = crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport * as Ed25519 from './ed25519-class.js'\nimport generateEphemeralKeyPair from './ephemeral-keys.js'\nimport { importer } from './importer.js'\nimport { keyStretcher } from './key-stretcher.js'\nimport * as keysPBM from './keys.js'\nimport * as RSA from './rsa-class.js'\nimport { importFromPem } from './rsa-utils.js'\nimport * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js'\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js'\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js'\nexport type { JWKKeyPair } from './interface.js'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string): CodeError> {\n const supported = Object.keys(supportedKeys).join(' / ')\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE')\n}\n\nfunction typeToKey (type: string): typeof RSA | typeof Ed25519 | typeof Secp256k1 {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise {\n return typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE')\n }\n\n return Ed25519.generateKeyPairFromSeed(seed)\n}\n\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown')\n }\n}\n\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise {\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA')\n }\n}\n\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey (encryptedKey: string, password: string): Promise {\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT')\n }\n\n return importFromPem(encryptedKey, password)\n}\n","export const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.payloadType)\n }\n\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26)\n w.bytes(obj.payload)\n }\n\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42)\n w.bytes(obj.signature)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.publicKey = reader.bytes()\n break\n case 2:\n obj.payloadType = reader.bytes()\n break\n case 3:\n obj.payload = reader.bytes()\n break\n case 5:\n obj.signature = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\n","import { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { CodeError } from '@libp2p/interface'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { codes } from '../errors.js'\nimport { Envelope as Protobuf } from './envelope.js'\nimport type { PeerId, Record, Envelope } from '@libp2p/interface'\n\nexport interface RecordEnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array | Uint8ArrayList): Promise => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\n }\n\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record: Record, peerId: PeerId): Promise => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\n\n const domain = record.domain\n const payloadType = record.codec\n const payload = record.marshal()\n const signData = formatSignaturePayload(domain, payloadType, payload)\n const key = await unmarshalPrivateKey(peerId.privateKey)\n const signature = await key.sign(signData.subarray())\n\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\n }\n\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data: Uint8Array | Uint8ArrayList, domain: string): Promise => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw new CodeError('envelope signature is not valid for the given domain', codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: RecordEnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope): boolean {\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string): Promise {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return key.verify(signData.subarray(), this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = varint.encode(domainUint8Array.byteLength)\n const payloadTypeLength = varint.encode(payloadType.length)\n const payloadLength = varint.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16)\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n","import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [777, V, 'memory']\n]\n\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\n}\n\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol (proto: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n","/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport { IpNet } from '@chainsafe/netmask'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf)\n case 42: // ipv6zone\n return bytes2str(buf)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf)\n\n case 421: // ipfs\n return bytes2mh(buf)\n case 444: // onion\n return bytes2onion(buf)\n case 445: // onion3\n return bytes2onion(buf)\n case 466: // certhash\n return bytes2mb(buf)\n default:\n return uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str)\n case 41: // ipv6\n return ip2bytes(str)\n case 42: // ipv6zone\n return str2bytes(str)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str)\n\n case 421: // ipfs\n return mh2bytes(str)\n case 444: // onion\n return onion2bytes(str)\n case 445: // onion3\n return onion32bytes(str)\n case 466: // certhash\n return mb2bytes(str)\n default:\n return uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value\n }\n if (code === ipcidrProtocol.code) {\n mask = value\n }\n })\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr')\n }\n return new IpNet(addr, mask)\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length)\n if (ipString == null) {\n throw new Error('ipBuff is required')\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ipString\n}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.encodingLength(size))\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\n\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length))\n return uint8ArrayConcat([size, mh], size.length + mh.length)\n}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\n const mb = anybaseDecoder.decode(mbstr)\n const size = Uint8Array.from(varint.encode(mb.length))\n return uint8ArrayConcat([size, mb], size.length + mb.length)\n}\nfunction bytes2mb (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.encodingLength(size))\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.encodingLength(size))\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.slice(0, buf.length - 2)\n const portBytes = buf.slice(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n","import * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\nexport interface MultiaddrParts {\n bytes: Uint8Array\n string: string\n tuples: Tuple[]\n stringTuples: StringTuple[]\n path: string | null\n}\n\nexport function stringToMultiaddrParts (str: string): MultiaddrParts {\n str = cleanPath(str)\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n const parts = str.split('/').slice(1)\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n }\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([proto.code])\n stringTuples.push([proto.code])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'))\n tuples.push([proto.code, convertToBytes(proto.code, path)])\n stringTuples.push([proto.code, path])\n break\n }\n\n const bytes = convertToBytes(proto.code, parts[p])\n tuples.push([proto.code, bytes])\n stringTuples.push([proto.code, convertToString(proto.code, bytes)])\n }\n\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n }\n}\n\nexport function bytesToMultiaddrParts (bytes: Uint8Array): MultiaddrParts {\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, bytes.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n stringTuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = bytes.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n const stringAddr = convertToString(code, addr)\n stringTuples.push([code, stringAddr])\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr\n break\n }\n }\n\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n }\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n }))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr))\n return size + varint.encodingLength(size)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a Multiaddr in JavaScript\n *\n * @example\n *\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, type MultiaddrParts, tuplesToBytes } from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport { isMultiaddr, multiaddr, resolvers } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, MultiaddrObject, Protocol, StringTuple, Tuple, NodeAddress, ResolveOptions } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n public bytes: Uint8Array\n #string: string\n #tuples: Tuple[]\n #stringTuples: StringTuple[]\n #path: string | null\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n let parts: MultiaddrParts\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr)\n } else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`)\n }\n parts = stringToMultiaddrParts(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes)\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n\n this.bytes = parts.bytes\n this.#string = parts.string\n this.#tuples = parts.tuples\n this.#stringTuples = parts.stringTuples\n this.#path = parts.path\n }\n\n toString (): string {\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\n const tcp = getProtocol('tcp')\n const udp = getProtocol('udp')\n const ip4 = getProtocol('ip4')\n const ip6 = getProtocol('ip6')\n const dns6 = getProtocol('dns6')\n const ip6zone = getProtocol('ip6zone')\n\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\n\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name\n port = 443\n host = `${value ?? ''}${zone}`\n family = code === dns6.code ? 6 : 4\n }\n\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\n\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name\n host = `${value ?? ''}${zone}`\n family = code === ip6.code ? 6 : 4\n }\n }\n\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".')\n }\n\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n return this.#tuples.map(([code]) => code)\n }\n\n protoNames (): string[] {\n return this.#tuples.map(([code]) => getProtocol(code).name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new Multiaddr(addr)\n return new Multiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`)\n }\n return new Multiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr(tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n let tuples: Array<[number, string | undefined]> = []\n\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name])\n }\n\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = []\n }\n })\n\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc')\n }\n\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n return this.#path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: ResolveOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const result = await resolver(this, options)\n\n return result.map(str => multiaddr(str))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`)\n }\n\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\n\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false\n }\n return true\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.#string})`\n }\n}\n","/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddr } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddr)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(await ma.resolve(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\n\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Resolver } from './resolvers/index.js'\nimport type { DNS } from '@multiformats/dns'\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\n\nexport type { Resolver }\n\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js'\n\nexport interface ResolveOptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions(): MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos(): Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes(): number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames(): string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples(): Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples(): StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId(): string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath(): string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve(options?: ResolveOptions): Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress(): NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress(addr?: Multiaddr): boolean\n}\n\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\n if (addr == null) {\n throw new Error('requires node address object')\n }\n if (transport == null) {\n throw new Error('requires transport protocol')\n }\n let ip: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\n\n host = parts[0]\n const zone = parts[1]\n ip = `/ip6zone/${zone}/ip6`\n }\n break\n default:\n throw Error('Invalid addr family, should be 4 or 6.')\n }\n return new MultiaddrClass('/' + [ip, host, transport, addr.port].join('/'))\n}\n\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName (addr: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\nexport { getProtocol as protocols }\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\n\nimport { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { type Multiaddr } from '@multiformats/multiaddr'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64url } from 'multiformats/bases/base64'\n\n/**\n * Split a multiaddr into path components\n */\nconst toParts = (ma: Multiaddr): string[] => {\n return ma.toString().split('/').slice(1)\n}\n\n/**\n * A matcher accepts multiaddr components and either fails to match and returns\n * false or returns a sublist of unmatched components\n */\ninterface Matcher {\n match(parts: string[]): string[] | false\n pattern: string\n}\n\nconst func = (fn: (val: string) => boolean): Matcher => {\n return {\n match: (vals) => {\n if (vals.length < 1) {\n return false\n }\n\n if (fn(vals[0])) {\n return vals.slice(1)\n }\n\n return false\n },\n pattern: 'fn'\n }\n}\n\nconst literal = (str: string): Matcher => {\n return {\n match: (vals) => func((val) => val === str).match(vals),\n pattern: str\n }\n}\n\nconst string = (): Matcher => {\n return {\n match: (vals) => func((val) => typeof val === 'string').match(vals),\n pattern: '{string}'\n }\n}\n\nconst number = (): Matcher => {\n return {\n match: (vals) => func((val) => !isNaN(parseInt(val))).match(vals),\n pattern: '{number}'\n }\n}\n\nconst peerId = (): Matcher => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false\n }\n\n if (vals[0] !== 'p2p' && vals[0] !== 'ipfs') {\n return false\n }\n\n // Q is RSA, 1 is Ed25519 or Secp256k1\n if (vals[1].startsWith('Q') || vals[1].startsWith('1')) {\n try {\n base58btc.decode(`z${vals[1]}`)\n } catch (err) {\n return false\n }\n } else {\n return false\n }\n\n return vals.slice(2)\n },\n pattern: '/p2p/{peerid}'\n }\n}\n\nconst certhash = (): Matcher => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false\n }\n\n if (vals[0] !== 'certhash') {\n return false\n }\n\n try {\n base64url.decode(vals[1])\n } catch {\n return false\n }\n\n return vals.slice(2)\n },\n pattern: '/certhash/{certhash}'\n }\n}\n\nconst optional = (matcher: Matcher): Matcher => {\n return {\n match: (vals) => {\n const result = matcher.match(vals)\n\n if (result === false) {\n return vals\n }\n\n return result\n },\n pattern: `optional(${matcher.pattern})`\n }\n}\n\nconst or = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n let matches: string[] | undefined\n\n for (const matcher of matchers) {\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n continue\n }\n\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result\n }\n }\n\n if (matches == null) {\n return false\n }\n\n return matches\n },\n pattern: `or(${matchers.map(m => m.pattern).join(', ')})`\n }\n}\n\nconst and = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n return false\n }\n\n vals = result\n }\n\n return vals\n },\n pattern: `and(${matchers.map(m => m.pattern).join(', ')})`\n }\n}\n\nfunction fmt (...matchers: Matcher[]): MultiaddrMatcher {\n function match (ma: Multiaddr): string[] | false {\n let parts = toParts(ma)\n\n for (const matcher of matchers) {\n const result = matcher.match(parts)\n\n if (result === false) {\n return false\n }\n\n parts = result\n }\n\n return parts\n }\n\n function matches (ma: Multiaddr): boolean {\n const result = match(ma)\n\n return result !== false\n }\n\n function exactMatch (ma: Multiaddr): boolean {\n const result = match(ma)\n\n if (result === false) {\n return false\n }\n\n return result.length === 0\n }\n\n return {\n matches,\n exactMatch\n }\n}\n\n/**\n * A MultiaddrMatcher allows interpreting a multiaddr as a certain type of\n * multiaddr\n */\nexport interface MultiaddrMatcher {\n /**\n * Returns true if the passed multiaddr can be treated as this type of\n * multiaddr\n */\n matches(ma: Multiaddr): boolean\n\n /**\n * Returns true if the passed multiaddr terminates as this type of\n * multiaddr\n */\n exactMatch(ma: Multiaddr): boolean\n}\n\n/**\n * DNS matchers\n */\nconst _DNS4 = and(literal('dns4'), string())\nconst _DNS6 = and(literal('dns6'), string())\nconst _DNSADDR = and(literal('dnsaddr'), string())\nconst _DNS = and(literal('dns'), string())\n\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nexport const DNS4 = fmt(_DNS4)\n\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS6 = fmt(_DNS6)\n\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * ```\n */\nexport const DNSADDR = fmt(_DNSADDR)\n\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS = fmt(or(\n _DNS,\n _DNSADDR,\n _DNS4,\n _DNS6\n))\n\nconst _IP4 = and(literal('ip4'), func(isIPv4))\nconst _IP6 = and(literal('ip6'), func(isIPv6))\nconst _IP = or(\n _IP4,\n _IP6\n)\n\nconst _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR)\n\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nexport const IP_OR_DOMAIN = fmt(_IP_OR_DOMAIN)\n\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nexport const IP4 = fmt(_IP4)\n\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nexport const IP6 = fmt(_IP6)\n\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nexport const IP = fmt(_IP)\n\nconst _TCP = and(_IP_OR_DOMAIN, literal('tcp'), number())\nconst _UDP = and(_IP_OR_DOMAIN, literal('udp'), number())\n\nconst TCP_OR_UDP = or(_TCP, _UDP)\n\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nexport const TCP = fmt(_TCP)\n\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nexport const UDP = fmt(_UDP)\n\nconst _QUIC = and(_UDP, literal('quic'))\nconst _QUICV1 = and(_UDP, literal('quic-v1'))\n\nconst QUIC_V0_OR_V1 = or(_QUIC, _QUICV1)\n\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nexport const QUIC = fmt(_QUIC)\n\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUICV1 } from '@multiformats/multiaddr-matcher'\n *\n * QUICV1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nexport const QUICV1 = fmt(_QUICV1)\n\nconst _WEB = or(\n _IP_OR_DOMAIN,\n _TCP,\n _UDP,\n _QUIC,\n _QUICV1\n)\n\nconst _WebSockets = or(\n and(_WEB, literal('ws'), optional(peerId()))\n)\n\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nexport const WebSockets = fmt(_WebSockets)\n\nconst _WebSocketsSecure = or(\n and(_WEB, literal('wss'), optional(peerId())),\n and(_WEB, literal('tls'), literal('ws'), optional(peerId()))\n)\n\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nexport const WebSocketsSecure = fmt(_WebSocketsSecure)\n\nconst _WebRTCDirect = and(TCP_OR_UDP, literal('webrtc-direct'), certhash(), optional(certhash()), optional(peerId()))\n\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nexport const WebRTCDirect = fmt(_WebRTCDirect)\n\nconst _WebTransport = and(_QUICV1, literal('webtransport'), certhash(), certhash(), optional(peerId()))\n\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nexport const WebTransport = fmt(_WebTransport)\n\nconst _P2P = or(\n _WebSockets,\n _WebSocketsSecure,\n and(_TCP, optional(peerId())),\n and(QUIC_V0_OR_V1, optional(peerId())),\n and(_IP_OR_DOMAIN, optional(peerId())),\n _WebRTCDirect,\n _WebTransport,\n peerId()\n)\n\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nexport const P2P = fmt(_P2P)\n\nconst _Circuit = and(_P2P, literal('p2p-circuit'), peerId())\n\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nexport const Circuit = fmt(_Circuit)\n\nconst _WebRTC = or(\n and(_P2P, literal('p2p-circuit'), literal('webrtc'), peerId()),\n and(_P2P, literal('webrtc'), optional(peerId())),\n literal('webrtc')\n)\n\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nexport const WebRTC = fmt(_WebRTC)\n\nconst _HTTP = or(\n and(_IP_OR_DOMAIN, literal('tcp'), number(), literal('http'), optional(peerId())),\n and(_IP_OR_DOMAIN, literal('http'), optional(peerId()))\n)\n\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nexport const HTTP = fmt(_HTTP)\n\nconst _HTTPS = or(\n and(_IP_OR_DOMAIN, literal('tcp'), or(\n and(literal('443'), literal('http')),\n and(number(), literal('https'))\n ), optional(peerId())),\n and(_IP_OR_DOMAIN, literal('tls'), literal('http'), optional(peerId())),\n and(_IP_OR_DOMAIN, literal('https'), optional(peerId()))\n)\n\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nexport const HTTPS = fmt(_HTTPS)\n","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed Protobuf encoded\n * messages over streams.\n *\n * @example\n *\n * ```typescript\n * import { pbStream } from 'it-protobuf-stream'\n * import { MessageType } from './src/my-message-type.js'\n *\n * // RequestType and ResponseType have been generate from `.proto` files and have\n * // `.encode` and `.decode` methods for serialization/deserialization\n *\n * const stream = pbStream(duplex)\n *\n * // write a message to the stream\n * stream.write({\n * foo: 'bar'\n * }, MessageType)\n *\n * // read a message from the stream\n * const res = await stream.read(MessageType)\n * ```\n */\n\nimport { lpStream } from 'it-length-prefixed-stream'\nimport type { LengthPrefixedStreamOpts } from 'it-length-prefixed-stream'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * A protobuf decoder - takes a byte array and returns an object\n */\nexport interface Decoder {\n (data: Uint8Array | Uint8ArrayList): T\n}\n\n/**\n * A protobuf encoder - takes an object and returns a byte array\n */\nexport interface Encoder {\n (data: T): Uint8Array\n}\n\n/**\n * Convenience methods for working with protobuf streams\n */\nexport interface ProtobufStream {\n /**\n * Read the next length-prefixed byte array from the stream and decode it as the passed protobuf format\n */\n read(proto: { decode: Decoder }, options?: AbortOptions): Promise\n\n /**\n * Encode the passed object as a protobuf message and write it's length-prefixed bytes to the stream\n */\n write(data: T, proto: { encode: Encoder }, options?: AbortOptions): Promise\n\n /**\n * Encode the passed objects as protobuf messages and write their length-prefixed bytes to the stream as a single write\n */\n writeV(input: T[], proto: { encode: Encoder }, options?: AbortOptions): Promise\n\n /**\n * Returns an object with read/write methods for operating on one specific type of protobuf message\n */\n pb(proto: { encode: Encoder, decode: Decoder }): MessageStream\n\n /**\n * Returns the underlying stream\n */\n unwrap(): Stream\n}\n\n/**\n * A message reader/writer that only uses one type of message\n */\nexport interface MessageStream {\n /**\n * Read a message from the stream\n */\n read(options?: AbortOptions): Promise\n\n /**\n * Write a message to the stream\n */\n write(d: T, options?: AbortOptions): Promise\n\n /**\n * Write several messages to the stream\n */\n writeV(d: T[], options?: AbortOptions): Promise\n\n /**\n * Unwrap the underlying protobuf stream\n */\n unwrap(): ProtobufStream\n}\n\nexport interface ProtobufStreamOpts extends LengthPrefixedStreamOpts {\n\n}\n\nexport function pbStream > (duplex: Stream, opts?: Partial): ProtobufStream {\n const lp = lpStream(duplex, opts)\n\n const W: ProtobufStream = {\n read: async (proto, options?: AbortOptions) => {\n // readLP, decode\n const value = await lp.read(options)\n\n return proto.decode(value)\n },\n write: async (message, proto, options?: AbortOptions) => {\n // encode, writeLP\n await lp.write(proto.encode(message), options)\n },\n writeV: async (messages, proto, options?: AbortOptions) => {\n // encode, writeLP\n await lp.writeV(messages.map(message => proto.encode(message)), options)\n },\n pb: (proto) => {\n return {\n read: async (options) => W.read(proto, options),\n write: async (d, options) => W.write(d, proto, options),\n writeV: async (d, options) => W.writeV(d, proto, options),\n unwrap: () => W\n }\n },\n unwrap: () => {\n return lp.unwrap()\n }\n }\n\n return W\n}\n","import detectElectron from 'is-electron'\n\nexport const isEnvWithDom = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\nexport const isElectron = detectElectron()\n\n/**\n * Detects browser main thread **NOT** web worker or service worker\n */\nexport const isBrowser = isEnvWithDom && !isElectron\nexport const isElectronMain = isElectron && !isEnvWithDom\nexport const isElectronRenderer = isElectron && isEnvWithDom\nexport const isNode = typeof globalThis.process !== 'undefined' && typeof globalThis.process.release !== 'undefined' && globalThis.process.release.name === 'node' && !isElectron\n// @ts-ignore\n// eslint-disable-next-line no-undef\nexport const isWebWorker = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\n\n// defeat bundlers replacing process.env.NODE_ENV with \"development\" or whatever\nexport const isTest = typeof globalThis.process !== 'undefined' && typeof globalThis.process.env !== 'undefined' && globalThis.process.env['NODE' + (() => '_')() + 'ENV'] === 'test'\nexport const isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n","const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n","import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Identify {\n protocolVersion?: string\n agentVersion?: string\n publicKey?: Uint8Array\n listenAddrs: Uint8Array[]\n observedAddr?: Uint8Array\n protocols: string[]\n signedPeerRecord?: Uint8Array\n}\n\nexport namespace Identify {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.protocolVersion != null) {\n w.uint32(42)\n w.string(obj.protocolVersion)\n }\n\n if (obj.agentVersion != null) {\n w.uint32(50)\n w.string(obj.agentVersion)\n }\n\n if (obj.publicKey != null) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if (obj.listenAddrs != null) {\n for (const value of obj.listenAddrs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (obj.observedAddr != null) {\n w.uint32(34)\n w.bytes(obj.observedAddr)\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(26)\n w.string(value)\n }\n }\n\n if (obj.signedPeerRecord != null) {\n w.uint32(66)\n w.bytes(obj.signedPeerRecord)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n listenAddrs: [],\n protocols: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 5:\n obj.protocolVersion = reader.string()\n break\n case 6:\n obj.agentVersion = reader.string()\n break\n case 1:\n obj.publicKey = reader.bytes()\n break\n case 2:\n obj.listenAddrs.push(reader.bytes())\n break\n case 4:\n obj.observedAddr = reader.bytes()\n break\n case 3:\n obj.protocols.push(reader.string())\n break\n case 8:\n obj.signedPeerRecord = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Identify.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Identify => {\n return decodeMessage(buf, Identify.codec())\n }\n}\n","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n\n this.code = code\n }\n}\n","import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","/* eslint-disable complexity */\n\nimport { CodeError, ERR_NOT_FOUND, setMaxListeners } from '@libp2p/interface'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport { type Multiaddr, multiaddr, protocols } from '@multiformats/multiaddr'\nimport { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\nimport { pbStream } from 'it-protobuf-stream'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'\nimport {\n IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION\n} from './consts.js'\nimport { Identify as IdentifyMessage } from './pb/message.js'\nimport type { Identify as IdentifyInterface, IdentifyComponents, IdentifyInit } from './index.js'\nimport type { Libp2pEvents, IdentifyResult, SignedPeerRecord, AbortOptions, Logger, Connection, Stream, TypedEventTarget, PeerId, Peer, PeerData, PeerStore, Startable } from '@libp2p/interface'\nimport type { AddressManager, ConnectionManager, IncomingStreamData, Registrar } from '@libp2p/interface-internal'\n\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nconst MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8\n\nconst defaultValues = {\n protocolPrefix: 'ipfs',\n // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48\n timeout: 60000,\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n maxPushIncomingStreams: 1,\n maxPushOutgoingStreams: 1,\n maxObservedAddresses: 10,\n maxIdentifyMessageSize: 8192,\n runOnConnectionOpen: true,\n runOnTransientConnection: true\n}\n\nexport class Identify implements Startable, IdentifyInterface {\n private readonly identifyProtocolStr: string\n private readonly identifyPushProtocolStr: string\n public readonly host: {\n protocolVersion: string\n agentVersion: string\n }\n\n private started: boolean\n private readonly timeout: number\n private readonly peerId: PeerId\n private readonly peerStore: PeerStore\n private readonly registrar: Registrar\n private readonly connectionManager: ConnectionManager\n private readonly addressManager: AddressManager\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n private readonly maxPushIncomingStreams: number\n private readonly maxPushOutgoingStreams: number\n private readonly maxIdentifyMessageSize: number\n private readonly maxObservedAddresses: number\n private readonly events: TypedEventTarget\n private readonly runOnTransientConnection: boolean\n private readonly log: Logger\n\n constructor (components: IdentifyComponents, init: IdentifyInit = {}) {\n this.started = false\n this.peerId = components.peerId\n this.peerStore = components.peerStore\n this.registrar = components.registrar\n this.addressManager = components.addressManager\n this.connectionManager = components.connectionManager\n this.events = components.events\n this.log = components.logger.forComponent('libp2p:identify')\n\n this.identifyProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`\n this.identifyPushProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`\n this.timeout = init.timeout ?? defaultValues.timeout\n this.maxInboundStreams = init.maxInboundStreams ?? defaultValues.maxInboundStreams\n this.maxOutboundStreams = init.maxOutboundStreams ?? defaultValues.maxOutboundStreams\n this.maxPushIncomingStreams = init.maxPushIncomingStreams ?? defaultValues.maxPushIncomingStreams\n this.maxPushOutgoingStreams = init.maxPushOutgoingStreams ?? defaultValues.maxPushOutgoingStreams\n this.maxIdentifyMessageSize = init.maxIdentifyMessageSize ?? defaultValues.maxIdentifyMessageSize\n this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses\n this.runOnTransientConnection = init.runOnTransientConnection ?? defaultValues.runOnTransientConnection\n\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix ?? defaultValues.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,\n agentVersion: init.agentVersion ?? `${components.nodeInfo.name}/${components.nodeInfo.version}`\n }\n\n if (init.runOnConnectionOpen ?? defaultValues.runOnConnectionOpen) {\n // When a new connection happens, trigger identify\n components.events.addEventListener('connection:open', (evt) => {\n const connection = evt.detail\n this.identify(connection).catch(err => { this.log.error('error during identify trigged by connection:open', err) })\n })\n }\n\n // When self peer record changes, trigger identify-push\n components.events.addEventListener('self:peer:update', (evt) => {\n void this.push().catch(err => { this.log.error(err) })\n })\n\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (this.host.agentVersion === `${components.nodeInfo.name}/${components.nodeInfo.version}`) {\n if (isNode || isElectronMain) {\n this.host.agentVersion += ` UserAgent=${globalThis.process.version}`\n } else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {\n this.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`\n }\n }\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n async start (): Promise {\n if (this.started) {\n return\n }\n\n await this.peerStore.merge(this.peerId, {\n metadata: {\n AgentVersion: uint8ArrayFromString(this.host.agentVersion),\n ProtocolVersion: uint8ArrayFromString(this.host.protocolVersion)\n }\n })\n\n await this.registrar.handle(this.identifyProtocolStr, (data) => {\n void this._handleIdentify(data).catch(err => {\n this.log.error(err)\n })\n }, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n })\n await this.registrar.handle(this.identifyPushProtocolStr, (data) => {\n void this._handlePush(data).catch(err => {\n this.log.error(err)\n })\n }, {\n maxInboundStreams: this.maxPushIncomingStreams,\n maxOutboundStreams: this.maxPushOutgoingStreams,\n runOnTransientConnection: this.runOnTransientConnection\n })\n\n this.started = true\n }\n\n async stop (): Promise {\n await this.registrar.unhandle(this.identifyProtocolStr)\n await this.registrar.unhandle(this.identifyPushProtocolStr)\n\n this.started = false\n }\n\n /**\n * Send an Identify Push update to the list of connections\n */\n async pushToConnections (connections: Connection[]): Promise {\n const listenAddresses = this.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n const peerRecord = new PeerRecord({\n peerId: this.peerId,\n multiaddrs: listenAddresses\n })\n const signedPeerRecord = await RecordEnvelope.seal(peerRecord, this.peerId)\n const supportedProtocols = this.registrar.getProtocols()\n const peer = await this.peerStore.get(this.peerId)\n const agentVersion = uint8ArrayToString(peer.metadata.get('AgentVersion') ?? uint8ArrayFromString(this.host.agentVersion))\n const protocolVersion = uint8ArrayToString(peer.metadata.get('ProtocolVersion') ?? uint8ArrayFromString(this.host.protocolVersion))\n\n const pushes = connections.map(async connection => {\n let stream: Stream | undefined\n const signal = AbortSignal.timeout(this.timeout)\n\n setMaxListeners(Infinity, signal)\n\n try {\n stream = await connection.newStream(this.identifyPushProtocolStr, {\n signal,\n runOnTransientConnection: this.runOnTransientConnection\n })\n\n const pb = pbStream(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(IdentifyMessage)\n\n await pb.write({\n listenAddrs: listenAddresses.map(ma => ma.bytes),\n signedPeerRecord: signedPeerRecord.marshal(),\n protocols: supportedProtocols,\n agentVersion,\n protocolVersion\n }, {\n signal\n })\n\n await stream.close({\n signal\n })\n } catch (err: any) {\n // Just log errors\n this.log.error('could not push identify update to peer', err)\n stream?.abort(err)\n }\n })\n\n await Promise.all(pushes)\n }\n\n /**\n * Calls `push` on all peer connections\n */\n async push (): Promise {\n // Do not try to push if we are not running\n if (!this.isStarted()) {\n return\n }\n\n const connections: Connection[] = []\n\n await Promise.all(\n this.connectionManager.getConnections().map(async conn => {\n try {\n const peer = await this.peerStore.get(conn.remotePeer)\n\n if (!peer.protocols.includes(this.identifyPushProtocolStr)) {\n return\n }\n\n connections.push(conn)\n } catch (err: any) {\n if (err.code !== ERR_NOT_FOUND) {\n throw err\n }\n }\n })\n )\n\n await this.pushToConnections(connections)\n }\n\n async _identify (connection: Connection, options: AbortOptions = {}): Promise {\n let stream: Stream | undefined\n\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout)\n setMaxListeners(Infinity, signal)\n\n options = {\n ...options,\n signal\n }\n }\n\n try {\n stream = await connection.newStream(this.identifyProtocolStr, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n })\n\n const pb = pbStream(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(IdentifyMessage)\n\n const message = await pb.read(options)\n\n await stream.close(options)\n\n return message\n } catch (err: any) {\n this.log.error('error while reading identify message', err)\n stream?.abort(err)\n throw err\n }\n }\n\n async identify (connection: Connection, options: AbortOptions = {}): Promise {\n const message = await this._identify(connection, options)\n const {\n publicKey,\n protocols,\n observedAddr\n } = message\n\n if (publicKey == null) {\n throw new CodeError('public key was missing from identify message', 'ERR_MISSING_PUBLIC_KEY')\n }\n\n const id = await peerIdFromKeys(publicKey)\n\n if (!connection.remotePeer.equals(id)) {\n throw new CodeError('identified peer does not match the expected peer', 'ERR_INVALID_PEER')\n }\n\n if (this.peerId.equals(id)) {\n throw new CodeError('identified peer is our own peer id?', 'ERR_INVALID_PEER')\n }\n\n // Get the observedAddr if there is one\n const cleanObservedAddr = getCleanMultiaddr(observedAddr)\n\n this.log('identify completed for peer %p and protocols %o', id, protocols)\n this.log('our observed address is %a', cleanObservedAddr)\n\n if (cleanObservedAddr != null &&\n this.addressManager.getObservedAddrs().length < (this.maxObservedAddresses ?? Infinity)) {\n this.log('storing our observed address %a', cleanObservedAddr)\n this.addressManager.addObservedAddr(cleanObservedAddr)\n }\n\n return this.#consumeIdentifyMessage(connection, message)\n }\n\n /**\n * Sends the `Identify` response with the Signed Peer Record\n * to the requesting peer over the given `connection`\n */\n async _handleIdentify (data: IncomingStreamData): Promise {\n const { connection, stream } = data\n\n const signal = AbortSignal.timeout(this.timeout)\n\n setMaxListeners(Infinity, signal)\n\n try {\n const publicKey = this.peerId.publicKey ?? new Uint8Array(0)\n const peerData = await this.peerStore.get(this.peerId)\n const multiaddrs = this.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n let signedPeerRecord = peerData.peerRecordEnvelope\n\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new PeerRecord({\n peerId: this.peerId,\n multiaddrs\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.peerId)\n signedPeerRecord = envelope.marshal().subarray()\n }\n\n let observedAddr: Uint8Array | undefined = connection.remoteAddr.bytes\n\n if (!IP_OR_DOMAIN.matches(connection.remoteAddr)) {\n observedAddr = undefined\n }\n\n const pb = pbStream(stream).pb(IdentifyMessage)\n\n await pb.write({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr,\n protocols: peerData.protocols\n }, {\n signal\n })\n\n await stream.close({\n signal\n })\n } catch (err: any) {\n this.log.error('could not respond to identify request', err)\n stream.abort(err)\n }\n }\n\n /**\n * Reads the Identify Push message from the given `connection`\n */\n async _handlePush (data: IncomingStreamData): Promise {\n const { connection, stream } = data\n\n try {\n if (this.peerId.equals(connection.remotePeer)) {\n throw new Error('received push from ourselves?')\n }\n\n const options = {\n signal: AbortSignal.timeout(this.timeout)\n }\n\n const pb = pbStream(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(IdentifyMessage)\n\n const message = await pb.read(options)\n await stream.close(options)\n\n await this.#consumeIdentifyMessage(connection, message)\n } catch (err: any) {\n this.log.error('received invalid message', err)\n stream.abort(err)\n return\n }\n\n this.log('handled push from %p', connection.remotePeer)\n }\n\n async #consumeIdentifyMessage (connection: Connection, message: IdentifyMessage): Promise {\n this.log('received identify from %p', connection.remotePeer)\n\n if (message == null) {\n throw new CodeError('message was null or undefined', 'ERR_INVALID_MESSAGE')\n }\n\n const peer: PeerData = {}\n\n if (message.listenAddrs.length > 0) {\n peer.addresses = message.listenAddrs.map(buf => ({\n isCertified: false,\n multiaddr: multiaddr(buf)\n }))\n }\n\n if (message.protocols.length > 0) {\n peer.protocols = message.protocols\n }\n\n if (message.publicKey != null) {\n peer.publicKey = message.publicKey\n\n const peerId = await peerIdFromKeys(message.publicKey)\n\n if (!peerId.equals(connection.remotePeer)) {\n throw new CodeError('public key did not match remote PeerId', 'ERR_INVALID_PUBLIC_KEY')\n }\n }\n\n let output: SignedPeerRecord | undefined\n\n // if the peer record has been sent, prefer the addresses in the record as they are signed by the remote peer\n if (message.signedPeerRecord != null) {\n this.log('received signedPeerRecord from %p', connection.remotePeer)\n\n let peerRecordEnvelope = message.signedPeerRecord\n const envelope = await RecordEnvelope.openAndCertify(peerRecordEnvelope, PeerRecord.DOMAIN)\n let peerRecord = PeerRecord.createFromProtobuf(envelope.payload)\n\n // Verify peerId\n if (!peerRecord.peerId.equals(envelope.peerId)) {\n throw new CodeError('signing key does not match PeerId in the PeerRecord', 'ERR_INVALID_SIGNING_KEY')\n }\n\n // Make sure remote peer is the one sending the record\n if (!connection.remotePeer.equals(peerRecord.peerId)) {\n throw new CodeError('signing key does not match remote PeerId', 'ERR_INVALID_PEER_RECORD_KEY')\n }\n\n let existingPeer: Peer | undefined\n\n try {\n existingPeer = await this.peerStore.get(peerRecord.peerId)\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n if (existingPeer != null) {\n // don't lose any existing metadata\n peer.metadata = existingPeer.metadata\n\n // if we have previously received a signed record for this peer, compare it to the incoming one\n if (existingPeer.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(existingPeer.peerRecordEnvelope)\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload)\n\n // ensure seq is greater than, or equal to, the last received\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber)\n peerRecord = storedRecord\n peerRecordEnvelope = existingPeer.peerRecordEnvelope\n }\n }\n }\n\n // store the signed record for next time\n peer.peerRecordEnvelope = peerRecordEnvelope\n\n // override the stored addresses with the signed multiaddrs\n peer.addresses = peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }))\n\n output = {\n seq: peerRecord.seqNumber,\n addresses: peerRecord.multiaddrs\n }\n } else {\n this.log('%p did not send a signed peer record', connection.remotePeer)\n }\n\n this.log('patching %p with', connection.remotePeer, peer)\n await this.peerStore.patch(connection.remotePeer, peer)\n\n if (message.agentVersion != null || message.protocolVersion != null) {\n const metadata: Record = {}\n\n if (message.agentVersion != null) {\n metadata.AgentVersion = uint8ArrayFromString(message.agentVersion)\n }\n\n if (message.protocolVersion != null) {\n metadata.ProtocolVersion = uint8ArrayFromString(message.protocolVersion)\n }\n\n this.log('merging %p metadata', connection.remotePeer, metadata)\n await this.peerStore.merge(connection.remotePeer, {\n metadata\n })\n }\n\n const result: IdentifyResult = {\n peerId: connection.remotePeer,\n protocolVersion: message.protocolVersion,\n agentVersion: message.agentVersion,\n publicKey: message.publicKey,\n listenAddrs: message.listenAddrs.map(buf => multiaddr(buf)),\n observedAddr: message.observedAddr == null ? undefined : multiaddr(message.observedAddr),\n protocols: message.protocols,\n signedPeerRecord: output,\n connection\n }\n\n this.events.safeDispatchEvent('peer:identify', { detail: result })\n\n return result\n }\n}\n\n/**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\nfunction getCleanMultiaddr (addr: Uint8Array | string | null | undefined): Multiaddr | undefined {\n if (addr != null && addr.length > 0) {\n try {\n return multiaddr(addr)\n } catch {\n\n }\n }\n}\n","/**\n * @packageDocumentation\n *\n * Use the `identify` function to add support for the [Identify protocol](https://github.com/libp2p/specs/blob/master/identify/README.md) to libp2p.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * identify: identify()\n * }\n * })\n * ```\n */\n\nimport {\n MULTICODEC_IDENTIFY,\n MULTICODEC_IDENTIFY_PUSH\n} from './consts.js'\nimport { Identify as IdentifyClass } from './identify.js'\nimport type { AbortOptions, IdentifyResult, Libp2pEvents, ComponentLogger, NodeInfo, TypedEventTarget, PeerId, PeerStore, Connection } from '@libp2p/interface'\nimport type { AddressManager, ConnectionManager, Registrar } from '@libp2p/interface-internal'\n\nexport interface IdentifyInit {\n /**\n * The prefix to use for the protocol (default: 'ipfs')\n */\n protocolPrefix?: string\n\n /**\n * What details we should send as part of an identify message\n */\n agentVersion?: string\n\n /**\n * How long we should wait for a remote peer to send their identify response\n */\n timeout?: number\n\n /**\n * Identify responses larger than this in bytes will be rejected (default: 8192)\n */\n maxIdentifyMessageSize?: number\n\n maxInboundStreams?: number\n maxOutboundStreams?: number\n\n maxPushIncomingStreams?: number\n maxPushOutgoingStreams?: number\n maxObservedAddresses?: number\n\n /**\n * Whether to automatically dial identify on newly opened connections (default: true)\n */\n runOnConnectionOpen?: boolean\n\n /**\n * Whether to run on connections with data or duration limits (default: true)\n */\n runOnTransientConnection?: boolean\n}\n\nexport interface IdentifyComponents {\n peerId: PeerId\n peerStore: PeerStore\n connectionManager: ConnectionManager\n registrar: Registrar\n addressManager: AddressManager\n events: TypedEventTarget\n logger: ComponentLogger\n nodeInfo: NodeInfo\n}\n\n/**\n * The protocols the Identify service supports\n */\nexport const multicodecs = {\n IDENTIFY: MULTICODEC_IDENTIFY,\n IDENTIFY_PUSH: MULTICODEC_IDENTIFY_PUSH\n}\n\nexport interface Identify {\n /**\n * due to the default limits on inbound/outbound streams for this protocol,\n * invoking this method when runOnConnectionOpen is true can lead to unpredictable results\n * as streams may be closed by the local or the remote node.\n * Please use with caution. If you find yourself needing to call this method to discover other peers that support your protocol,\n * you may be better off configuring a topology to be notified instead.\n */\n identify(connection: Connection, options?: AbortOptions): Promise\n\n push(): Promise\n}\n\nexport function identify (init: IdentifyInit = {}): (components: IdentifyComponents) => Identify {\n return (components) => new IdentifyClass(components, init)\n}\n","import { getIterator } from 'get-iterator'\nimport { isPromise } from './is-promise.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { Source } from 'it-stream-types'\n\nexport function closeSource (source: Source, log: Logger): void {\n const res = getIterator(source).return?.()\n\n if (isPromise(res)) {\n res.catch(err => {\n log.error('could not cause iterator to return', err)\n })\n }\n}\n","\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator (obj: AsyncIterable): AsyncIterator\nexport function getIterator (obj: AsyncIterator): AsyncIterator\nexport function getIterator (obj: Iterable): Iterator\nexport function getIterator (obj: Iterator): Iterator\nexport function getIterator (obj: any): AsyncIterator | Iterator \nexport function getIterator (obj: any): AsyncIterator | Iterator {\n if (obj != null) {\n if (typeof obj[Symbol.iterator] === 'function') {\n return obj[Symbol.iterator]()\n }\n if (typeof obj[Symbol.asyncIterator] === 'function') {\n return obj[Symbol.asyncIterator]()\n }\n if (typeof obj.next === 'function') {\n return obj // probably an iterator\n }\n }\n throw new Error('argument is not an iterator or iterable')\n}\n","export function isPromise (thing: any): thing is Promise {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n","// From https://github.com/sindresorhus/random-int/blob/c37741b56f76b9160b0b63dae4e9c64875128146/index.js#L13-L15\nconst randomInteger = (minimum, maximum) => Math.floor((Math.random() * (maximum - minimum + 1)) + minimum);\n\nconst createAbortError = () => {\n\tconst error = new Error('Delay aborted');\n\terror.name = 'AbortError';\n\treturn error;\n};\n\nconst clearMethods = new WeakMap();\n\nexport function createDelay({clearTimeout: defaultClear, setTimeout: defaultSet} = {}) {\n\t// We cannot use `async` here as we need the promise identity.\n\treturn (milliseconds, {value, signal} = {}) => {\n\t\t// TODO: Use `signal?.throwIfAborted()` when targeting Node.js 18.\n\t\tif (signal?.aborted) {\n\t\t\treturn Promise.reject(createAbortError());\n\t\t}\n\n\t\tlet timeoutId;\n\t\tlet settle;\n\t\tlet rejectFunction;\n\t\tconst clear = defaultClear ?? clearTimeout;\n\n\t\tconst signalListener = () => {\n\t\t\tclear(timeoutId);\n\t\t\trejectFunction(createAbortError());\n\t\t};\n\n\t\tconst cleanup = () => {\n\t\t\tif (signal) {\n\t\t\t\tsignal.removeEventListener('abort', signalListener);\n\t\t\t}\n\t\t};\n\n\t\tconst delayPromise = new Promise((resolve, reject) => {\n\t\t\tsettle = () => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t};\n\n\t\t\trejectFunction = reject;\n\t\t\ttimeoutId = (defaultSet ?? setTimeout)(settle, milliseconds);\n\t\t});\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', signalListener, {once: true});\n\t\t}\n\n\t\tclearMethods.set(delayPromise, () => {\n\t\t\tclear(timeoutId);\n\t\t\ttimeoutId = null;\n\t\t\tsettle();\n\t\t});\n\n\t\treturn delayPromise;\n\t};\n}\n\nconst delay = createDelay();\n\nexport default delay;\n\nexport async function rangeDelay(minimum, maximum, options = {}) {\n\treturn delay(randomInteger(minimum, maximum), options);\n}\n\nexport function clearDelay(promise) {\n\tclearMethods.get(promise)?.();\n}\n","import { CodeError } from '@libp2p/interface'\nimport delay from 'delay'\n\nexport interface RateLimiterInit {\n /**\n * Number of points\n *\n * @default 4\n */\n points?: number\n\n /**\n * Per seconds\n *\n * @default 1\n */\n duration?: number\n\n /**\n * Block if consumed more than points in current duration for blockDuration seconds\n *\n * @default 0\n */\n blockDuration?: number\n\n /**\n * Execute allowed actions evenly over duration\n *\n * @default false\n */\n execEvenly?: boolean\n\n /**\n * ms, works with execEvenly=true option\n *\n * @default duration * 1000 / points\n */\n execEvenlyMinDelayMs?: number\n\n /**\n * @default rlflx\n */\n keyPrefix?: string\n}\n\nexport interface GetKeySecDurationOptions {\n customDuration?: number\n}\n\nexport interface RateLimiterResult {\n remainingPoints: number\n msBeforeNext: number\n consumedPoints: number\n isFirstInDuration: boolean\n}\n\nexport interface RateRecord {\n value: number\n expiresAt?: Date\n timeoutId?: ReturnType\n}\n\nexport class RateLimiter {\n public readonly memoryStorage: MemoryStorage\n protected points: number\n protected duration: number\n protected blockDuration: number\n protected execEvenly: boolean\n protected execEvenlyMinDelayMs: number\n protected keyPrefix: string\n\n constructor (opts: RateLimiterInit = {}) {\n this.points = opts.points ?? 4\n this.duration = opts.duration ?? 1\n this.blockDuration = opts.blockDuration ?? 0\n this.execEvenly = opts.execEvenly ?? false\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs ?? (this.duration * 1000 / this.points)\n this.keyPrefix = opts.keyPrefix ?? 'rlflx'\n this.memoryStorage = new MemoryStorage()\n }\n\n async consume (key: string, pointsToConsume: number = 1, options: GetKeySecDurationOptions = {}): Promise {\n const rlKey = this.getKey(key)\n const secDuration = this._getKeySecDuration(options)\n let res = this.memoryStorage.incrby(rlKey, pointsToConsume, secDuration)\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0)\n\n if (res.consumedPoints > this.points) {\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + pointsToConsume)) {\n // Block key\n res = this.memoryStorage.set(rlKey, res.consumedPoints, this.blockDuration)\n }\n\n throw new CodeError('Rate limit exceeded', 'ERR_RATE_LIMIT_EXCEEDED', res)\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delayMs = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2))\n if (delayMs < this.execEvenlyMinDelayMs) {\n delayMs = res.consumedPoints * this.execEvenlyMinDelayMs\n }\n\n await delay(delayMs)\n }\n\n return res\n }\n\n penalty (key: string, points: number = 1, options: GetKeySecDurationOptions = {}): RateLimiterResult {\n const rlKey = this.getKey(key)\n const secDuration = this._getKeySecDuration(options)\n const res = this.memoryStorage.incrby(rlKey, points, secDuration)\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0)\n\n return res\n }\n\n reward (key: string, points: number = 1, options: GetKeySecDurationOptions = {}): RateLimiterResult {\n const rlKey = this.getKey(key)\n const secDuration = this._getKeySecDuration(options)\n const res = this.memoryStorage.incrby(rlKey, -points, secDuration)\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0)\n\n return res\n }\n\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n */\n block (key: string, secDuration: number): RateLimiterResult {\n const msDuration = secDuration * 1000\n const initPoints = this.points + 1\n\n this.memoryStorage.set(this.getKey(key), initPoints, secDuration)\n\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: initPoints,\n isFirstInDuration: false\n }\n }\n\n set (key: string, points: number, secDuration: number = 0): RateLimiterResult {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000\n\n this.memoryStorage.set(this.getKey(key), points, secDuration)\n\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: points,\n isFirstInDuration: false\n }\n }\n\n get (key: string): RateLimiterResult | undefined {\n const res = this.memoryStorage.get(this.getKey(key))\n\n if (res != null) {\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0)\n }\n\n return res\n }\n\n delete (key: string): void {\n this.memoryStorage.delete(this.getKey(key))\n }\n\n private _getKeySecDuration (options?: GetKeySecDurationOptions): number {\n if (options?.customDuration != null && options.customDuration >= 0) {\n return options.customDuration\n }\n\n return this.duration\n }\n\n getKey (key: string): string {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key\n }\n\n parseKey (rlKey: string): string {\n return rlKey.substring(this.keyPrefix.length)\n }\n}\n\nclass MemoryStorage {\n public readonly storage: Map\n\n constructor () {\n this.storage = new Map()\n }\n\n incrby (key: string, value: number, durationSec: number): RateLimiterResult {\n const existing = this.storage.get(key)\n\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1\n\n if (existing.expiresAt == null || msBeforeExpires > 0) {\n // Change value\n existing.value += value\n\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n }\n }\n\n return this.set(key, value, durationSec)\n }\n\n return this.set(key, value, durationSec)\n }\n\n set (key: string, value: number, durationSec: number): RateLimiterResult {\n const durationMs = durationSec * 1000\n const existing = this.storage.get(key)\n\n if (existing != null) {\n clearTimeout(existing.timeoutId)\n }\n\n const record: RateRecord = {\n value,\n expiresAt: durationMs > 0 ? new Date(Date.now() + durationMs) : undefined\n }\n\n this.storage.set(key, record)\n\n if (durationMs > 0) {\n record.timeoutId = setTimeout(() => {\n this.storage.delete(key)\n }, durationMs)\n\n if (record.timeoutId.unref != null) {\n record.timeoutId.unref()\n }\n }\n\n return {\n remainingPoints: 0,\n msBeforeNext: durationMs === 0 ? -1 : durationMs,\n consumedPoints: record.value,\n isFirstInDuration: true\n }\n }\n\n get (key: string): RateLimiterResult | undefined {\n const existing = this.storage.get(key)\n\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n }\n }\n }\n\n delete (key: string): boolean {\n const record = this.storage.get(key)\n\n if (record != null) {\n if (record.timeoutId != null) {\n clearTimeout(record.timeoutId)\n }\n\n this.storage.delete(key)\n\n return true\n }\n return false\n }\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\ntype INITIATOR_NAME = 'NEW_STREAM' | 'MESSAGE' | 'CLOSE' | 'RESET'\ntype RECEIVER_NAME = 'MESSAGE' | 'CLOSE' | 'RESET'\ntype NAME = 'NEW_STREAM' | 'MESSAGE_INITIATOR' | 'CLOSE_INITIATOR' | 'RESET_INITIATOR' | 'MESSAGE_RECEIVER' | 'CLOSE_RECEIVER' | 'RESET_RECEIVER'\ntype CODE = 0 | 1 | 2 | 3 | 4 | 5 | 6\n\nexport enum MessageTypes {\n NEW_STREAM = 0,\n MESSAGE_RECEIVER = 1,\n MESSAGE_INITIATOR = 2,\n CLOSE_RECEIVER = 3,\n CLOSE_INITIATOR = 4,\n RESET_RECEIVER = 5,\n RESET_INITIATOR = 6\n}\n\nexport const MessageTypeNames: Record = Object.freeze({\n 0: 'NEW_STREAM',\n 1: 'MESSAGE_RECEIVER',\n 2: 'MESSAGE_INITIATOR',\n 3: 'CLOSE_RECEIVER',\n 4: 'CLOSE_INITIATOR',\n 5: 'RESET_RECEIVER',\n 6: 'RESET_INITIATOR'\n})\n\nexport const InitiatorMessageTypes: Record = Object.freeze({\n NEW_STREAM: MessageTypes.NEW_STREAM,\n MESSAGE: MessageTypes.MESSAGE_INITIATOR,\n CLOSE: MessageTypes.CLOSE_INITIATOR,\n RESET: MessageTypes.RESET_INITIATOR\n})\n\nexport const ReceiverMessageTypes: Record = Object.freeze({\n MESSAGE: MessageTypes.MESSAGE_RECEIVER,\n CLOSE: MessageTypes.CLOSE_RECEIVER,\n RESET: MessageTypes.RESET_RECEIVER\n})\n\nexport interface NewStreamMessage {\n id: number\n type: MessageTypes.NEW_STREAM\n data: Uint8ArrayList\n}\n\nexport interface MessageReceiverMessage {\n id: number\n type: MessageTypes.MESSAGE_RECEIVER\n data: Uint8ArrayList\n}\n\nexport interface MessageInitiatorMessage {\n id: number\n type: MessageTypes.MESSAGE_INITIATOR\n data: Uint8ArrayList\n}\n\nexport interface CloseReceiverMessage {\n id: number\n type: MessageTypes.CLOSE_RECEIVER\n}\n\nexport interface CloseInitiatorMessage {\n id: number\n type: MessageTypes.CLOSE_INITIATOR\n}\n\nexport interface ResetReceiverMessage {\n id: number\n type: MessageTypes.RESET_RECEIVER\n}\n\nexport interface ResetInitiatorMessage {\n id: number\n type: MessageTypes.RESET_INITIATOR\n}\n\nexport type Message = NewStreamMessage | MessageReceiverMessage | MessageInitiatorMessage | CloseReceiverMessage | CloseInitiatorMessage | ResetReceiverMessage | ResetInitiatorMessage\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { MessageTypeNames, MessageTypes } from './message-types.js'\nimport type { Message } from './message-types.js'\n\nexport const MAX_MSG_SIZE = 1 << 20 // 1MB\nexport const MAX_MSG_QUEUE_SIZE = 4 << 20 // 4MB\n\ninterface MessageHeader {\n id: number\n type: keyof typeof MessageTypeNames\n offset: number\n length: number\n}\n\nexport class Decoder {\n private readonly _buffer: Uint8ArrayList\n private _headerInfo: MessageHeader | null\n private readonly _maxMessageSize: number\n private readonly _maxUnprocessedMessageQueueSize: number\n\n constructor (maxMessageSize: number = MAX_MSG_SIZE, maxUnprocessedMessageQueueSize: number = MAX_MSG_QUEUE_SIZE) {\n this._buffer = new Uint8ArrayList()\n this._headerInfo = null\n this._maxMessageSize = maxMessageSize\n this._maxUnprocessedMessageQueueSize = maxUnprocessedMessageQueueSize\n }\n\n write (chunk: Uint8Array | Uint8ArrayList): Message[] {\n if (chunk == null || chunk.length === 0) {\n return []\n }\n\n this._buffer.append(chunk)\n\n if (this._buffer.byteLength > this._maxUnprocessedMessageQueueSize) {\n throw Object.assign(new Error('unprocessed message queue size too large!'), { code: 'ERR_MSG_QUEUE_TOO_BIG' })\n }\n\n const msgs: Message[] = []\n\n while (this._buffer.length !== 0) {\n if (this._headerInfo == null) {\n try {\n this._headerInfo = this._decodeHeader(this._buffer)\n } catch (err: any) {\n if (err.code === 'ERR_MSG_TOO_BIG') {\n throw err\n }\n\n break // We haven't received enough data yet\n }\n }\n\n const { id, type, length, offset } = this._headerInfo\n const bufferedDataLength = this._buffer.length - offset\n\n if (bufferedDataLength < length) {\n break // not enough data yet\n }\n\n const msg: any = {\n id,\n type\n }\n\n if (type === MessageTypes.NEW_STREAM || type === MessageTypes.MESSAGE_INITIATOR || type === MessageTypes.MESSAGE_RECEIVER) {\n msg.data = this._buffer.sublist(offset, offset + length)\n }\n\n msgs.push(msg)\n\n this._buffer.consume(offset + length)\n this._headerInfo = null\n }\n\n return msgs\n }\n\n /**\n * Attempts to decode the message header from the buffer\n */\n _decodeHeader (data: Uint8ArrayList): MessageHeader {\n const {\n value: h,\n offset\n } = readVarInt(data)\n const {\n value: length,\n offset: end\n } = readVarInt(data, offset)\n\n const type = h & 7\n\n // @ts-expect-error h is a number not a CODE\n if (MessageTypeNames[type] == null) {\n throw new Error(`Invalid type received: ${type}`)\n }\n\n // test message type varint + data length\n if (length > this._maxMessageSize) {\n throw Object.assign(new Error('message size too large!'), { code: 'ERR_MSG_TOO_BIG' })\n }\n\n // @ts-expect-error h is a number not a CODE\n return { id: h >> 3, type, offset: offset + end, length }\n }\n}\n\nconst MSB = 0x80\nconst REST = 0x7F\n\nexport interface ReadVarIntResult {\n value: number\n offset: number\n}\n\nfunction readVarInt (buf: Uint8ArrayList, offset: number = 0): ReadVarIntResult {\n let res = 0\n let shift = 0\n let counter = offset\n let b: number\n const l = buf.length\n\n do {\n if (counter >= l || shift > 49) {\n offset = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf.get(counter++)\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n offset = counter - offset\n\n return {\n value: res,\n offset\n }\n}\n","import * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { type Message, MessageTypes } from './message-types.js'\nimport type { Source } from 'it-stream-types'\n\nconst POOL_SIZE = 10 * 1024\n\nclass Encoder {\n private _pool: Uint8Array\n private _poolOffset: number\n\n constructor () {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n }\n\n /**\n * Encodes the given message and adds it to the passed list\n */\n write (msg: Message, list: Uint8ArrayList): void {\n const pool = this._pool\n let offset = this._poolOffset\n\n varint.encode(msg.id << 3 | msg.type, pool, offset)\n offset += varint.encodingLength(msg.id << 3 | msg.type)\n\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n varint.encode(msg.data.length, pool, offset)\n offset += varint.encodingLength(msg.data.length)\n } else {\n varint.encode(0, pool, offset)\n offset += varint.encodingLength(0)\n }\n\n const header = pool.subarray(this._poolOffset, offset)\n\n if (POOL_SIZE - offset < 100) {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n } else {\n this._poolOffset = offset\n }\n\n list.append(header)\n\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n list.append(msg.data)\n }\n }\n}\n\nconst encoder = new Encoder()\n\n/**\n * Encode and yield one or more messages\n */\nexport async function * encode (source: Source): AsyncGenerator {\n for await (const message of source) {\n const list = new Uint8ArrayList()\n encoder.write(message, list)\n yield list\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { type Pushable, pushable } from 'it-pushable'\nimport defer, { type DeferredPromise } from 'p-defer'\nimport pDefer from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { closeSource } from './close-source.js'\nimport type { AbortOptions, Direction, ReadStatus, Stream, StreamStatus, StreamTimeline, WriteStatus } from '@libp2p/interface'\nimport type { Logger } from '@libp2p/logger'\nimport type { Source } from 'it-stream-types'\n\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET'\nconst ERR_SINK_INVALID_STATE = 'ERR_SINK_INVALID_STATE'\nconst DEFAULT_SEND_CLOSE_WRITE_TIMEOUT = 5000\n\nexport interface AbstractStreamInit {\n /**\n * A unique identifier for this stream\n */\n id: string\n\n /**\n * The stream direction\n */\n direction: Direction\n\n /**\n * A Logger implementation used to log stream-specific information\n */\n log: Logger\n\n /**\n * User specific stream metadata\n */\n metadata?: Record\n\n /**\n * Invoked when the stream ends\n */\n onEnd?(err?: Error | undefined): void\n\n /**\n * Invoked when the readable end of the stream is closed\n */\n onCloseRead?(): void\n\n /**\n * Invoked when the writable end of the stream is closed\n */\n onCloseWrite?(): void\n\n /**\n * Invoked when the stream has been reset by the remote\n */\n onReset?(): void\n\n /**\n * Invoked when the stream has errored\n */\n onAbort?(err: Error): void\n\n /**\n * How long to wait in ms for stream data to be written to the underlying\n * connection when closing the writable end of the stream. (default: 500)\n */\n closeTimeout?: number\n\n /**\n * After the stream sink has closed, a limit on how long it takes to send\n * a close-write message to the remote peer.\n */\n sendCloseWriteTimeout?: number\n}\n\nfunction isPromise (thing: any): thing is Promise {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n\nexport abstract class AbstractStream implements Stream {\n public id: string\n public direction: Direction\n public timeline: StreamTimeline\n public protocol?: string\n public metadata: Record\n public source: AsyncGenerator\n public status: StreamStatus\n public readStatus: ReadStatus\n public writeStatus: WriteStatus\n public readonly log: Logger\n\n private readonly sinkController: AbortController\n private readonly sinkEnd: DeferredPromise\n private readonly closed: DeferredPromise\n private endErr: Error | undefined\n private readonly streamSource: Pushable\n private readonly onEnd?: (err?: Error | undefined) => void\n private readonly onCloseRead?: () => void\n private readonly onCloseWrite?: () => void\n private readonly onReset?: () => void\n private readonly onAbort?: (err: Error) => void\n private readonly sendCloseWriteTimeout: number\n private sendingData?: DeferredPromise\n\n constructor (init: AbstractStreamInit) {\n this.sinkController = new AbortController()\n this.sinkEnd = defer()\n this.closed = defer()\n this.log = init.log\n\n // stream status\n this.status = 'open'\n this.readStatus = 'ready'\n this.writeStatus = 'ready'\n\n this.id = init.id\n this.metadata = init.metadata ?? {}\n this.direction = init.direction\n this.timeline = {\n open: Date.now()\n }\n this.sendCloseWriteTimeout = init.sendCloseWriteTimeout ?? DEFAULT_SEND_CLOSE_WRITE_TIMEOUT\n\n this.onEnd = init.onEnd\n this.onCloseRead = init?.onCloseRead\n this.onCloseWrite = init?.onCloseWrite\n this.onReset = init?.onReset\n this.onAbort = init?.onAbort\n\n this.source = this.streamSource = pushable({\n onEnd: (err) => {\n if (err != null) {\n this.log.trace('source ended with error', err)\n } else {\n this.log.trace('source ended')\n }\n\n this.onSourceEnd(err)\n }\n })\n\n // necessary because the libp2p upgrader wraps the sink function\n this.sink = this.sink.bind(this)\n }\n\n async sink (source: Source): Promise {\n if (this.writeStatus !== 'ready') {\n throw new CodeError(`writable end state is \"${this.writeStatus}\" not \"ready\"`, ERR_SINK_INVALID_STATE)\n }\n\n try {\n this.writeStatus = 'writing'\n\n const options: AbortOptions = {\n signal: this.sinkController.signal\n }\n\n if (this.direction === 'outbound') { // If initiator, open a new stream\n const res = this.sendNewStream(options)\n\n if (isPromise(res)) {\n await res\n }\n }\n\n const abortListener = (): void => {\n closeSource(source, this.log)\n }\n\n try {\n this.sinkController.signal.addEventListener('abort', abortListener)\n\n this.log.trace('sink reading from source')\n\n for await (let data of source) {\n data = data instanceof Uint8Array ? new Uint8ArrayList(data) : data\n\n const res = this.sendData(data, options)\n\n if (isPromise(res)) {\n this.sendingData = pDefer()\n await res\n this.sendingData.resolve()\n this.sendingData = undefined\n }\n }\n } finally {\n this.sinkController.signal.removeEventListener('abort', abortListener)\n }\n\n this.log.trace('sink finished reading from source, write status is \"%s\"', this.writeStatus)\n\n if (this.writeStatus === 'writing') {\n this.writeStatus = 'closing'\n\n this.log.trace('send close write to remote')\n await this.sendCloseWrite({\n signal: AbortSignal.timeout(this.sendCloseWriteTimeout)\n })\n\n this.writeStatus = 'closed'\n }\n\n this.onSinkEnd()\n } catch (err: any) {\n this.log.trace('sink ended with error, calling abort with error', err)\n this.abort(err)\n\n throw err\n } finally {\n this.log.trace('resolve sink end')\n this.sinkEnd.resolve()\n }\n }\n\n protected onSourceEnd (err?: Error): void {\n if (this.timeline.closeRead != null) {\n return\n }\n\n this.timeline.closeRead = Date.now()\n this.readStatus = 'closed'\n\n if (err != null && this.endErr == null) {\n this.endErr = err\n }\n\n this.onCloseRead?.()\n\n if (this.timeline.closeWrite != null) {\n this.log.trace('source and sink ended')\n this.timeline.close = Date.now()\n\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed'\n }\n\n if (this.onEnd != null) {\n this.onEnd(this.endErr)\n }\n\n this.closed.resolve()\n } else {\n this.log.trace('source ended, waiting for sink to end')\n }\n }\n\n protected onSinkEnd (err?: Error): void {\n if (this.timeline.closeWrite != null) {\n return\n }\n\n this.timeline.closeWrite = Date.now()\n this.writeStatus = 'closed'\n\n if (err != null && this.endErr == null) {\n this.endErr = err\n }\n\n this.onCloseWrite?.()\n\n if (this.timeline.closeRead != null) {\n this.log.trace('sink and source ended')\n this.timeline.close = Date.now()\n\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed'\n }\n\n if (this.onEnd != null) {\n this.onEnd(this.endErr)\n }\n\n this.closed.resolve()\n } else {\n this.log.trace('sink ended, waiting for source to end')\n }\n }\n\n // Close for both Reading and Writing\n async close (options?: AbortOptions): Promise {\n this.log.trace('closing gracefully')\n\n this.status = 'closing'\n\n // wait for read and write ends to close\n await raceSignal(Promise.all([\n this.closeWrite(options),\n this.closeRead(options),\n this.closed.promise\n ]), options?.signal)\n\n this.status = 'closed'\n\n this.log.trace('closed gracefully')\n }\n\n async closeRead (options: AbortOptions = {}): Promise {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n return\n }\n\n this.log.trace('closing readable end of stream with starting read status \"%s\"', this.readStatus)\n\n const readStatus = this.readStatus\n this.readStatus = 'closing'\n\n if (this.status !== 'reset' && this.status !== 'aborted' && this.timeline.closeRead == null) {\n this.log.trace('send close read to remote')\n await this.sendCloseRead(options)\n }\n\n if (readStatus === 'ready') {\n this.log.trace('ending internal source queue with %d queued bytes', this.streamSource.readableLength)\n this.streamSource.end()\n }\n\n this.log.trace('closed readable end of stream')\n }\n\n async closeWrite (options: AbortOptions = {}): Promise {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n return\n }\n\n this.log.trace('closing writable end of stream with starting write status \"%s\"', this.writeStatus)\n\n if (this.writeStatus === 'ready') {\n this.log.trace('sink was never sunk, sink an empty array')\n\n await raceSignal(this.sink([]), options.signal)\n }\n\n if (this.writeStatus === 'writing') {\n // try to let sending outgoing data succeed\n if (this.sendingData != null) {\n await raceSignal(this.sendingData.promise, options.signal)\n }\n\n // stop reading from the source passed to `.sink`\n this.log.trace('aborting source passed to .sink')\n this.sinkController.abort()\n await raceSignal(this.sinkEnd.promise, options.signal)\n }\n\n this.writeStatus = 'closed'\n\n this.log.trace('closed writable end of stream')\n }\n\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort (err: Error): void {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return\n }\n\n this.log('abort with error', err)\n\n // try to send a reset message\n this.log('try to send reset to remote')\n const res = this.sendReset()\n\n if (isPromise(res)) {\n res.catch((err) => {\n this.log.error('error sending reset message', err)\n })\n }\n\n this.status = 'aborted'\n this.timeline.abort = Date.now()\n this._closeSinkAndSource(err)\n this.onAbort?.(err)\n }\n\n /**\n * Receive a reset message - close immediately for reading and writing (remote\n * error)\n */\n reset (): void {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return\n }\n\n const err = new CodeError('stream reset', ERR_STREAM_RESET)\n\n this.status = 'reset'\n this.timeline.reset = Date.now()\n this._closeSinkAndSource(err)\n this.onReset?.()\n }\n\n _closeSinkAndSource (err?: Error): void {\n this._closeSink(err)\n this._closeSource(err)\n }\n\n _closeSink (err?: Error): void {\n // if the sink function is running, cause it to end\n if (this.writeStatus === 'writing') {\n this.log.trace('end sink source')\n this.sinkController.abort()\n }\n\n this.onSinkEnd(err)\n }\n\n _closeSource (err?: Error): void {\n // if the source is not ending, end it\n if (this.readStatus !== 'closing' && this.readStatus !== 'closed') {\n this.log.trace('ending source with %d bytes to be read by consumer', this.streamSource.readableLength)\n this.readStatus = 'closing'\n this.streamSource.end(err)\n }\n }\n\n /**\n * The remote closed for writing so we should expect to receive no more\n * messages\n */\n remoteCloseWrite (): void {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('received remote close write but local source is already closed')\n return\n }\n\n this.log.trace('remote close write')\n this._closeSource()\n }\n\n /**\n * The remote closed for reading so we should not send any more\n * messages\n */\n remoteCloseRead (): void {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n this.log('received remote close read but local sink is already closed')\n return\n }\n\n this.log.trace('remote close read')\n this._closeSink()\n }\n\n /**\n * The underlying muxer has closed, no more messages can be sent or will\n * be received, close immediately to free up resources\n */\n destroy (): void {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n this.log('received destroy but we are already closed')\n return\n }\n\n this.log.trace('stream destroyed')\n\n this._closeSinkAndSource()\n }\n\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n sourcePush (data: Uint8ArrayList): void {\n this.streamSource.push(data)\n }\n\n /**\n * Returns the amount of unread data - can be used to prevent large amounts of\n * data building up when the stream consumer is too slow.\n */\n sourceReadableLength (): number {\n return this.streamSource.readableLength\n }\n\n /**\n * Send a message to the remote muxer informing them a new stream is being\n * opened\n */\n abstract sendNewStream (options?: AbortOptions): void | Promise\n\n /**\n * Send a data message to the remote muxer\n */\n abstract sendData (buf: Uint8ArrayList, options?: AbortOptions): void | Promise\n\n /**\n * Send a reset message to the remote muxer\n */\n abstract sendReset (options?: AbortOptions): void | Promise\n\n /**\n * Send a message to the remote muxer, informing them no more data messages\n * will be sent by this end of the stream\n */\n abstract sendCloseWrite (options?: AbortOptions): void | Promise\n\n /**\n * Send a message to the remote muxer, informing them no more data messages\n * will be read by this end of the stream\n */\n abstract sendCloseRead (options?: AbortOptions): void | Promise\n}\n","import { AbstractStream, type AbstractStreamInit } from '@libp2p/utils/abstract-stream'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { MAX_MSG_SIZE } from './decode.js'\nimport { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js'\nimport type { Message } from './message-types.js'\nimport type { ComponentLogger } from '@libp2p/interface'\n\nexport interface Options {\n id: number\n send(msg: Message): Promise\n name?: string\n onEnd?(err?: Error): void\n type?: 'initiator' | 'receiver'\n maxMsgSize?: number\n logger: ComponentLogger\n}\n\ninterface MplexStreamInit extends AbstractStreamInit {\n streamId: number\n name: string\n send(msg: Message): Promise\n\n /**\n * The maximum allowable data size, any data larger than this will be\n * chunked and sent in multiple data messages\n */\n maxDataSize: number\n}\n\nexport class MplexStream extends AbstractStream {\n private readonly name: string\n private readonly streamId: number\n private readonly send: (msg: Message) => Promise\n private readonly types: Record\n private readonly maxDataSize: number\n\n constructor (init: MplexStreamInit) {\n super(init)\n\n this.types = init.direction === 'outbound' ? InitiatorMessageTypes : ReceiverMessageTypes\n this.send = init.send\n this.name = init.name\n this.streamId = init.streamId\n this.maxDataSize = init.maxDataSize\n }\n\n async sendNewStream (): Promise {\n await this.send({ id: this.streamId, type: InitiatorMessageTypes.NEW_STREAM, data: new Uint8ArrayList(uint8ArrayFromString(this.name)) })\n }\n\n async sendData (data: Uint8ArrayList): Promise {\n data = data.sublist()\n\n while (data.byteLength > 0) {\n const toSend = Math.min(data.byteLength, this.maxDataSize)\n await this.send({\n id: this.streamId,\n type: this.types.MESSAGE,\n data: data.sublist(0, toSend)\n })\n\n data.consume(toSend)\n }\n }\n\n async sendReset (): Promise {\n await this.send({ id: this.streamId, type: this.types.RESET })\n }\n\n async sendCloseWrite (): Promise {\n await this.send({ id: this.streamId, type: this.types.CLOSE })\n }\n\n async sendCloseRead (): Promise {\n // mplex does not support close read, only close write\n }\n}\n\nexport function createStream (options: Options): MplexStream {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options\n\n return new MplexStream({\n id: type === 'initiator' ? (`i${id}`) : `r${id}`,\n streamId: id,\n name: `${name == null ? id : name}`,\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n maxDataSize: maxMsgSize,\n onEnd,\n send,\n log: options.logger.forComponent(`libp2p:mplex:stream:${type}:${id}`)\n })\n}\n","import { CodeError } from '@libp2p/interface'\nimport { closeSource } from '@libp2p/utils/close-source'\nimport { RateLimiter } from '@libp2p/utils/rate-limiter'\nimport { pipe } from 'it-pipe'\nimport { type Pushable, pushable } from 'it-pushable'\nimport { toString as uint8ArrayToString } from 'uint8arrays'\nimport { Decoder } from './decode.js'\nimport { encode } from './encode.js'\nimport { MessageTypes, MessageTypeNames, type Message } from './message-types.js'\nimport { createStream, type MplexStream } from './stream.js'\nimport type { MplexInit } from './index.js'\nimport type { AbortOptions, ComponentLogger, Logger, Stream, StreamMuxer, StreamMuxerInit } from '@libp2p/interface'\nimport type { Sink, Source } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024\nconst MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024\nconst MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4 // 4MB\nconst DISCONNECT_THRESHOLD = 5\nconst CLOSE_TIMEOUT = 500\n\nfunction printMessage (msg: Message): any {\n const output: any = {\n ...msg,\n type: `${MessageTypeNames[msg.type]} (${msg.type})`\n }\n\n if (msg.type === MessageTypes.NEW_STREAM) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray())\n }\n\n if (msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray(), 'base16')\n }\n\n return output\n}\n\nexport interface MplexComponents {\n logger: ComponentLogger\n}\n\ninterface MplexStreamMuxerInit extends MplexInit, StreamMuxerInit {\n /**\n * The default timeout to use in ms when shutting down the muxer.\n */\n closeTimeout?: number\n}\n\nexport class MplexStreamMuxer implements StreamMuxer {\n public protocol = '/mplex/6.7.0'\n\n public sink: Sink, Promise>\n public source: AsyncGenerator\n\n private readonly log: Logger\n private _streamId: number\n private readonly _streams: { initiators: Map, receivers: Map }\n private readonly _init: MplexStreamMuxerInit\n private readonly _source: Pushable\n private readonly closeController: AbortController\n private readonly rateLimiter: RateLimiter\n private readonly closeTimeout: number\n private readonly logger: ComponentLogger\n\n constructor (components: MplexComponents, init?: MplexStreamMuxerInit) {\n init = init ?? {}\n\n this.log = components.logger.forComponent('libp2p:mplex')\n this.logger = components.logger\n this._streamId = 0\n this._streams = {\n /**\n * Stream to ids map\n */\n initiators: new Map(),\n /**\n * Stream to ids map\n */\n receivers: new Map()\n }\n this._init = init\n this.closeTimeout = init.closeTimeout ?? CLOSE_TIMEOUT\n\n /**\n * An iterable sink\n */\n this.sink = this._createSink()\n\n /**\n * An iterable source\n */\n this._source = pushable({\n objectMode: true,\n onEnd: (): void => {\n // the source has ended, we can't write any more messages to gracefully\n // close streams so all we can do is destroy them\n for (const stream of this._streams.initiators.values()) {\n stream.destroy()\n }\n\n for (const stream of this._streams.receivers.values()) {\n stream.destroy()\n }\n }\n })\n this.source = pipe(\n this._source,\n source => encode(source)\n )\n\n /**\n * Close controller\n */\n this.closeController = new AbortController()\n\n this.rateLimiter = new RateLimiter({\n points: init.disconnectThreshold ?? DISCONNECT_THRESHOLD,\n duration: 1\n })\n }\n\n /**\n * Returns a Map of streams and their ids\n */\n get streams (): Stream[] {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams: Stream[] = []\n for (const stream of this._streams.initiators.values()) {\n streams.push(stream)\n }\n\n for (const stream of this._streams.receivers.values()) {\n streams.push(stream)\n }\n return streams\n }\n\n /**\n * Initiate a new stream with the given name. If no name is\n * provided, the id of the stream will be used.\n */\n newStream (name?: string): Stream {\n if (this.closeController.signal.aborted) {\n throw new Error('Muxer already closed')\n }\n const id = this._streamId++\n name = name == null ? id.toString() : name.toString()\n const registry = this._streams.initiators\n return this._newStream({ id, name, type: 'initiator', registry })\n }\n\n /**\n * Close or abort all tracked streams and stop the muxer\n */\n async close (options?: AbortOptions): Promise {\n if (this.closeController.signal.aborted) {\n return\n }\n\n const signal = options?.signal ?? AbortSignal.timeout(this.closeTimeout)\n\n try {\n // try to gracefully close all streams\n await Promise.all(\n this.streams.map(async s => s.close({\n signal\n }))\n )\n\n this._source.end()\n\n // try to gracefully close the muxer\n await this._source.onEmpty({\n signal\n })\n\n this.closeController.abort()\n } catch (err: any) {\n this.abort(err)\n }\n }\n\n abort (err: Error): void {\n if (this.closeController.signal.aborted) {\n return\n }\n\n this.streams.forEach(s => { s.abort(err) })\n this.closeController.abort(err)\n }\n\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream (options: { id: number, name: string }): MplexStream {\n const { id, name } = options\n const registry = this._streams.receivers\n return this._newStream({ id, name, type: 'receiver', registry })\n }\n\n _newStream (options: { id: number, name: string, type: 'initiator' | 'receiver', registry: Map }): MplexStream {\n const { id, name, type, registry } = options\n\n this.log('new %s stream %s', type, id)\n\n if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {\n throw new CodeError('Too many outbound streams open', 'ERR_TOO_MANY_OUTBOUND_STREAMS')\n }\n\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`)\n }\n\n const send = async (msg: Message): Promise => {\n if (this.log.enabled) {\n this.log.trace('%s stream %s send', type, id, printMessage(msg))\n }\n\n this._source.push(msg)\n }\n\n const onEnd = (): void => {\n this.log('%s stream with id %s and protocol %s ended', type, id, stream.protocol)\n registry.delete(id)\n\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream)\n }\n }\n\n const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize, logger: this.logger })\n registry.set(id, stream)\n return stream\n }\n\n /**\n * Creates a sink with an abortable source. Incoming messages will\n * also have their size restricted. All messages will be varint decoded.\n */\n _createSink (): Sink, Promise> {\n const sink: Sink, Promise> = async source => {\n const abortListener = (): void => {\n closeSource(source, this.log)\n }\n\n this.closeController.signal.addEventListener('abort', abortListener)\n\n try {\n const decoder = new Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize)\n\n for await (const chunk of source) {\n for (const msg of decoder.write(chunk)) {\n await this._handleIncoming(msg)\n }\n }\n\n this._source.end()\n } catch (err: any) {\n this.log('error in sink', err)\n this._source.end(err) // End the source with an error\n } finally {\n this.closeController.signal.removeEventListener('abort', abortListener)\n }\n }\n\n return sink\n }\n\n async _handleIncoming (message: Message): Promise {\n const { id, type } = message\n\n if (this.log.enabled) {\n this.log.trace('incoming message', printMessage(message))\n }\n\n // Create a new stream?\n if (message.type === MessageTypes.NEW_STREAM) {\n if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {\n this.log('too many inbound streams open')\n\n // not going to allow this stream, send the reset message manually\n // instead of setting it up just to tear it down\n this._source.push({\n id,\n type: MessageTypes.RESET_RECEIVER\n })\n\n // if we've hit our stream limit, and the remote keeps trying to open\n // more new streams, if they are doing this very quickly maybe they\n // are attacking us and we should close the connection\n try {\n await this.rateLimiter.consume('new-stream', 1)\n } catch {\n this.log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection')\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many open streams'))\n return\n }\n\n return\n }\n\n const stream = this._newReceiverStream({ id, name: uint8ArrayToString(message.data instanceof Uint8Array ? message.data : message.data.subarray()) })\n\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream)\n }\n\n return\n }\n\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers\n const stream = list.get(id)\n\n if (stream == null) {\n this.log('missing stream %s for message type %s', id, MessageTypeNames[type])\n\n // if the remote keeps sending us messages for streams that have been\n // closed or were never opened they may be attacking us so if they do\n // this very quickly all we can do is close the connection\n try {\n await this.rateLimiter.consume('missing-stream', 1)\n } catch {\n this.log('rate limit hit when receiving messages for streams that do not exist - closing remote connection')\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many messages for missing streams'))\n return\n }\n\n return\n }\n\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE\n\n try {\n switch (type) {\n case MessageTypes.MESSAGE_INITIATOR:\n case MessageTypes.MESSAGE_RECEIVER:\n if (stream.sourceReadableLength() > maxBufferSize) {\n // Stream buffer has got too large, reset the stream\n this._source.push({\n id: message.id,\n type: type === MessageTypes.MESSAGE_INITIATOR ? MessageTypes.RESET_RECEIVER : MessageTypes.RESET_INITIATOR\n })\n\n // Inform the stream consumer they are not fast enough\n throw new CodeError('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers', 'ERR_STREAM_INPUT_BUFFER_FULL')\n }\n\n // We got data from the remote, push it into our local stream\n stream.sourcePush(message.data)\n break\n case MessageTypes.CLOSE_INITIATOR:\n case MessageTypes.CLOSE_RECEIVER:\n // The remote has stopped writing, so we can stop reading\n stream.remoteCloseWrite()\n break\n case MessageTypes.RESET_INITIATOR:\n case MessageTypes.RESET_RECEIVER:\n // The remote has errored, stop reading and writing to the stream immediately\n stream.reset()\n break\n default:\n this.log('unknown message type %s', type)\n }\n } catch (err: any) {\n this.log.error('error while processing message', err)\n stream.abort(err)\n }\n }\n}\n","/**\n * @packageDocumentation\n *\n * This is a [simple stream multiplexer(https://docs.libp2p.io/concepts/multiplex/mplex/) that has been deprecated.\n *\n * Please use [@chainsafe/libp2p-yamux](https://www.npmjs.com/package/@chainsafe/libp2p-yamux) instead.\n *\n * @example\n *\n * ```TypeScript\n * import { mplex } from '@libp2p/mplex'\n * import { pipe } from 'it-pipe'\n *\n * const factory = mplex()\n *\n * const muxer = factory.createStreamMuxer(components, {\n * onStream: stream => { // Receive a duplex stream from the remote\n * // ...receive data from the remote and optionally send data back\n * },\n * onStreamEnd: stream => {\n * // ...handle any tracking you may need of stream closures\n * }\n * })\n *\n * pipe(conn, muxer, conn) // conn is duplex connection to another peer\n *\n * const stream = muxer.newStream() // Create a new duplex stream to the remote\n *\n * // Use the duplex stream to send some data to the remote...\n * pipe([1, 2, 3], stream)\n * ```\n */\n\nimport { MplexStreamMuxer, type MplexComponents } from './mplex.js'\nimport type { StreamMuxer, StreamMuxerFactory, StreamMuxerInit } from '@libp2p/interface'\n\nexport interface MplexInit {\n /**\n * The maximum size of message that can be sent in one go in bytes.\n * Messages larger than this will be split into multiple smaller\n * messages. If we receive a message larger than this an error will\n * be thrown and the connection closed. (default: 1MB)\n */\n maxMsgSize?: number\n\n /**\n * Constrains the size of the unprocessed message queue buffer.\n * Before messages are deserialized, the raw bytes are buffered to ensure\n * we have the complete message to deserialized. If the queue gets longer\n * than this value an error will be thrown and the connection closed.\n * (default: 4MB)\n */\n maxUnprocessedMessageQueueSize?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. A request to open more than this will have a stream\n * reset message sent immediately as a response for the newly opened\n * stream id (default: 1024)\n */\n maxInboundStreams?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. An attempt to open more than this will throw (default: 1024)\n */\n maxOutboundStreams?: number\n\n /**\n * Incoming stream messages are buffered until processed by the stream\n * handler. If the buffer reaches this size in bytes the stream will\n * be reset (default: 4MB)\n */\n maxStreamBufferSize?: number\n\n /**\n * When `maxInboundStreams` is hit, if the remote continues try to open\n * more than this many new multiplexed streams per second the connection\n * will be closed (default: 5)\n */\n disconnectThreshold?: number\n}\n\nclass Mplex implements StreamMuxerFactory {\n public protocol = '/mplex/6.7.0'\n private readonly _init: MplexInit\n private readonly components: MplexComponents\n\n constructor (components: MplexComponents, init: MplexInit = {}) {\n this.components = components\n this._init = init\n }\n\n createStreamMuxer (init: StreamMuxerInit = {}): StreamMuxer {\n return new MplexStreamMuxer(this.components, {\n ...init,\n ...this._init\n })\n }\n}\n\nexport function mplex (init: MplexInit = {}): (components: MplexComponents) => StreamMuxerFactory {\n return (components) => new Mplex(components, init)\n}\n","/**\n * @packageDocumentation\n *\n * Return the first value in an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import first from 'it-first'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const res = first(values)\n *\n * console.info(res) // 0\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import first from 'it-first'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const res = await first(values())\n *\n * console.info(res) // 0\n * ```\n */\n\nfunction isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Returns the first result from an (async) iterable, unless empty, in which\n * case returns `undefined`\n */\nfunction first (source: Iterable): T | undefined\nfunction first (source: Iterable | AsyncIterable): Promise\nfunction first (source: Iterable | AsyncIterable): Promise | T | undefined {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry\n }\n\n return undefined\n })()\n }\n\n for (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry\n }\n\n return undefined\n}\n\nexport default first\n","export const PING_PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\nexport const PROTOCOL_PREFIX = 'ipfs'\nexport const TIMEOUT = 10000\n\n// See https://github.com/libp2p/specs/blob/d4b5fb0152a6bb86cfd9ea/ping/ping.md?plain=1#L38-L43\n// The dialing peer MUST NOT keep more than one outbound stream for the ping protocol per peer.\n// The listening peer SHOULD accept at most two streams per peer since cross-stream behavior is\n// non-linear and stream writes occur asynchronously. The listening peer may perceive the\n// dialing peer closing and opening the wrong streams (for instance, closing stream B and\n// opening stream A even though the dialing peer is opening stream B and closing stream A).\nexport const MAX_INBOUND_STREAMS = 2\nexport const MAX_OUTBOUND_STREAMS = 1\n\nexport const ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK'\n","import { randomBytes } from '@libp2p/crypto'\nimport { CodeError, ERR_TIMEOUT } from '@libp2p/interface'\nimport first from 'it-first'\nimport { pipe } from 'it-pipe'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS, ERR_WRONG_PING_ACK } from './constants.js'\nimport type { PingServiceComponents, PingServiceInit, PingService as PingServiceInterface } from './index.js'\nimport type { AbortOptions, Logger, Stream, PeerId, Startable } from '@libp2p/interface'\nimport type { IncomingStreamData } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport class PingService implements Startable, PingServiceInterface {\n public readonly protocol: string\n private readonly components: PingServiceComponents\n private started: boolean\n private readonly timeout: number\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n private readonly runOnTransientConnection: boolean\n private readonly log: Logger\n\n constructor (components: PingServiceComponents, init: PingServiceInit = {}) {\n this.components = components\n this.log = components.logger.forComponent('libp2p:ping')\n this.started = false\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.timeout = init.timeout ?? TIMEOUT\n this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS\n this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS\n this.runOnTransientConnection = init.runOnTransientConnection ?? true\n\n this.handleMessage = this.handleMessage.bind(this)\n }\n\n async start (): Promise {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n })\n this.started = true\n }\n\n async stop (): Promise {\n await this.components.registrar.unhandle(this.protocol)\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage (data: IncomingStreamData): void {\n this.log('incoming ping from %p', data.connection.remotePeer)\n\n const { stream } = data\n const start = Date.now()\n\n void pipe(stream, stream)\n .catch(err => {\n this.log.error('incoming ping from %p failed with error', data.connection.remotePeer, err)\n })\n .finally(() => {\n const ms = Date.now() - start\n\n this.log('incoming ping from %p complete in %dms', data.connection.remotePeer, ms)\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping (peer: PeerId | Multiaddr | Multiaddr[], options: AbortOptions = {}): Promise {\n this.log('pinging %p', peer)\n\n const start = Date.now()\n const data = randomBytes(PING_LENGTH)\n const connection = await this.components.connectionManager.openConnection(peer, options)\n let stream: Stream | undefined\n let onAbort = (): void => {}\n\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout)\n\n options = {\n ...options,\n signal\n }\n }\n\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n })\n\n onAbort = () => {\n stream?.abort(new CodeError('ping timeout', ERR_TIMEOUT))\n }\n\n // make stream abortable\n options.signal?.addEventListener('abort', onAbort, { once: true })\n\n const result = await pipe(\n [data],\n stream,\n async (source) => first(source)\n )\n\n const ms = Date.now() - start\n\n if (result == null) {\n throw new CodeError(`Did not receive a ping ack after ${ms}ms`, ERR_WRONG_PING_ACK)\n }\n\n if (!uint8ArrayEquals(data, result.subarray())) {\n throw new CodeError(`Received wrong ping ack after ${ms}ms`, ERR_WRONG_PING_ACK)\n }\n\n this.log('ping %p complete in %dms', connection.remotePeer, ms)\n\n return ms\n } catch (err: any) {\n this.log.error('error while pinging %p', connection.remotePeer, err)\n\n stream?.abort(err)\n\n throw err\n } finally {\n options.signal?.removeEventListener('abort', onAbort)\n if (stream != null) {\n await stream.close()\n }\n }\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH')\n }\n return randB(length)\n}\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","/**\n * @packageDocumentation\n *\n * The ping service implements the [libp2p ping spec](https://github.com/libp2p/specs/blob/master/ping/ping.md) allowing you to make a latency measurement to a remote peer.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { ping } from '@libp2p/ping'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * services: {\n * ping: ping()\n * }\n * })\n *\n * const rtt = await node.services.ping.ping(multiaddr('/ip4/...'))\n *\n * console.info(rtt)\n * ```\n */\n\nimport { PingService as PingServiceClass } from './ping.js'\nimport type { AbortOptions, ComponentLogger, PeerId } from '@libp2p/interface'\nimport type { ConnectionManager, Registrar } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface PingService {\n ping(peer: PeerId | Multiaddr | Multiaddr[], options?: AbortOptions): Promise\n}\n\nexport interface PingServiceInit {\n protocolPrefix?: string\n maxInboundStreams?: number\n maxOutboundStreams?: number\n runOnTransientConnection?: boolean\n\n /**\n * How long we should wait for a ping response\n */\n timeout?: number\n}\n\nexport interface PingServiceComponents {\n registrar: Registrar\n connectionManager: ConnectionManager\n logger: ComponentLogger\n}\n\nexport function ping (init: PingServiceInit = {}): (components: PingServiceComponents) => PingService {\n return (components) => new PingServiceClass(components, init)\n}\n\nexport { PING_PROTOCOL } from './constants.js'\n","import type { Connection, MultiaddrConnection } from '../connection/index.js'\nimport type { TypedEventTarget } from '../event-target.js'\nimport type { AbortOptions } from '../index.js'\nimport type { StreamMuxerFactory } from '../stream-muxer/index.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface ListenerEvents {\n 'connection': CustomEvent\n 'listening': CustomEvent\n 'error': CustomEvent\n 'close': CustomEvent\n}\n\nexport interface Listener extends TypedEventTarget {\n /**\n * Start a listener\n */\n listen(multiaddr: Multiaddr): Promise\n /**\n * Get listen addresses\n */\n getAddrs(): Multiaddr[]\n /**\n * Close listener\n *\n * @returns {Promise}\n */\n close(): Promise\n}\n\nexport const transportSymbol = Symbol.for('@libp2p/transport')\n\nexport interface ConnectionHandler { (connection: Connection): void }\n\nexport interface MultiaddrFilter { (multiaddrs: Multiaddr[]): Multiaddr[] }\n\nexport interface CreateListenerOptions {\n handler?: ConnectionHandler\n upgrader: Upgrader\n}\n\nexport interface DialOptions extends AbortOptions {\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport is understood as something that offers a dial and listen interface to establish connections.\n */\nexport interface Transport {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [transportSymbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial(ma: Multiaddr, options: DialOptions): Promise\n\n /**\n * Create transport listeners.\n */\n createListener(options: CreateListenerOptions): Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid addresses for the transport\n */\n filter: MultiaddrFilter\n}\n\nexport function isTransport (other: any): other is Transport {\n return other != null && Boolean(other[transportSymbol])\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n\nexport interface UpgraderOptions {\n skipEncryption?: boolean\n skipProtection?: boolean\n muxerFactory?: StreamMuxerFactory\n\n /**\n * The passed MultiaddrConnection has limits place on duration and/or data\n * transfer amounts so is not expected to be open for very long.\n */\n transient?: boolean\n}\n\nexport interface Upgrader {\n /**\n * Upgrades an outbound connection on `transport.dial`.\n */\n upgradeOutbound(maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise\n\n /**\n * Upgrades an inbound connection on transport listener.\n */\n upgradeInbound(maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise\n}\n","/**\n * @packageDocumentation\n *\n * This module allows easy conversion of Multiaddrs to string URIs.\n *\n * @example Converting multiaddrs to string URIs\n *\n * ```js\n * import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\n *\n * console.log(multiaddrToUri('/dnsaddr/protocol.ai/https'))\n * // -> https://protocol.ai\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080'))\n * // -> http://127.0.0.1:8080\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080', { assumeHttp: false }))\n * // -> tcp://127.0.0.1:8080\n * ```\n *\n * Note:\n *\n * - When `/tcp` is the last (terminating) protocol HTTP is assumed by default (implicit `assumeHttp: true`)\n * - this means produced URIs will start with `http://` instead of `tcp://`\n * - passing `{ assumeHttp: false }` disables this behavior\n * - Might be lossy - e.g. a DNSv6 multiaddr\n * - Can throw if the passed multiaddr:\n * - is not a valid multiaddr\n * - is not supported as a URI e.g. circuit\n */\n\nimport { multiaddr, protocols } from '@multiformats/multiaddr'\nimport type { Multiaddr, StringTuple } from '@multiformats/multiaddr'\n\nexport interface MultiaddrToUriOpts {\n assumeHttp?: boolean\n}\n\nconst ASSUME_HTTP_CODES = [\n protocols('tcp').code,\n protocols('dns').code,\n protocols('dnsaddr').code,\n protocols('dns4').code,\n protocols('dns6').code\n]\n\ninterface Interpreter { (value: string, ma: StringTuple[]): string }\n\nfunction extractSNI (ma: StringTuple[]): string | null {\n let sniProtoCode: number\n try {\n sniProtoCode = protocols('sni').code\n } catch (e) {\n // No SNI protocol in multiaddr\n return null\n }\n for (const [proto, value] of ma) {\n if (proto === sniProtoCode && value !== undefined) {\n return value\n }\n }\n return null\n}\n\nfunction hasTLS (ma: StringTuple[]): boolean {\n return ma.some(([proto, _]) => proto === protocols('tls').code)\n}\n\nfunction interpretNext (headProtoCode: number, headProtoVal: string, restMa: StringTuple[]): string {\n const interpreter = interpreters[protocols(headProtoCode).name]\n if (interpreter === undefined) {\n throw new Error(`Can't interpret protocol ${protocols(headProtoCode).name}`)\n }\n const restVal = interpreter(headProtoVal, restMa)\n if (headProtoCode === protocols('ip6').code) {\n return `[${restVal}]`\n }\n return restVal\n}\n\nconst interpreters: Record = {\n ip4: (value: string, restMa: StringTuple[]) => value,\n ip6: (value: string, restMa: StringTuple[]) => {\n if (restMa.length === 0) {\n return value\n }\n return `[${value}]`\n },\n tcp: (value: string, restMa: StringTuple[]) => {\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n return `tcp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`\n },\n udp: (value: string, restMa: StringTuple[]) => {\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n return `udp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`\n },\n dnsaddr: (value: string, restMa: StringTuple[]) => value,\n dns4: (value: string, restMa: StringTuple[]) => value,\n dns6: (value: string, restMa: StringTuple[]) => value,\n dns: (value: string, restMa: StringTuple[]) => value,\n ipfs: (value: string, restMa: StringTuple[]) => {\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/ipfs/${value}`\n },\n p2p: (value: string, restMa: StringTuple[]) => {\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p/${value}`\n },\n http: (value: string, restMa: StringTuple[]) => {\n const maHasTLS = hasTLS(restMa)\n const sni = extractSNI(restMa)\n if (maHasTLS && sni !== null) {\n return `https://${sni}`\n }\n const protocol = maHasTLS ? 'https://' : 'http://'\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa)\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '')\n return `${protocol}${baseVal}`\n },\n tls: (value: string, restMa: StringTuple[]) => {\n // Noop, the parent context knows that it's tls. We don't need to do\n // anything here\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa)\n },\n sni: (value: string, restMa: StringTuple[]) => {\n // Noop, the parent context uses the sni information, we don't need to do\n // anything here\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa)\n },\n https: (value: string, restMa: StringTuple[]) => {\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa)\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '')\n return `https://${baseVal}`\n },\n ws: (value: string, restMa: StringTuple[]) => {\n const maHasTLS = hasTLS(restMa)\n const sni = extractSNI(restMa)\n if (maHasTLS && sni !== null) {\n return `wss://${sni}`\n }\n const protocol = maHasTLS ? 'wss://' : 'ws://'\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa)\n // We are reinterpreting the base, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '')\n return `${protocol}${baseVal}`\n },\n wss: (value: string, restMa: StringTuple[]) => {\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa)\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '')\n return `wss://${baseVal}`\n },\n 'p2p-websocket-star': (value: string, restMa: StringTuple[]) => {\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-websocket-star`\n },\n 'p2p-webrtc-star': (value: string, restMa: StringTuple[]) => {\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-star`\n },\n 'p2p-webrtc-direct': (value: string, restMa: StringTuple[]) => {\n const tailProto = restMa.pop()\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-direct`\n }\n}\n\nexport function multiaddrToUri (input: Multiaddr | string | Uint8Array, opts?: MultiaddrToUriOpts): string {\n const ma = multiaddr(input)\n const parts = ma.stringTuples()\n const head = parts.pop()\n if (head === undefined) {\n throw new Error('Unexpected end of multiaddr')\n }\n\n const protocol = protocols(head[0])\n const interpreter = interpreters[protocol.name]\n\n if (interpreter == null) {\n throw new Error(`No interpreter found for ${protocol.name}`)\n }\n\n let uri = interpreter(head[1] ?? '', parts)\n\n if (opts?.assumeHttp !== false && ASSUME_HTTP_CODES.includes(head[0])) {\n // strip any declared protocol\n uri = uri.replace(/^.*:\\/\\//, '')\n\n if (head[1] === '443') {\n uri = `https://${uri}`\n } else {\n uri = `http://${uri}`\n }\n }\n\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n // this will strip default ports while keeping paths intact\n uri = new URL(uri).toString()\n\n // strip trailing slash, e.g. http://127.0.0.1/ -> http://127.0.0.1\n if (uri.endsWith('/')) {\n uri = uri.substring(0, uri.length - 1)\n }\n }\n\n return uri\n}\n","import type { ErrorEvent, WebSocket } from 'ws'\n\nexport default async (socket: WebSocket): Promise => {\n // if the socket is closing or closed, return end\n if (socket.readyState >= 2) {\n throw new Error('socket closed')\n }\n\n // if open, return\n if (socket.readyState === 1) {\n return\n }\n\n await new Promise((resolve, reject) => {\n function cleanup (): void {\n socket.removeEventListener('open', handleOpen)\n socket.removeEventListener('error', handleErr)\n }\n\n function handleOpen (): void {\n cleanup()\n resolve()\n }\n\n function handleErr (event: ErrorEvent): void {\n cleanup()\n reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`))\n }\n\n socket.addEventListener('open', handleOpen)\n socket.addEventListener('error', handleErr)\n })\n}\n","import ready from './ready.js'\nimport type { Sink, Source } from 'it-stream-types'\nimport type { WebSocket } from 'ws'\n\nexport interface SinkOptions {\n closeOnEnd?: boolean\n}\n\nexport default (socket: WebSocket, options: SinkOptions): Sink, Promise> => {\n options = options ?? {}\n options.closeOnEnd = options.closeOnEnd !== false\n\n const sink: Sink, Promise> = async source => {\n for await (const data of source) {\n try {\n await ready(socket)\n } catch (err: any) {\n if (err.message === 'socket closed') break\n throw err\n }\n\n // the ready promise resolved without error but the socket was closing so\n // exit the loop and don't send data\n if (socket.readyState === socket.CLOSING || socket.readyState === socket.CLOSED) {\n break\n }\n\n socket.send(data)\n }\n\n if (options.closeOnEnd != null && socket.readyState <= 1) {\n await new Promise((resolve, reject) => {\n socket.addEventListener('close', event => {\n if (event.wasClean || event.code === 1006) {\n resolve()\n } else {\n const err = Object.assign(new Error('ws error'), { event })\n reject(err)\n }\n })\n\n setTimeout(() => { socket.close() })\n })\n }\n }\n\n return sink\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { EventIterator } from 'event-iterator'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { WebSocket, ErrorEvent, MessageEvent } from 'ws'\n\n// copied from github.com/feross/buffer\n// Some ArrayBuffers are not passing the instanceof check, so we need to do a bit more work :(\nfunction isArrayBuffer (obj: any): obj is ArrayBuffer {\n return (obj instanceof ArrayBuffer) ||\n (obj?.constructor?.name === 'ArrayBuffer' && typeof obj?.byteLength === 'number')\n}\n\nexport interface ConnectedSource extends AsyncGenerator {\n connected: () => Promise\n}\n\nexport default (socket: WebSocket): ConnectedSource => {\n socket.binaryType = 'arraybuffer'\n\n const connected = async (): Promise => {\n await new Promise((resolve, reject) => {\n if (isConnected) {\n resolve(); return\n }\n if (connError != null) {\n reject(connError); return\n }\n\n const cleanUp = (cont: () => void): void => {\n socket.removeEventListener('open', onOpen)\n socket.removeEventListener('error', onError)\n cont()\n }\n\n const onOpen = (): void => { cleanUp(resolve) }\n const onError = (event: ErrorEvent): void => {\n cleanUp(() => { reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)) })\n }\n\n socket.addEventListener('open', onOpen)\n socket.addEventListener('error', onError)\n })\n }\n\n const source = (async function * () {\n const messages = new EventIterator(\n ({ push, stop, fail }) => {\n const onMessage = (event: MessageEvent): void => {\n let data: Uint8Array | null = null\n\n if (typeof event.data === 'string') {\n data = uint8ArrayFromString(event.data)\n }\n\n if (isArrayBuffer(event.data)) {\n data = new Uint8Array(event.data)\n }\n\n if (event.data instanceof Uint8Array) {\n data = event.data\n }\n\n if (data == null) {\n return\n }\n\n push(data)\n }\n const onError = (event: ErrorEvent): void => { fail(event.error ?? new Error('Socket error')) }\n\n socket.addEventListener('message', onMessage)\n socket.addEventListener('error', onError)\n socket.addEventListener('close', stop)\n\n return () => {\n socket.removeEventListener('message', onMessage)\n socket.removeEventListener('error', onError)\n socket.removeEventListener('close', stop)\n }\n },\n { highWaterMark: Infinity }\n )\n\n await connected()\n\n for await (const chunk of messages) {\n yield isArrayBuffer(chunk) ? new Uint8Array(chunk) : chunk\n }\n }())\n\n let isConnected = socket.readyState === 1\n let connError: Error | null\n\n socket.addEventListener('open', () => {\n isConnected = true\n connError = null\n })\n\n socket.addEventListener('close', () => {\n isConnected = false\n connError = null\n })\n\n socket.addEventListener('error', event => {\n if (!isConnected) {\n connError = event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)\n }\n })\n\n return Object.assign(source, {\n connected\n })\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","/* eslint-env browser */\n\nexport default WebSocket\n","const map = { 'http:': 'ws:', 'https:': 'wss:' }\nconst defaultProtocol = 'ws:'\n\nexport default (url: string, location?: Partial): URL => {\n if (url.startsWith('//')) {\n url = `${location?.protocol ?? defaultProtocol}${url}`\n }\n\n if (url.startsWith('/') && location != null) {\n const proto = location.protocol ?? defaultProtocol\n const host = location.host\n const port = location.port != null && host?.endsWith(`:${location.port}`) !== true ? `:${location.port}` : ''\n url = `${proto}//${host}${port}${url}`\n }\n\n const wsUrl = new URL(url)\n\n for (const [httpProto, wsProto] of Object.entries(map)) {\n if (wsUrl.protocol === httpProto) {\n wsUrl.protocol = wsProto\n }\n }\n\n return wsUrl\n}\n","// load websocket library if we are not in the browser\nimport duplex from './duplex.js'\nimport WebSocket from './web-socket.js'\nimport wsurl from './ws-url.js'\nimport type { DuplexWebSocket } from './duplex.js'\nimport type { SinkOptions } from './sink.js'\nimport type { ClientOptions } from 'ws'\n\nexport interface WebSocketOptions extends SinkOptions {\n websocket?: ClientOptions\n}\n\nexport function connect (addr: string, opts?: WebSocketOptions): DuplexWebSocket {\n const location = typeof window === 'undefined' ? undefined : window.location\n opts = opts ?? {}\n\n const url = wsurl(addr, location)\n\n // it's necessary to stringify the URL object otherwise react-native crashes\n const socket = new WebSocket(url.toString(), opts.websocket)\n return duplex(socket, opts)\n}\n","import sink from './sink.js'\nimport source from './source.js'\nimport type { SinkOptions } from './sink.js'\nimport type WebSocket from './web-socket.js'\nimport type { Duplex, Source } from 'it-stream-types'\n\nexport interface DuplexWebSocket extends Duplex, Source, Promise> {\n connected: () => Promise\n localAddress?: string\n localPort?: number\n remoteAddress: string\n remotePort: number\n close: () => Promise\n destroy: () => void\n socket: WebSocket\n}\n\nexport interface DuplexWebSocketOptions extends SinkOptions {\n remoteAddress?: string\n remotePort?: number\n}\n\nexport default (socket: WebSocket, options?: DuplexWebSocketOptions): DuplexWebSocket => {\n options = options ?? {}\n\n const connectedSource = source(socket)\n let remoteAddress: string | undefined = options.remoteAddress\n let remotePort: number | undefined = options.remotePort\n\n if (socket.url != null) {\n // only client->server sockets have urls, server->client connections do not\n try {\n const url = new URL(socket.url)\n remoteAddress = url.hostname\n remotePort = parseInt(url.port, 10)\n } catch {}\n }\n\n if (remoteAddress == null || remotePort == null) {\n throw new Error('Remote connection did not have address and/or port')\n }\n\n const duplex: DuplexWebSocket = {\n sink: sink(socket, options),\n source: connectedSource,\n connected: async () => { await connectedSource.connected() },\n close: async () => {\n if (socket.readyState === socket.CONNECTING || socket.readyState === socket.OPEN) {\n await new Promise((resolve) => {\n socket.addEventListener('close', () => {\n resolve()\n })\n socket.close()\n })\n }\n },\n destroy: () => {\n if (socket.terminate != null) {\n socket.terminate()\n } else {\n socket.close()\n }\n },\n remoteAddress,\n remotePort,\n socket\n }\n\n return duplex\n}\n","// p2p multi-address code\nexport const CODE_P2P = 421\nexport const CODE_CIRCUIT = 290\n\nexport const CODE_TCP = 6\nexport const CODE_WS = 477\nexport const CODE_WSS = 478\n\n// Time to wait for a connection to close gracefully before destroying it manually\nexport const CLOSE_TIMEOUT = 500\n","import * as mafmt from '@multiformats/mafmt'\nimport {\n CODE_CIRCUIT,\n CODE_P2P,\n CODE_TCP,\n CODE_WS,\n CODE_WSS\n} from './constants.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport function all (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSockets.matches(testMa) ||\n mafmt.WebSocketsSecure.matches(testMa)\n })\n}\n\nexport function wss (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSocketsSecure.matches(testMa)\n })\n}\n\nexport function dnsWss (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n\nexport function dnsWsOrWss (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n // WS\n if (mafmt.WebSockets.matches(testMa)) {\n return mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WS))\n }\n\n // WSS\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n","/**\n * @packageDocumentation\n *\n * A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/) based on [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API).\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets()\n * ]\n * //... other config\n * })\n * await node.start()\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/9090/ws')\n * await node.dial(ma)\n * ```\n *\n * ## Filters\n *\n * When run in a browser by default this module will only connect to secure web socket addresses.\n *\n * To change this you should pass a filter to the factory function.\n *\n * You can create your own address filters for this transports, or rely in the filters [provided](./src/filters.js).\n *\n * The available filters are:\n *\n * - `filters.all`\n * - Returns all TCP and DNS based addresses, both with `ws` or `wss`.\n * - `filters.dnsWss`\n * - Returns all DNS based addresses with `wss`.\n * - `filters.dnsWsOrWss`\n * - Returns all DNS based addresses, both with `ws` or `wss`.\n *\n * @example Allow dialing insecure WebSockets\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import filters from '@libp2p/websockets/filters'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets({\n * // connect to all sockets, even insecure ones\n * filter: filters.all\n * })\n * ]\n * })\n * ```\n */\n\nimport { AbortError, CodeError } from '@libp2p/interface'\nimport { type Transport, type MultiaddrFilter, transportSymbol, type CreateListenerOptions, type DialOptions, type Listener, type AbortOptions, type ComponentLogger, type Logger, type Connection } from '@libp2p/interface'\nimport { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri'\nimport { connect, type WebSocketOptions } from 'it-ws/client'\nimport pDefer from 'p-defer'\nimport { isBrowser, isWebWorker } from 'wherearewe'\nimport * as filters from './filters.js'\nimport { createListener } from './listener.js'\nimport { socketToMaConn } from './socket-to-conn.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Server } from 'http'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\nimport type { ClientOptions } from 'ws'\n\nexport interface WebSocketsInit extends AbortOptions, WebSocketOptions {\n filter?: MultiaddrFilter\n websocket?: ClientOptions\n server?: Server\n}\n\nexport interface WebSocketsComponents {\n logger: ComponentLogger\n}\n\nclass WebSockets implements Transport {\n private readonly log: Logger\n private readonly init?: WebSocketsInit\n private readonly logger: ComponentLogger\n\n constructor (components: WebSocketsComponents, init?: WebSocketsInit) {\n this.log = components.logger.forComponent('libp2p:websockets')\n this.logger = components.logger\n this.init = init\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/websockets'\n\n readonly [transportSymbol] = true\n\n async dial (ma: Multiaddr, options: DialOptions): Promise {\n this.log('dialing %s', ma)\n options = options ?? {}\n\n const socket = await this._connect(ma, options)\n const maConn = socketToMaConn(socket, ma, {\n logger: this.logger\n })\n this.log('new outbound connection %s', maConn.remoteAddr)\n\n const conn = await options.upgrader.upgradeOutbound(maConn)\n this.log('outbound connection %s upgraded', maConn.remoteAddr)\n return conn\n }\n\n async _connect (ma: Multiaddr, options: AbortOptions): Promise {\n if (options?.signal?.aborted === true) {\n throw new AbortError()\n }\n const cOpts = ma.toOptions()\n this.log('dialing %s:%s', cOpts.host, cOpts.port)\n\n const errorPromise = pDefer()\n const rawSocket = connect(toUri(ma), this.init)\n rawSocket.socket.addEventListener('error', () => {\n // the WebSocket.ErrorEvent type doesn't actually give us any useful\n // information about what happened\n // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event\n const err = new CodeError(`Could not connect to ${ma.toString()}`, 'ERR_CONNECTION_FAILED')\n this.log.error('connection error:', err)\n errorPromise.reject(err)\n })\n\n if (options.signal == null) {\n await Promise.race([rawSocket.connected(), errorPromise.promise])\n\n this.log('connected %s', ma)\n return rawSocket\n }\n\n // Allow abort via signal during connect\n let onAbort\n const abort = new Promise((resolve, reject) => {\n onAbort = () => {\n reject(new AbortError())\n rawSocket.close().catch(err => {\n this.log.error('error closing raw socket', err)\n })\n }\n\n // Already aborted?\n if (options?.signal?.aborted === true) {\n onAbort(); return\n }\n\n options?.signal?.addEventListener('abort', onAbort)\n })\n\n try {\n await Promise.race([abort, errorPromise.promise, rawSocket.connected()])\n } finally {\n if (onAbort != null) {\n options?.signal?.removeEventListener('abort', onAbort)\n }\n }\n\n this.log('connected %s', ma)\n return rawSocket\n }\n\n /**\n * Creates a Websockets listener. The provided `handler` function will be called\n * anytime a new incoming Connection has been successfully upgraded via\n * `upgrader.upgradeInbound`\n */\n createListener (options: CreateListenerOptions): Listener {\n return createListener({\n logger: this.logger\n }, {\n ...this.init,\n ...options\n })\n }\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid Websockets addresses.\n * By default, in a browser environment only DNS+WSS multiaddr is accepted,\n * while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.\n */\n filter (multiaddrs: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs)\n }\n\n // Browser\n if (isBrowser || isWebWorker) {\n return filters.wss(multiaddrs)\n }\n\n return filters.all(multiaddrs)\n }\n}\n\nexport function webSockets (init: WebSocketsInit = {}): (components: WebSocketsComponents) => Transport {\n return (components) => {\n return new WebSockets(components, init)\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { CLOSE_TIMEOUT } from './constants.js'\nimport type { AbortOptions, ComponentLogger, MultiaddrConnection } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\n\nexport interface SocketToConnOptions {\n localAddr?: Multiaddr\n logger: ComponentLogger\n}\n\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nexport function socketToMaConn (stream: DuplexWebSocket, remoteAddr: Multiaddr, options: SocketToConnOptions): MultiaddrConnection {\n const log = options.logger.forComponent('libp2p:websockets:maconn')\n\n const maConn: MultiaddrConnection = {\n log,\n\n async sink (source) {\n try {\n await stream.sink((async function * () {\n for await (const buf of source) {\n if (buf instanceof Uint8Array) {\n yield buf\n } else {\n yield buf.subarray()\n }\n }\n })())\n } catch (err: any) {\n if (err.type !== 'aborted') {\n log.error(err)\n }\n }\n },\n\n source: stream.source,\n\n remoteAddr,\n\n timeline: { open: Date.now() },\n\n async close (options: AbortOptions = {}) {\n const start = Date.now()\n\n if (options.signal == null) {\n const signal = AbortSignal.timeout(CLOSE_TIMEOUT)\n\n options = {\n ...options,\n signal\n }\n }\n\n const listener = (): void => {\n const { host, port } = maConn.remoteAddr.toOptions()\n log('timeout closing stream to %s:%s after %dms, destroying it manually',\n host, port, Date.now() - start)\n\n this.abort(new CodeError('Socket close timeout', 'ERR_SOCKET_CLOSE_TIMEOUT'))\n }\n\n options.signal?.addEventListener('abort', listener)\n\n try {\n await stream.close()\n } catch (err: any) {\n log.error('error closing WebSocket gracefully', err)\n this.abort(err)\n } finally {\n options.signal?.removeEventListener('abort', listener)\n maConn.timeline.close = Date.now()\n }\n },\n\n abort (err: Error): void {\n const { host, port } = maConn.remoteAddr.toOptions()\n log('timeout closing stream to %s:%s due to error',\n host, port, err)\n\n stream.destroy()\n maConn.timeline.close = Date.now()\n }\n }\n\n stream.socket.addEventListener('close', () => {\n // In instances where `close` was not explicitly called,\n // such as an iterable stream ending, ensure we have set the close\n // timeline\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now()\n }\n }, { once: true })\n\n return maConn\n}\n","import type { Listener } from '@libp2p/interface'\n\nexport function createListener (): Listener {\n throw new Error('WebSocket Servers can not be created in the browser!')\n}\n","import type { Stream } from '../connection/index.js'\nimport type { TypedEventTarget } from '../event-target.js'\nimport type { PeerId } from '../peer-id/index.js'\nimport type { Pushable } from 'it-pushable'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/**\n * On the producing side:\n * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * * Enforce the fields to be present, reject otherwise.\n * * Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nexport const StrictSign = 'StrictSign'\n\n/**\n * On the producing side:\n * * Build messages without the signature, key, from and seqno fields.\n * * The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * * Enforce the fields to be absent, reject otherwise.\n * * Propagate only if the fields are absent, reject otherwise.\n * * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nexport const StrictNoSign = 'StrictNoSign'\n\nexport type SignaturePolicy = typeof StrictSign | typeof StrictNoSign\n\nexport interface SignedMessage {\n type: 'signed'\n from: PeerId\n topic: string\n data: Uint8Array\n sequenceNumber: bigint\n signature: Uint8Array\n key: Uint8Array\n}\n\nexport interface UnsignedMessage {\n type: 'unsigned'\n topic: string\n data: Uint8Array\n}\n\nexport type Message = SignedMessage | UnsignedMessage\n\nexport interface PubSubRPCMessage {\n from?: Uint8Array\n topic?: string\n data?: Uint8Array\n sequenceNumber?: Uint8Array\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCSubscription {\n subscribe?: boolean\n topic?: string\n}\n\nexport interface PubSubRPC {\n subscriptions: PubSubRPCSubscription[]\n messages: PubSubRPCMessage[]\n}\n\nexport interface PeerStreams extends TypedEventTarget {\n id: PeerId\n protocol: string\n outboundStream?: Pushable\n inboundStream?: AsyncIterable\n isWritable: boolean\n\n close(): void\n write(buf: Uint8Array | Uint8ArrayList): void\n attachInboundStream(stream: Stream): AsyncIterable\n attachOutboundStream(stream: Stream): Promise>\n}\n\nexport interface PubSubInit {\n enabled?: boolean\n\n multicodecs?: string[]\n\n /**\n * defines how signatures should be handled\n */\n globalSignaturePolicy?: SignaturePolicy\n\n /**\n * if can relay messages not subscribed\n */\n canRelayMessage?: boolean\n\n /**\n * if publish should emit to self, if subscribed\n */\n emitSelf?: boolean\n\n /**\n * handle this many incoming pubsub messages concurrently\n */\n messageProcessingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the pubsub protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the pubsub protocol per-connection\n */\n maxOutboundStreams?: number\n}\n\ninterface Subscription {\n topic: string\n subscribe: boolean\n}\n\nexport interface SubscriptionChangeData {\n peerId: PeerId\n subscriptions: Subscription[]\n}\n\nexport interface PubSubEvents {\n 'subscription-change': CustomEvent\n 'message': CustomEvent\n}\n\nexport interface PublishResult {\n recipients: PeerId[]\n}\n\nexport enum TopicValidatorResult {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n Accept = 'accept',\n /**\n * The message is neither delivered nor forwarded to the network\n */\n Ignore = 'ignore',\n /**\n * The message is considered invalid, and it should be rejected\n */\n Reject = 'reject'\n}\n\nexport interface TopicValidatorFn {\n (peer: PeerId, message: Message): TopicValidatorResult | Promise\n}\n\nexport interface PubSub = PubSubEvents> extends TypedEventTarget {\n /**\n * The global signature policy controls whether or not we sill send and receive\n * signed or unsigned messages.\n *\n * Signed messages prevent spoofing message senders and should be preferred to\n * using unsigned messages.\n */\n globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n\n /**\n * A list of multicodecs that contain the pubsub protocol name.\n */\n multicodecs: string[]\n\n /**\n * Pubsub routers support message validators per topic, which will validate the message\n * before its propagations. They are stored in a map where keys are the topic name and\n * values are the validators.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const validateMessage = (msgTopic, msg) => {\n * const input = uint8ArrayToString(msg.data)\n * const validInputs = ['a', 'b', 'c']\n *\n * if (!validInputs.includes(input)) {\n * throw new Error('no valid input received')\n * }\n * }\n * libp2p.pubsub.topicValidators.set(topic, validateMessage)\n * ```\n */\n topicValidators: Map\n\n getPeers(): PeerId[]\n\n /**\n * Gets a list of topics the node is subscribed to.\n *\n * ```TypeScript\n * const topics = libp2p.pubsub.getTopics()\n * ```\n */\n getTopics(): string[]\n\n /**\n * Subscribes to a pubsub topic.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const handler = (msg) => {\n * if (msg.topic === topic) {\n * // msg.data - pubsub data received\n * }\n * }\n *\n * libp2p.pubsub.addEventListener('message', handler)\n * libp2p.pubsub.subscribe(topic)\n * ```\n */\n subscribe(topic: string): void\n\n /**\n * Unsubscribes from a pubsub topic.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const handler = (msg) => {\n * // msg.data - pubsub data received\n * }\n *\n * libp2p.pubsub.removeEventListener(topic handler)\n * libp2p.pubsub.unsubscribe(topic)\n * ```\n */\n unsubscribe(topic: string): void\n\n /**\n * Gets a list of the PeerIds that are subscribed to one topic.\n *\n * @example\n *\n * ```TypeScript\n * const peerIds = libp2p.pubsub.getSubscribers(topic)\n * ```\n */\n getSubscribers(topic: string): PeerId[]\n\n /**\n * Publishes messages to the given topic.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const data = uint8ArrayFromString('data')\n *\n * await libp2p.pubsub.publish(topic, data)\n * ```\n */\n publish(topic: string, data: Uint8Array): Promise\n}\n\nexport interface PeerStreamEvents {\n 'stream:inbound': CustomEvent\n 'stream:outbound': CustomEvent\n 'close': CustomEvent\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","export const second = 1000\nexport const minute = 60 * second\n\n// Protocol identifiers\n\nexport const FloodsubID = '/floodsub/1.0.0'\n\n/**\n * The protocol ID for version 1.0.0 of the Gossipsub protocol\n * It is advertised along with GossipsubIDv11 for backwards compatability\n */\nexport const GossipsubIDv10 = '/meshsub/1.0.0'\n\n/**\n * The protocol ID for version 1.1.0 of the Gossipsub protocol\n * See the spec for details about how v1.1.0 compares to v1.0.0:\n * https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/gossipsub-v1.1.md\n */\nexport const GossipsubIDv11 = '/meshsub/1.1.0'\n\n// Overlay parameters\n\n/**\n * GossipsubD sets the optimal degree for a Gossipsub topic mesh. For example, if GossipsubD == 6,\n * each peer will want to have about six peers in their mesh for each topic they're subscribed to.\n * GossipsubD should be set somewhere between GossipsubDlo and GossipsubDhi.\n */\nexport const GossipsubD = 6\n\n/**\n * GossipsubDlo sets the lower bound on the number of peers we keep in a Gossipsub topic mesh.\n * If we have fewer than GossipsubDlo peers, we will attempt to graft some more into the mesh at\n * the next heartbeat.\n */\nexport const GossipsubDlo = 4\n\n/**\n * GossipsubDhi sets the upper bound on the number of peers we keep in a Gossipsub topic mesh.\n * If we have more than GossipsubDhi peers, we will select some to prune from the mesh at the next heartbeat.\n */\nexport const GossipsubDhi = 12\n\n/**\n * GossipsubDscore affects how peers are selected when pruning a mesh due to over subscription.\n * At least GossipsubDscore of the retained peers will be high-scoring, while the remainder are\n * chosen randomly.\n */\nexport const GossipsubDscore = 4\n\n/**\n * GossipsubDout sets the quota for the number of outbound connections to maintain in a topic mesh.\n * When the mesh is pruned due to over subscription, we make sure that we have outbound connections\n * to at least GossipsubDout of the survivor peers. This prevents sybil attackers from overwhelming\n * our mesh with incoming connections.\n *\n * GossipsubDout must be set below GossipsubDlo, and must not exceed GossipsubD / 2.\n */\nexport const GossipsubDout = 2\n\n// Gossip parameters\n\n/**\n * GossipsubHistoryLength controls the size of the message cache used for gossip.\n * The message cache will remember messages for GossipsubHistoryLength heartbeats.\n */\nexport const GossipsubHistoryLength = 5\n\n/**\n * GossipsubHistoryGossip controls how many cached message ids we will advertise in\n * IHAVE gossip messages. When asked for our seen message IDs, we will return\n * only those from the most recent GossipsubHistoryGossip heartbeats. The slack between\n * GossipsubHistoryGossip and GossipsubHistoryLength allows us to avoid advertising messages\n * that will be expired by the time they're requested.\n *\n * GossipsubHistoryGossip must be less than or equal to GossipsubHistoryLength to\n * avoid a runtime panic.\n */\nexport const GossipsubHistoryGossip = 3\n\n/**\n * GossipsubDlazy affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to at least GossipsubDlazy peers outside our mesh. The actual\n * number may be more, depending on GossipsubGossipFactor and how many peers we're\n * connected to.\n */\nexport const GossipsubDlazy = 6\n\n/**\n * GossipsubGossipFactor affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to GossipsubGossipFactor * (total number of non-mesh peers), or\n * GossipsubDlazy, whichever is greater.\n */\nexport const GossipsubGossipFactor = 0.25\n\n/**\n * GossipsubGossipRetransmission controls how many times we will allow a peer to request\n * the same message id through IWANT gossip before we start ignoring them. This is designed\n * to prevent peers from spamming us with requests and wasting our resources.\n */\nexport const GossipsubGossipRetransmission = 3\n\n// Heartbeat interval\n\n/**\n * GossipsubHeartbeatInitialDelay is the short delay before the heartbeat timer begins\n * after the router is initialized.\n */\nexport const GossipsubHeartbeatInitialDelay = 100\n\n/**\n * GossipsubHeartbeatInterval controls the time between heartbeats.\n */\nexport const GossipsubHeartbeatInterval = second\n\n/**\n * GossipsubFanoutTTL controls how long we keep track of the fanout state. If it's been\n * GossipsubFanoutTTL since we've published to a topic that we're not subscribed to,\n * we'll delete the fanout map for that topic.\n */\nexport const GossipsubFanoutTTL = minute\n\n/**\n * GossipsubPrunePeers controls the number of peers to include in prune Peer eXchange.\n * When we prune a peer that's eligible for PX (has a good score, etc), we will try to\n * send them signed peer records for up to GossipsubPrunePeers other peers that we\n * know of.\n */\nexport const GossipsubPrunePeers = 16\n\n/**\n * GossipsubPruneBackoff controls the backoff time for pruned peers. This is how long\n * a peer must wait before attempting to graft into our mesh again after being pruned.\n * When pruning a peer, we send them our value of GossipsubPruneBackoff so they know\n * the minimum time to wait. Peers running older versions may not send a backoff time,\n * so if we receive a prune message without one, we will wait at least GossipsubPruneBackoff\n * before attempting to re-graft.\n */\nexport const GossipsubPruneBackoff = minute\n\n/**\n * Backoff to use when unsuscribing from a topic. Should not resubscribe to this topic before it expired.\n */\nexport const GossipsubUnsubscribeBackoff = 10 * second\n\n/**\n * GossipsubPruneBackoffTicks is the number of heartbeat ticks for attempting to prune expired\n * backoff timers.\n */\nexport const GossipsubPruneBackoffTicks = 15\n\n/**\n * GossipsubConnectors controls the number of active connection attempts for peers obtained through PX.\n */\nexport const GossipsubConnectors = 8\n\n/**\n * GossipsubMaxPendingConnections sets the maximum number of pending connections for peers attempted through px.\n */\nexport const GossipsubMaxPendingConnections = 128\n\n/**\n * GossipsubConnectionTimeout controls the timeout for connection attempts.\n */\nexport const GossipsubConnectionTimeout = 30 * second\n\n/**\n * GossipsubDirectConnectTicks is the number of heartbeat ticks for attempting to reconnect direct peers\n * that are not currently connected.\n */\nexport const GossipsubDirectConnectTicks = 300\n\n/**\n * GossipsubDirectConnectInitialDelay is the initial delay before opening connections to direct peers\n */\nexport const GossipsubDirectConnectInitialDelay = second\n\n/**\n * GossipsubOpportunisticGraftTicks is the number of heartbeat ticks for attempting to improve the mesh\n * with opportunistic grafting. Every GossipsubOpportunisticGraftTicks we will attempt to select some\n * high-scoring mesh peers to replace lower-scoring ones, if the median score of our mesh peers falls\n * below a threshold\n */\nexport const GossipsubOpportunisticGraftTicks = 60\n\n/**\n * GossipsubOpportunisticGraftPeers is the number of peers to opportunistically graft.\n */\nexport const GossipsubOpportunisticGraftPeers = 2\n\n/**\n * If a GRAFT comes before GossipsubGraftFloodThreshold has elapsed since the last PRUNE,\n * then there is an extra score penalty applied to the peer through P7.\n */\nexport const GossipsubGraftFloodThreshold = 10 * second\n\n/**\n * GossipsubMaxIHaveLength is the maximum number of messages to include in an IHAVE message.\n * Also controls the maximum number of IHAVE ids we will accept and request with IWANT from a\n * peer within a heartbeat, to protect from IHAVE floods. You should adjust this value from the\n * default if your system is pushing more than 5000 messages in GossipsubHistoryGossip heartbeats;\n * with the defaults this is 1666 messages/s.\n */\nexport const GossipsubMaxIHaveLength = 5000\n\n/**\n * GossipsubMaxIHaveMessages is the maximum number of IHAVE messages to accept from a peer within a heartbeat.\n */\nexport const GossipsubMaxIHaveMessages = 10\n\n/**\n * Time to wait for a message requested through IWANT following an IHAVE advertisement.\n * If the message is not received within this window, a broken promise is declared and\n * the router may apply bahavioural penalties.\n */\nexport const GossipsubIWantFollowupTime = 3 * second\n\n/**\n * Time in milliseconds to keep message ids in the seen cache\n */\nexport const GossipsubSeenTTL = 2 * minute\n\nexport const TimeCacheDuration = 120 * 1000\n\nexport const ERR_TOPIC_VALIDATOR_REJECT = 'ERR_TOPIC_VALIDATOR_REJECT'\nexport const ERR_TOPIC_VALIDATOR_IGNORE = 'ERR_TOPIC_VALIDATOR_IGNORE'\n\n/**\n * If peer score is better than this, we accept messages from this peer\n * within ACCEPT_FROM_WHITELIST_DURATION_MS from the last time computing score.\n **/\nexport const ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE = 0\n\n/**\n * If peer score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE, accept up to this\n * number of messages from that peer.\n */\nexport const ACCEPT_FROM_WHITELIST_MAX_MESSAGES = 128\n\n/**\n * If peer score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE, accept messages from\n * this peer up to this time duration.\n */\nexport const ACCEPT_FROM_WHITELIST_DURATION_MS = 1000\n\n/**\n * The default MeshMessageDeliveriesWindow to be used in metrics.\n */\nexport const DEFAULT_METRIC_MESH_MESSAGE_DELIVERIES_WINDOWS = 1000\n\n/** Wait for 1 more heartbeats before clearing a backoff */\nexport const BACKOFF_SLACK = 1\n","export interface DecodeRPCLimits {\n maxSubscriptions: number\n maxMessages: number\n maxIhaveMessageIDs: number\n maxIwantMessageIDs: number\n maxControlMessages: number\n maxPeerInfos: number\n}\n\nexport const defaultDecodeRpcLimits: DecodeRPCLimits = {\n maxSubscriptions: Infinity,\n maxMessages: Infinity,\n maxIhaveMessageIDs: Infinity,\n maxIwantMessageIDs: Infinity,\n maxControlMessages: Infinity,\n maxPeerInfos: Infinity\n}\n","const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n","import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, CodeError, decodeMessage, type DecodeOptions, encodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface RPC {\n subscriptions: RPC.SubOpts[]\n messages: RPC.Message[]\n control?: RPC.ControlMessage\n}\n\nexport namespace RPC {\n export interface SubOpts {\n subscribe?: boolean\n topic?: string\n }\n\n export namespace SubOpts {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.subscribe != null) {\n w.uint32(8)\n w.bool(obj.subscribe)\n }\n\n if (obj.topic != null) {\n w.uint32(18)\n w.string(obj.topic)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.subscribe = reader.bool()\n break\n }\n case 2: {\n obj.topic = reader.string()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, SubOpts.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions): SubOpts => {\n return decodeMessage(buf, SubOpts.codec(), opts)\n }\n }\n\n export interface Message {\n from?: Uint8Array\n data?: Uint8Array\n seqno?: Uint8Array\n topic: string\n signature?: Uint8Array\n key?: Uint8Array\n }\n\n export namespace Message {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.from != null) {\n w.uint32(10)\n w.bytes(obj.from)\n }\n\n if (obj.data != null) {\n w.uint32(18)\n w.bytes(obj.data)\n }\n\n if (obj.seqno != null) {\n w.uint32(26)\n w.bytes(obj.seqno)\n }\n\n if ((obj.topic != null && obj.topic !== '')) {\n w.uint32(34)\n w.string(obj.topic)\n }\n\n if (obj.signature != null) {\n w.uint32(42)\n w.bytes(obj.signature)\n }\n\n if (obj.key != null) {\n w.uint32(50)\n w.bytes(obj.key)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n topic: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.from = reader.bytes()\n break\n }\n case 2: {\n obj.data = reader.bytes()\n break\n }\n case 3: {\n obj.seqno = reader.bytes()\n break\n }\n case 4: {\n obj.topic = reader.string()\n break\n }\n case 5: {\n obj.signature = reader.bytes()\n break\n }\n case 6: {\n obj.key = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Message.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions): Message => {\n return decodeMessage(buf, Message.codec(), opts)\n }\n }\n\n export interface ControlMessage {\n ihave: RPC.ControlIHave[]\n iwant: RPC.ControlIWant[]\n graft: RPC.ControlGraft[]\n prune: RPC.ControlPrune[]\n }\n\n export namespace ControlMessage {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.ihave != null) {\n for (const value of obj.ihave) {\n w.uint32(10)\n RPC.ControlIHave.codec().encode(value, w)\n }\n }\n\n if (obj.iwant != null) {\n for (const value of obj.iwant) {\n w.uint32(18)\n RPC.ControlIWant.codec().encode(value, w)\n }\n }\n\n if (obj.graft != null) {\n for (const value of obj.graft) {\n w.uint32(26)\n RPC.ControlGraft.codec().encode(value, w)\n }\n }\n\n if (obj.prune != null) {\n for (const value of obj.prune) {\n w.uint32(34)\n RPC.ControlPrune.codec().encode(value, w)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n ihave: [],\n iwant: [],\n graft: [],\n prune: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.ihave != null && obj.ihave.length === opts.limits.ihave) {\n throw new CodeError('decode error - map field \"ihave\" had too many elements', 'ERR_MAX_LENGTH')\n }\n\n obj.ihave.push(RPC.ControlIHave.codec().decode(reader, reader.uint32()))\n break\n }\n case 2: {\n if (opts.limits?.iwant != null && obj.iwant.length === opts.limits.iwant) {\n throw new CodeError('decode error - map field \"iwant\" had too many elements', 'ERR_MAX_LENGTH')\n }\n\n obj.iwant.push(RPC.ControlIWant.codec().decode(reader, reader.uint32()))\n break\n }\n case 3: {\n if (opts.limits?.graft != null && obj.graft.length === opts.limits.graft) {\n throw new CodeError('decode error - map field \"graft\" had too many elements', 'ERR_MAX_LENGTH')\n }\n\n obj.graft.push(RPC.ControlGraft.codec().decode(reader, reader.uint32()))\n break\n }\n case 4: {\n if (opts.limits?.prune != null && obj.prune.length === opts.limits.prune) {\n throw new CodeError('decode error - map field \"prune\" had too many elements', 'ERR_MAX_LENGTH')\n }\n\n obj.prune.push(RPC.ControlPrune.codec().decode(reader, reader.uint32()))\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, ControlMessage.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions): ControlMessage => {\n return decodeMessage(buf, ControlMessage.codec(), opts)\n }\n }\n\n export interface ControlIHave {\n topicID?: string\n messageIDs: Uint8Array[]\n }\n\n export namespace ControlIHave {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.topicID != null) {\n w.uint32(10)\n w.string(obj.topicID)\n }\n\n if (obj.messageIDs != null) {\n for (const value of obj.messageIDs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n messageIDs: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string()\n break\n }\n case 2: {\n if (opts.limits?.messageIDs != null && obj.messageIDs.length === opts.limits.messageIDs) {\n throw new CodeError('decode error - map field \"messageIDs\" had too many elements', 'ERR_MAX_LENGTH')\n }\n\n obj.messageIDs.push(reader.bytes())\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, ControlIHave.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions): ControlIHave => {\n return decodeMessage(buf, ControlIHave.codec(), opts)\n }\n }\n\n export interface ControlIWant {\n messageIDs: Uint8Array[]\n }\n\n export namespace ControlIWant {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.messageIDs != null) {\n for (const value of obj.messageIDs) {\n w.uint32(10)\n w.bytes(value)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n messageIDs: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.messageIDs != null && obj.messageIDs.length === opts.limits.messageIDs) {\n throw new CodeError('decode error - map field \"messageIDs\" had too many elements', 'ERR_MAX_LENGTH')\n }\n\n obj.messageIDs.push(reader.bytes())\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, ControlIWant.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions): ControlIWant => {\n return decodeMessage(buf, ControlIWant.codec(), opts)\n }\n }\n\n export interface ControlGraft {\n topicID?: string\n }\n\n export namespace ControlGraft {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.topicID != null) {\n w.uint32(10)\n w.string(obj.topicID)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, ControlGraft.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions): ControlGraft => {\n return decodeMessage(buf, ControlGraft.codec(), opts)\n }\n }\n\n export interface ControlPrune {\n topicID?: string\n peers: RPC.PeerInfo[]\n backoff?: number\n }\n\n export namespace ControlPrune {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.topicID != null) {\n w.uint32(10)\n w.string(obj.topicID)\n }\n\n if (obj.peers != null) {\n for (const value of obj.peers) {\n w.uint32(18)\n RPC.PeerInfo.codec().encode(value, w)\n }\n }\n\n if (obj.backoff != null) {\n w.uint32(24)\n w.uint64Number(obj.backoff)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n peers: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string()\n break\n }\n case 2: {\n if (opts.limits?.peers != null && obj.peers.length === opts.limits.peers) {\n throw new CodeError('decode error - map field \"peers\" had too many elements', 'ERR_MAX_LENGTH')\n }\n\n obj.peers.push(RPC.PeerInfo.codec().decode(reader, reader.uint32()))\n break\n }\n case 3: {\n obj.backoff = reader.uint64Number()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, ControlPrune.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions): ControlPrune => {\n return decodeMessage(buf, ControlPrune.codec(), opts)\n }\n }\n\n export interface PeerInfo {\n peerID?: Uint8Array\n signedPeerRecord?: Uint8Array\n }\n\n export namespace PeerInfo {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.peerID != null) {\n w.uint32(10)\n w.bytes(obj.peerID)\n }\n\n if (obj.signedPeerRecord != null) {\n w.uint32(18)\n w.bytes(obj.signedPeerRecord)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.peerID = reader.bytes()\n break\n }\n case 2: {\n obj.signedPeerRecord = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PeerInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions): PeerInfo => {\n return decodeMessage(buf, PeerInfo.codec(), opts)\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.subscriptions != null) {\n for (const value of obj.subscriptions) {\n w.uint32(10)\n RPC.SubOpts.codec().encode(value, w)\n }\n }\n\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(18)\n RPC.Message.codec().encode(value, w)\n }\n }\n\n if (obj.control != null) {\n w.uint32(26)\n RPC.ControlMessage.codec().encode(obj.control, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n subscriptions: [],\n messages: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.subscriptions != null && obj.subscriptions.length === opts.limits.subscriptions) {\n throw new CodeError('decode error - map field \"subscriptions\" had too many elements', 'ERR_MAX_LENGTH')\n }\n\n obj.subscriptions.push(RPC.SubOpts.codec().decode(reader, reader.uint32()))\n break\n }\n case 2: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new CodeError('decode error - map field \"messages\" had too many elements', 'ERR_MAX_LENGTH')\n }\n\n obj.messages.push(RPC.Message.codec().decode(reader, reader.uint32()))\n break\n }\n case 3: {\n obj.control = RPC.ControlMessage.codec().decode(reader, reader.uint32())\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, RPC.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions): RPC => {\n return decodeMessage(buf, RPC.codec(), opts)\n }\n}\n","import { type Message, TopicValidatorResult, type PrivateKey, type PeerId } from '@libp2p/interface'\nimport type { RPC } from './message/rpc.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport type MsgIdStr = string\nexport type PeerIdStr = string\nexport type TopicStr = string\nexport type IPStr = string\n\nexport interface AddrInfo {\n id: PeerId\n addrs: Multiaddr[]\n}\n\n/**\n * Compute a local non-spec'ed msg-id for faster de-duplication of seen messages.\n * Used exclusively for a local seen_cache\n */\nexport interface FastMsgIdFn { (msg: RPC.Message): string | number }\n\n/**\n * By default, gossipsub only provide a browser friendly function to convert Uint8Array message id to string.\n * Application could use this option to provide a more efficient function.\n */\nexport interface MsgIdToStrFn { (msgId: Uint8Array): string }\n\n/**\n * Compute spec'ed msg-id. Used for IHAVE / IWANT messages\n */\nexport interface MsgIdFn {\n (msg: Message): Promise | Uint8Array\n}\n\nexport interface DataTransform {\n /**\n * Takes the data published by peers on a topic and transforms the data.\n * Should be the reverse of outboundTransform(). Example:\n * - `inboundTransform()`: decompress snappy payload\n * - `outboundTransform()`: compress snappy payload\n */\n inboundTransform(topic: TopicStr, data: Uint8Array): Uint8Array\n\n /**\n * Takes the data to be published (a topic and associated data) transforms the data. The\n * transformed data will then be used to create a `RawGossipsubMessage` to be sent to peers.\n */\n outboundTransform(topic: TopicStr, data: Uint8Array): Uint8Array\n}\n\nexport enum SignaturePolicy {\n /**\n * On the producing side:\n * - Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * - Enforce the fields to be present, reject otherwise.\n * - Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\n StrictSign = 'StrictSign',\n /**\n * On the producing side:\n * - Build messages without the signature, key, from and seqno fields.\n * - The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * - Enforce the fields to be absent, reject otherwise.\n * - Propagate only if the fields are absent, reject otherwise.\n * - A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\n StrictNoSign = 'StrictNoSign'\n}\n\nexport interface PublishOpts {\n allowPublishToZeroPeers?: boolean\n ignoreDuplicatePublishError?: boolean\n /** serialize message once and send to all peers without control messages */\n batchPublish?: boolean\n}\n\nexport enum PublishConfigType {\n Signing,\n Anonymous\n}\n\nexport type PublishConfig =\n | {\n type: PublishConfigType.Signing\n author: PeerId\n key: Uint8Array\n privateKey: PrivateKey\n }\n | { type: PublishConfigType.Anonymous }\n\nexport type RejectReasonObj =\n | { reason: RejectReason.Error, error: ValidateError }\n | { reason: Exclude }\n\nexport enum RejectReason {\n /**\n * The message failed the configured validation during decoding.\n * SelfOrigin is considered a ValidationError\n */\n Error = 'error',\n /**\n * Custom validator fn reported status IGNORE.\n */\n Ignore = 'ignore',\n /**\n * Custom validator fn reported status REJECT.\n */\n Reject = 'reject',\n /**\n * The peer that sent the message OR the source from field is blacklisted.\n * Causes messages to be ignored, not penalized, neither do score record creation.\n */\n Blacklisted = 'blacklisted'\n}\n\nexport enum ValidateError {\n /// The message has an invalid signature,\n InvalidSignature = 'invalid_signature',\n /// The sequence number was the incorrect size\n InvalidSeqno = 'invalid_seqno',\n /// The PeerId was invalid\n InvalidPeerId = 'invalid_peerid',\n /// Signature existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n SignaturePresent = 'signature_present',\n /// Sequence number existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n SeqnoPresent = 'seqno_present',\n /// Message source existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n FromPresent = 'from_present',\n /// The data transformation failed.\n TransformFailed = 'transform_failed'\n}\n\nexport enum MessageStatus {\n duplicate = 'duplicate',\n invalid = 'invalid',\n valid = 'valid'\n}\n\n/**\n * Store both Uint8Array and string message id so that we don't have to convert data between the two.\n * See https://github.com/ChainSafe/js-libp2p-gossipsub/pull/274\n */\nexport interface MessageId {\n msgId: Uint8Array\n msgIdStr: MsgIdStr\n}\n\n/**\n * Typesafe conversion of MessageAcceptance -> RejectReason. TS ensures all values covered\n */\nexport function rejectReasonFromAcceptance (\n acceptance: Exclude\n): RejectReason.Ignore | RejectReason.Reject {\n switch (acceptance) {\n case TopicValidatorResult.Ignore:\n return RejectReason.Ignore\n case TopicValidatorResult.Reject:\n return RejectReason.Reject\n default:\n throw new Error('Unreachable')\n }\n}\n","import { TopicValidatorResult } from '@libp2p/interface'\nimport {\n MessageStatus,\n type PeerIdStr,\n RejectReason,\n type RejectReasonObj,\n type TopicStr,\n type ValidateError\n} from './types.js'\nimport type { RPC } from './message/rpc.js'\nimport type { PeerScoreThresholds } from './score/peer-score-thresholds.js'\n\n/** Topic label as provided in `topicStrToLabel` */\nexport type TopicLabel = string\nexport type TopicStrToLabel = Map\n\nexport enum MessageSource {\n forward = 'forward',\n publish = 'publish'\n}\n\ntype NoLabels = Record\ntype LabelsGeneric = Record\ntype LabelKeys = Extract\ninterface CollectFn { (metric: Gauge): void }\n\nexport interface Gauge {\n inc: NoLabels extends Labels ? (value?: number) => void : (labels: Labels, value?: number) => void\n set: NoLabels extends Labels ? (value: number) => void : (labels: Labels, value: number) => void\n\n addCollect(collectFn: CollectFn): void\n}\n\nexport interface Histogram {\n startTimer(): () => void\n\n observe: NoLabels extends Labels ? (value: number) => void : (labels: Labels, value: number) => void\n\n reset(): void\n}\n\nexport interface AvgMinMax {\n set: NoLabels extends Labels ? (values: number[]) => void : (labels: Labels, values: number[]) => void\n}\n\nexport type GaugeConfig = {\n name: string\n help: string\n} & (NoLabels extends Labels ? { labelNames?: never } : { labelNames: [LabelKeys, ...Array>] })\n\nexport type HistogramConfig = GaugeConfig & {\n buckets?: number[]\n}\n\nexport type AvgMinMaxConfig = GaugeConfig\n\nexport interface MetricsRegister {\n gauge(config: GaugeConfig): Gauge\n histogram(config: HistogramConfig): Histogram\n avgMinMax(config: AvgMinMaxConfig): AvgMinMax\n}\n\nexport enum InclusionReason {\n /** Peer was a fanaout peer. */\n Fanout = 'fanout',\n /** Included from random selection. */\n Random = 'random',\n /** Peer subscribed. */\n Subscribed = 'subscribed',\n /** On heartbeat, peer was included to fill the outbound quota. */\n Outbound = 'outbound',\n /** On heartbeat, not enough peers in mesh */\n NotEnough = 'not_enough',\n /** On heartbeat opportunistic grafting due to low mesh score */\n Opportunistic = 'opportunistic'\n}\n\n/// Reasons why a peer was removed from the mesh.\nexport enum ChurnReason {\n /// Peer disconnected.\n Dc = 'disconnected',\n /// Peer had a bad score.\n BadScore = 'bad_score',\n /// Peer sent a PRUNE.\n Prune = 'prune',\n /// Too many peers.\n Excess = 'excess'\n}\n\n/// Kinds of reasons a peer's score has been penalized\nexport enum ScorePenalty {\n /// A peer grafted before waiting the back-off time.\n GraftBackoff = 'graft_backoff',\n /// A Peer did not respond to an IWANT request in time.\n BrokenPromise = 'broken_promise',\n /// A Peer did not send enough messages as expected.\n MessageDeficit = 'message_deficit',\n /// Too many peers under one IP address.\n IPColocation = 'IP_colocation'\n}\n\nexport enum IHaveIgnoreReason {\n LowScore = 'low_score',\n MaxIhave = 'max_ihave',\n MaxIasked = 'max_iasked'\n}\n\nexport enum ScoreThreshold {\n graylist = 'graylist',\n publish = 'publish',\n gossip = 'gossip',\n mesh = 'mesh'\n}\n\nexport type PeersByScoreThreshold = Record\n\nexport interface ToSendGroupCount {\n direct: number\n floodsub: number\n mesh: number\n fanout: number\n}\n\nexport interface ToAddGroupCount {\n fanout: number\n random: number\n}\n\nexport type PromiseDeliveredStats =\n | { expired: false, requestedCount: number, maxDeliverMs: number }\n | { expired: true, maxDeliverMs: number }\n\nexport interface TopicScoreWeights { p1w: T, p2w: T, p3w: T, p3bw: T, p4w: T }\nexport interface ScoreWeights {\n byTopic: Map>\n p5w: T\n p6w: T\n p7w: T\n score: T\n}\n\nexport type Metrics = ReturnType\n\n/**\n * A collection of metrics used throughout the Gossipsub behaviour.\n * NOTE: except for special reasons, do not add more than 1 label for frequent metrics,\n * there's a performance penalty as of June 2023.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type\nexport function getMetrics (\n register: MetricsRegister,\n topicStrToLabel: TopicStrToLabel,\n opts: { gossipPromiseExpireSec: number, behaviourPenaltyThreshold: number, maxMeshMessageDeliveriesWindowSec: number }\n) {\n // Using function style instead of class to prevent having to re-declare all MetricsPrometheus types.\n\n return {\n /* Metrics for static config */\n protocolsEnabled: register.gauge<{ protocol: string }>({\n name: 'gossipsub_protocol',\n help: 'Status of enabled protocols',\n labelNames: ['protocol']\n }),\n\n /* Metrics per known topic */\n /**\n * Status of our subscription to this topic. This metric allows analyzing other topic metrics\n * filtered by our current subscription status.\n * = rust-libp2p `topic_subscription_status` */\n topicSubscriptionStatus: register.gauge<{ topicStr: TopicStr }>({\n name: 'gossipsub_topic_subscription_status',\n help: 'Status of our subscription to this topic',\n labelNames: ['topicStr']\n }),\n /** Number of peers subscribed to each topic. This allows us to analyze a topic's behaviour\n * regardless of our subscription status. */\n topicPeersCount: register.gauge<{ topicStr: TopicStr }>({\n name: 'gossipsub_topic_peer_count',\n help: 'Number of peers subscribed to each topic',\n labelNames: ['topicStr']\n }),\n\n /* Metrics regarding mesh state */\n /**\n * Number of peers in our mesh. This metric should be updated with the count of peers for a\n * topic in the mesh regardless of inclusion and churn events.\n * = rust-libp2p `mesh_peer_counts` */\n meshPeerCounts: register.gauge<{ topicStr: TopicStr }>({\n name: 'gossipsub_mesh_peer_count',\n help: 'Number of peers in our mesh',\n labelNames: ['topicStr']\n }),\n /**\n * Number of times we include peers in a topic mesh for different reasons.\n * = rust-libp2p `mesh_peer_inclusion_events` */\n meshPeerInclusionEventsFanout: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_mesh_peer_inclusion_events_fanout_total',\n help: 'Number of times we include peers in a topic mesh for fanout reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsRandom: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_mesh_peer_inclusion_events_random_total',\n help: 'Number of times we include peers in a topic mesh for random reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsSubscribed: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_mesh_peer_inclusion_events_subscribed_total',\n help: 'Number of times we include peers in a topic mesh for subscribed reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsOutbound: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_mesh_peer_inclusion_events_outbound_total',\n help: 'Number of times we include peers in a topic mesh for outbound reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsNotEnough: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_mesh_peer_inclusion_events_not_enough_total',\n help: 'Number of times we include peers in a topic mesh for not_enough reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsOpportunistic: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_mesh_peer_inclusion_events_opportunistic_total',\n help: 'Number of times we include peers in a topic mesh for opportunistic reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsUnknown: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_mesh_peer_inclusion_events_unknown_total',\n help: 'Number of times we include peers in a topic mesh for unknown reasons',\n labelNames: ['topic']\n }),\n /**\n * Number of times we remove peers in a topic mesh for different reasons.\n * = rust-libp2p `mesh_peer_churn_events` */\n meshPeerChurnEventsDisconnected: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_peer_churn_events_disconnected_total',\n help: 'Number of times we remove peers in a topic mesh for disconnected reasons',\n labelNames: ['topic']\n }),\n meshPeerChurnEventsBadScore: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_peer_churn_events_bad_score_total',\n help: 'Number of times we remove peers in a topic mesh for bad_score reasons',\n labelNames: ['topic']\n }),\n meshPeerChurnEventsPrune: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_peer_churn_events_prune_total',\n help: 'Number of times we remove peers in a topic mesh for prune reasons',\n labelNames: ['topic']\n }),\n meshPeerChurnEventsExcess: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_peer_churn_events_excess_total',\n help: 'Number of times we remove peers in a topic mesh for excess reasons',\n labelNames: ['topic']\n }),\n meshPeerChurnEventsUnknown: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_peer_churn_events_unknown_total',\n help: 'Number of times we remove peers in a topic mesh for unknown reasons',\n labelNames: ['topic']\n }),\n\n /* General Metrics */\n /**\n * Gossipsub supports floodsub, gossipsub v1.0 and gossipsub v1.1. Peers are classified based\n * on which protocol they support. This metric keeps track of the number of peers that are\n * connected of each type. */\n peersPerProtocol: register.gauge<{ protocol: string }>({\n name: 'gossipsub_peers_per_protocol_count',\n help: 'Peers connected for each topic',\n labelNames: ['protocol']\n }),\n /** The time it takes to complete one iteration of the heartbeat. */\n heartbeatDuration: register.histogram({\n name: 'gossipsub_heartbeat_duration_seconds',\n help: 'The time it takes to complete one iteration of the heartbeat',\n // Should take <10ms, over 1s it's a huge issue that needs debugging, since a heartbeat will be cancelled\n buckets: [0.01, 0.1, 1]\n }),\n /** Heartbeat run took longer than heartbeat interval so next is skipped */\n heartbeatSkipped: register.gauge({\n name: 'gossipsub_heartbeat_skipped',\n help: 'Heartbeat run took longer than heartbeat interval so next is skipped'\n }),\n\n /**\n * Message validation results for each topic.\n * Invalid == Reject?\n * = rust-libp2p `invalid_messages`, `accepted_messages`, `ignored_messages`, `rejected_messages` */\n acceptedMessagesTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_accepted_messages_total',\n help: 'Total accepted messages for each topic',\n labelNames: ['topic']\n }),\n ignoredMessagesTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_ignored_messages_total',\n help: 'Total ignored messages for each topic',\n labelNames: ['topic']\n }),\n rejectedMessagesTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_rejected_messages_total',\n help: 'Total rejected messages for each topic',\n labelNames: ['topic']\n }),\n unknownValidationResultsTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_unknown_validation_results_total',\n help: 'Total unknown validation results for each topic',\n labelNames: ['topic']\n }),\n /**\n * When the user validates a message, it tries to re propagate it to its mesh peers. If the\n * message expires from the memcache before it can be validated, we count this a cache miss\n * and it is an indicator that the memcache size should be increased.\n * = rust-libp2p `mcache_misses` */\n asyncValidationMcacheHit: register.gauge<{ hit: 'hit' | 'miss' }>({\n name: 'gossipsub_async_validation_mcache_hit_total',\n help: 'Async validation result reported by the user layer',\n labelNames: ['hit']\n }),\n\n asyncValidationDelayFromFirstSeenSec: register.histogram({\n name: 'gossipsub_async_validation_delay_from_first_seen',\n help: 'Async validation report delay from first seen in second',\n buckets: [0.01, 0.03, 0.1, 0.3, 1, 3, 10]\n }),\n\n asyncValidationUnknownFirstSeen: register.gauge({\n name: 'gossipsub_async_validation_unknown_first_seen_count_total',\n help: 'Async validation report unknown first seen value for message'\n }),\n\n // peer stream\n peerReadStreamError: register.gauge({\n name: 'gossipsub_peer_read_stream_err_count_total',\n help: 'Peer read stream error'\n }),\n\n // RPC outgoing. Track byte length + data structure sizes\n rpcRecvBytes: register.gauge({ name: 'gossipsub_rpc_recv_bytes_total', help: 'RPC recv' }),\n rpcRecvCount: register.gauge({ name: 'gossipsub_rpc_recv_count_total', help: 'RPC recv' }),\n rpcRecvSubscription: register.gauge({ name: 'gossipsub_rpc_recv_subscription_total', help: 'RPC recv' }),\n rpcRecvMessage: register.gauge({ name: 'gossipsub_rpc_recv_message_total', help: 'RPC recv' }),\n rpcRecvControl: register.gauge({ name: 'gossipsub_rpc_recv_control_total', help: 'RPC recv' }),\n rpcRecvIHave: register.gauge({ name: 'gossipsub_rpc_recv_ihave_total', help: 'RPC recv' }),\n rpcRecvIWant: register.gauge({ name: 'gossipsub_rpc_recv_iwant_total', help: 'RPC recv' }),\n rpcRecvGraft: register.gauge({ name: 'gossipsub_rpc_recv_graft_total', help: 'RPC recv' }),\n rpcRecvPrune: register.gauge({ name: 'gossipsub_rpc_recv_prune_total', help: 'RPC recv' }),\n rpcDataError: register.gauge({ name: 'gossipsub_rpc_data_err_count_total', help: 'RPC data error' }),\n rpcRecvError: register.gauge({ name: 'gossipsub_rpc_recv_err_count_total', help: 'RPC recv error' }),\n\n /** Total count of RPC dropped because acceptFrom() == false */\n rpcRecvNotAccepted: register.gauge({\n name: 'gossipsub_rpc_rcv_not_accepted_total',\n help: 'Total count of RPC dropped because acceptFrom() == false'\n }),\n\n // RPC incoming. Track byte length + data structure sizes\n rpcSentBytes: register.gauge({ name: 'gossipsub_rpc_sent_bytes_total', help: 'RPC sent' }),\n rpcSentCount: register.gauge({ name: 'gossipsub_rpc_sent_count_total', help: 'RPC sent' }),\n rpcSentSubscription: register.gauge({ name: 'gossipsub_rpc_sent_subscription_total', help: 'RPC sent' }),\n rpcSentMessage: register.gauge({ name: 'gossipsub_rpc_sent_message_total', help: 'RPC sent' }),\n rpcSentControl: register.gauge({ name: 'gossipsub_rpc_sent_control_total', help: 'RPC sent' }),\n rpcSentIHave: register.gauge({ name: 'gossipsub_rpc_sent_ihave_total', help: 'RPC sent' }),\n rpcSentIWant: register.gauge({ name: 'gossipsub_rpc_sent_iwant_total', help: 'RPC sent' }),\n rpcSentGraft: register.gauge({ name: 'gossipsub_rpc_sent_graft_total', help: 'RPC sent' }),\n rpcSentPrune: register.gauge({ name: 'gossipsub_rpc_sent_prune_total', help: 'RPC sent' }),\n\n // publish message. Track peers sent to and bytes\n /** Total count of msg published by topic */\n msgPublishCount: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_count_total',\n help: 'Total count of msg published by topic',\n labelNames: ['topic']\n }),\n /** Total count of peers that we publish a msg to */\n msgPublishPeersByTopic: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_peers_total',\n help: 'Total count of peers that we publish a msg to',\n labelNames: ['topic']\n }),\n /** Total count of peers (by group) that we publish a msg to */\n directPeersPublishedTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_direct_peers_published_total',\n help: 'Total direct peers that we publish a msg to',\n labelNames: ['topic']\n }),\n floodsubPeersPublishedTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_floodsub_peers_published_total',\n help: 'Total floodsub peers that we publish a msg to',\n labelNames: ['topic']\n }),\n meshPeersPublishedTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_mesh_peers_published_total',\n help: 'Total mesh peers that we publish a msg to',\n labelNames: ['topic']\n }),\n fanoutPeersPublishedTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_fanout_peers_published_total',\n help: 'Total fanout peers that we publish a msg to',\n labelNames: ['topic']\n }),\n /** Total count of msg publish data.length bytes */\n msgPublishBytes: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_bytes_total',\n help: 'Total count of msg publish data.length bytes',\n labelNames: ['topic']\n }),\n /** Total time in seconds to publish a message */\n msgPublishTime: register.histogram<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_seconds',\n help: 'Total time in seconds to publish a message',\n buckets: [0.001, 0.002, 0.005, 0.01, 0.1, 0.5, 1],\n labelNames: ['topic']\n }),\n\n /** Total count of msg forwarded by topic */\n msgForwardCount: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_forward_count_total',\n help: 'Total count of msg forwarded by topic',\n labelNames: ['topic']\n }),\n /** Total count of peers that we forward a msg to */\n msgForwardPeers: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_forward_peers_total',\n help: 'Total count of peers that we forward a msg to',\n labelNames: ['topic']\n }),\n\n /** Total count of recv msgs before any validation */\n msgReceivedPreValidation: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_received_prevalidation_total',\n help: 'Total count of recv msgs before any validation',\n labelNames: ['topic']\n }),\n /** Total count of recv msgs error */\n msgReceivedError: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_received_error_total',\n help: 'Total count of recv msgs error',\n labelNames: ['topic']\n }),\n /** Tracks distribution of recv msgs by duplicate, invalid, valid */\n prevalidationInvalidTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_pre_validation_invalid_total',\n help: 'Total count of invalid messages received',\n labelNames: ['topic']\n }),\n prevalidationValidTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_pre_validation_valid_total',\n help: 'Total count of valid messages received',\n labelNames: ['topic']\n }),\n prevalidationDuplicateTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_pre_validation_duplicate_total',\n help: 'Total count of duplicate messages received',\n labelNames: ['topic']\n }),\n prevalidationUnknownTotal: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_pre_validation_unknown_status_total',\n help: 'Total count of unknown_status messages received',\n labelNames: ['topic']\n }),\n /** Tracks specific reason of invalid */\n msgReceivedInvalid: register.gauge<{ error: RejectReason | ValidateError }>({\n name: 'gossipsub_msg_received_invalid_total',\n help: 'Tracks specific reason of invalid',\n labelNames: ['error']\n }),\n msgReceivedInvalidByTopic: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_received_invalid_by_topic_total',\n help: 'Tracks specific invalid message by topic',\n labelNames: ['topic']\n }),\n /** Track duplicate message delivery time */\n duplicateMsgDeliveryDelay: register.histogram<{ topic: TopicLabel }>({\n name: 'gossisub_duplicate_msg_delivery_delay_seconds',\n help: 'Time since the 1st duplicated message validated',\n labelNames: ['topic'],\n buckets: [\n 0.25 * opts.maxMeshMessageDeliveriesWindowSec,\n 0.5 * opts.maxMeshMessageDeliveriesWindowSec,\n Number(opts.maxMeshMessageDeliveriesWindowSec),\n 2 * opts.maxMeshMessageDeliveriesWindowSec,\n 4 * opts.maxMeshMessageDeliveriesWindowSec\n ]\n }),\n /** Total count of late msg delivery total by topic */\n duplicateMsgLateDelivery: register.gauge<{ topic: TopicLabel }>({\n name: 'gossisub_duplicate_msg_late_delivery_total',\n help: 'Total count of late duplicate message delivery by topic, which triggers P3 penalty',\n labelNames: ['topic']\n }),\n\n duplicateMsgIgnored: register.gauge<{ topic: TopicLabel }>({\n name: 'gossisub_ignored_published_duplicate_msgs_total',\n help: 'Total count of published duplicate message ignored by topic',\n labelNames: ['topic']\n }),\n\n /* Metrics related to scoring */\n /** Total times score() is called */\n scoreFnCalls: register.gauge({\n name: 'gossipsub_score_fn_calls_total',\n help: 'Total times score() is called'\n }),\n /** Total times score() call actually computed computeScore(), no cache */\n scoreFnRuns: register.gauge({\n name: 'gossipsub_score_fn_runs_total',\n help: 'Total times score() call actually computed computeScore(), no cache'\n }),\n scoreCachedDelta: register.histogram({\n name: 'gossipsub_score_cache_delta',\n help: 'Delta of score between cached values that expired',\n buckets: [10, 100, 1000]\n }),\n /** Current count of peers by score threshold */\n peersByScoreThreshold: register.gauge<{ threshold: ScoreThreshold }>({\n name: 'gossipsub_peers_by_score_threshold_count',\n help: 'Current count of peers by score threshold',\n labelNames: ['threshold']\n }),\n score: register.avgMinMax({\n name: 'gossipsub_score',\n help: 'Avg min max of gossip scores'\n }),\n /**\n * Separate score weights\n * Need to use 2-label metrics in this case to debug the score weights\n **/\n scoreWeights: register.avgMinMax<{ topic?: TopicLabel, p: string }>({\n name: 'gossipsub_score_weights',\n help: 'Separate score weights',\n labelNames: ['topic', 'p']\n }),\n /** Histogram of the scores for each mesh topic. */\n // TODO: Not implemented\n scorePerMesh: register.avgMinMax<{ topic: TopicLabel }>({\n name: 'gossipsub_score_per_mesh',\n help: 'Histogram of the scores for each mesh topic',\n labelNames: ['topic']\n }),\n /** A counter of the kind of penalties being applied to peers. */\n // TODO: Not fully implemented\n scoringPenalties: register.gauge<{ penalty: ScorePenalty }>({\n name: 'gossipsub_scoring_penalties_total',\n help: 'A counter of the kind of penalties being applied to peers',\n labelNames: ['penalty']\n }),\n behaviourPenalty: register.histogram({\n name: 'gossipsub_peer_stat_behaviour_penalty',\n help: 'Current peer stat behaviour_penalty at each scrape',\n buckets: [\n 0.25 * opts.behaviourPenaltyThreshold,\n 0.5 * opts.behaviourPenaltyThreshold,\n Number(opts.behaviourPenaltyThreshold),\n 2 * opts.behaviourPenaltyThreshold,\n 4 * opts.behaviourPenaltyThreshold\n ]\n }),\n\n // TODO:\n // - iasked per peer (on heartbeat)\n // - when promise is resolved, track messages from promises\n\n /** Total received IHAVE messages that we ignore for some reason */\n ihaveRcvIgnored: register.gauge<{ reason: IHaveIgnoreReason }>({\n name: 'gossipsub_ihave_rcv_ignored_total',\n help: 'Total received IHAVE messages that we ignore for some reason',\n labelNames: ['reason']\n }),\n /** Total received IHAVE messages by topic */\n ihaveRcvMsgids: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_ihave_rcv_msgids_total',\n help: 'Total received IHAVE messages by topic',\n labelNames: ['topic']\n }),\n /**\n * Total messages per topic we don't have. Not actual requests.\n * The number of times we have decided that an IWANT control message is required for this\n * topic. A very high metric might indicate an underperforming network.\n * = rust-libp2p `topic_iwant_msgs` */\n ihaveRcvNotSeenMsgids: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_ihave_rcv_not_seen_msgids_total',\n help: 'Total messages per topic we do not have, not actual requests',\n labelNames: ['topic']\n }),\n\n /** Total received IWANT messages by topic */\n iwantRcvMsgids: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_iwant_rcv_msgids_total',\n help: 'Total received IWANT messages by topic',\n labelNames: ['topic']\n }),\n /** Total requested messageIDs that we don't have */\n iwantRcvDonthaveMsgids: register.gauge({\n name: 'gossipsub_iwant_rcv_dont_have_msgids_total',\n help: 'Total requested messageIDs that we do not have'\n }),\n iwantPromiseStarted: register.gauge({\n name: 'gossipsub_iwant_promise_sent_total',\n help: 'Total count of started IWANT promises'\n }),\n /** Total count of resolved IWANT promises */\n iwantPromiseResolved: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_total',\n help: 'Total count of resolved IWANT promises'\n }),\n /** Total count of resolved IWANT promises from duplicate messages */\n iwantPromiseResolvedFromDuplicate: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_from_duplicate_total',\n help: 'Total count of resolved IWANT promises from duplicate messages'\n }),\n /** Total count of peers we have asked IWANT promises that are resolved */\n iwantPromiseResolvedPeers: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_peers',\n help: 'Total count of peers we have asked IWANT promises that are resolved'\n }),\n iwantPromiseBroken: register.gauge({\n name: 'gossipsub_iwant_promise_broken',\n help: 'Total count of broken IWANT promises'\n }),\n iwantMessagePruned: register.gauge({\n name: 'gossipsub_iwant_message_pruned',\n help: 'Total count of pruned IWANT messages'\n }),\n /** Histogram of delivery time of resolved IWANT promises */\n iwantPromiseDeliveryTime: register.histogram({\n name: 'gossipsub_iwant_promise_delivery_seconds',\n help: 'Histogram of delivery time of resolved IWANT promises',\n buckets: [\n 0.5 * opts.gossipPromiseExpireSec,\n Number(opts.gossipPromiseExpireSec),\n 2 * opts.gossipPromiseExpireSec,\n 4 * opts.gossipPromiseExpireSec\n ]\n }),\n iwantPromiseUntracked: register.gauge({\n name: 'gossip_iwant_promise_untracked',\n help: 'Total count of untracked IWANT promise'\n }),\n /** Backoff time */\n connectedPeersBackoffSec: register.histogram({\n name: 'gossipsub_connected_peers_backoff_seconds',\n help: 'Backoff time in seconds',\n // Using 1 seconds as minimum as that's close to the heartbeat duration, no need for more resolution.\n // As per spec, backoff times are 10 seconds for UnsubscribeBackoff and 60 seconds for PruneBackoff.\n // Higher values of 60 seconds should not occur, but we add 120 seconds just in case\n // https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/gossipsub-v1.1.md#overview-of-new-parameters\n buckets: [1, 2, 4, 10, 20, 60, 120]\n }),\n\n /* Data structure sizes */\n /** Unbounded cache sizes */\n cacheSize: register.gauge<{ cache: string }>({\n name: 'gossipsub_cache_size',\n help: 'Unbounded cache sizes',\n labelNames: ['cache']\n }),\n /** Current mcache msg count */\n mcacheSize: register.gauge({\n name: 'gossipsub_mcache_size',\n help: 'Current mcache msg count'\n }),\n mcacheNotValidatedCount: register.gauge({\n name: 'gossipsub_mcache_not_validated_count',\n help: 'Current mcache msg count not validated'\n }),\n\n fastMsgIdCacheCollision: register.gauge({\n name: 'gossipsub_fastmsgid_cache_collision_total',\n help: 'Total count of key collisions on fastmsgid cache put'\n }),\n\n newConnectionCount: register.gauge<{ status: string }>({\n name: 'gossipsub_new_connection_total',\n help: 'Total new connection by status',\n labelNames: ['status']\n }),\n\n topicStrToLabel,\n\n toTopic (topicStr: TopicStr): TopicLabel {\n return this.topicStrToLabel.get(topicStr) ?? topicStr\n },\n\n /** We joined a topic */\n onJoin (topicStr: TopicStr): void {\n this.topicSubscriptionStatus.set({ topicStr }, 1)\n this.meshPeerCounts.set({ topicStr }, 0) // Reset count\n },\n\n /** We left a topic */\n onLeave (topicStr: TopicStr): void {\n this.topicSubscriptionStatus.set({ topicStr }, 0)\n this.meshPeerCounts.set({ topicStr }, 0) // Reset count\n },\n\n /** Register the inclusion of peers in our mesh due to some reason. */\n onAddToMesh (topicStr: TopicStr, reason: InclusionReason, count: number): void {\n const topic = this.toTopic(topicStr)\n switch (reason) {\n case InclusionReason.Fanout:\n this.meshPeerInclusionEventsFanout.inc({ topic }, count)\n break\n case InclusionReason.Random:\n this.meshPeerInclusionEventsRandom.inc({ topic }, count)\n break\n case InclusionReason.Subscribed:\n this.meshPeerInclusionEventsSubscribed.inc({ topic }, count)\n break\n case InclusionReason.Outbound:\n this.meshPeerInclusionEventsOutbound.inc({ topic }, count)\n break\n case InclusionReason.NotEnough:\n this.meshPeerInclusionEventsNotEnough.inc({ topic }, count)\n break\n case InclusionReason.Opportunistic:\n this.meshPeerInclusionEventsOpportunistic.inc({ topic }, count)\n break\n default:\n this.meshPeerInclusionEventsUnknown.inc({ topic }, count)\n break\n }\n },\n\n /** Register the removal of peers in our mesh due to some reason */\n // - remove_peer_from_mesh()\n // - heartbeat() Churn::BadScore\n // - heartbeat() Churn::Excess\n // - on_disconnect() Churn::Ds\n onRemoveFromMesh (topicStr: TopicStr, reason: ChurnReason, count: number): void {\n const topic = this.toTopic(topicStr)\n switch (reason) {\n case ChurnReason.Dc:\n this.meshPeerChurnEventsDisconnected.inc({ topic }, count)\n break\n case ChurnReason.BadScore:\n this.meshPeerChurnEventsBadScore.inc({ topic }, count)\n break\n case ChurnReason.Prune:\n this.meshPeerChurnEventsPrune.inc({ topic }, count)\n break\n case ChurnReason.Excess:\n this.meshPeerChurnEventsExcess.inc({ topic }, count)\n break\n default:\n this.meshPeerChurnEventsUnknown.inc({ topic }, count)\n break\n }\n },\n\n /**\n * Update validation result to metrics\n *\n * @param messageRecord - null means the message's mcache record was not known at the time of acceptance report\n */\n onReportValidation (\n messageRecord: { message: { topic: TopicStr } } | null,\n acceptance: TopicValidatorResult,\n firstSeenTimestampMs: number | null\n ): void {\n this.asyncValidationMcacheHit.inc({ hit: messageRecord != null ? 'hit' : 'miss' })\n\n if (messageRecord != null) {\n const topic = this.toTopic(messageRecord.message.topic)\n switch (acceptance) {\n case TopicValidatorResult.Accept:\n this.acceptedMessagesTotal.inc({ topic })\n break\n case TopicValidatorResult.Ignore:\n this.ignoredMessagesTotal.inc({ topic })\n break\n case TopicValidatorResult.Reject:\n this.rejectedMessagesTotal.inc({ topic })\n break\n default:\n this.unknownValidationResultsTotal.inc({ topic })\n break\n }\n }\n\n if (firstSeenTimestampMs != null) {\n this.asyncValidationDelayFromFirstSeenSec.observe((Date.now() - firstSeenTimestampMs) / 1000)\n } else {\n this.asyncValidationUnknownFirstSeen.inc()\n }\n },\n\n /**\n * - in handle_graft() Penalty::GraftBackoff\n * - in apply_iwant_penalties() Penalty::BrokenPromise\n * - in metric_score() P3 Penalty::MessageDeficit\n * - in metric_score() P6 Penalty::IPColocation\n */\n onScorePenalty (penalty: ScorePenalty): void {\n // Can this be labeled by topic too?\n this.scoringPenalties.inc({ penalty }, 1)\n },\n\n onIhaveRcv (topicStr: TopicStr, ihave: number, idonthave: number): void {\n const topic = this.toTopic(topicStr)\n this.ihaveRcvMsgids.inc({ topic }, ihave)\n this.ihaveRcvNotSeenMsgids.inc({ topic }, idonthave)\n },\n\n onIwantRcv (iwantByTopic: Map, iwantDonthave: number): void {\n for (const [topicStr, iwant] of iwantByTopic) {\n const topic = this.toTopic(topicStr)\n this.iwantRcvMsgids.inc({ topic }, iwant)\n }\n\n this.iwantRcvDonthaveMsgids.inc(iwantDonthave)\n },\n\n onForwardMsg (topicStr: TopicStr, tosendCount: number): void {\n const topic = this.toTopic(topicStr)\n this.msgForwardCount.inc({ topic }, 1)\n this.msgForwardPeers.inc({ topic }, tosendCount)\n },\n\n onPublishMsg (\n topicStr: TopicStr,\n tosendGroupCount: ToSendGroupCount,\n tosendCount: number,\n dataLen: number,\n ms: number\n ): void {\n const topic = this.toTopic(topicStr)\n this.msgPublishCount.inc({ topic }, 1)\n this.msgPublishBytes.inc({ topic }, tosendCount * dataLen)\n this.msgPublishPeersByTopic.inc({ topic }, tosendCount)\n this.directPeersPublishedTotal.inc({ topic }, tosendGroupCount.direct)\n this.floodsubPeersPublishedTotal.inc({ topic }, tosendGroupCount.floodsub)\n this.meshPeersPublishedTotal.inc({ topic }, tosendGroupCount.mesh)\n this.fanoutPeersPublishedTotal.inc({ topic }, tosendGroupCount.fanout)\n this.msgPublishTime.observe({ topic }, ms / 1000)\n },\n\n onMsgRecvPreValidation (topicStr: TopicStr): void {\n const topic = this.toTopic(topicStr)\n this.msgReceivedPreValidation.inc({ topic }, 1)\n },\n\n onMsgRecvError (topicStr: TopicStr): void {\n const topic = this.toTopic(topicStr)\n this.msgReceivedError.inc({ topic }, 1)\n },\n\n onPrevalidationResult (topicStr: TopicStr, status: MessageStatus): void {\n const topic = this.toTopic(topicStr)\n switch (status) {\n case MessageStatus.duplicate:\n this.prevalidationDuplicateTotal.inc({ topic })\n break\n case MessageStatus.invalid:\n this.prevalidationInvalidTotal.inc({ topic })\n break\n case MessageStatus.valid:\n this.prevalidationValidTotal.inc({ topic })\n break\n default:\n this.prevalidationUnknownTotal.inc({ topic })\n break\n }\n },\n\n onMsgRecvInvalid (topicStr: TopicStr, reason: RejectReasonObj): void {\n const topic = this.toTopic(topicStr)\n\n const error = reason.reason === RejectReason.Error ? reason.error : reason.reason\n this.msgReceivedInvalid.inc({ error }, 1)\n this.msgReceivedInvalidByTopic.inc({ topic }, 1)\n },\n\n onDuplicateMsgDelivery (topicStr: TopicStr, deliveryDelayMs: number, isLateDelivery: boolean): void {\n const topic = this.toTopic(topicStr)\n this.duplicateMsgDeliveryDelay.observe({ topic }, deliveryDelayMs / 1000)\n if (isLateDelivery) {\n this.duplicateMsgLateDelivery.inc({ topic }, 1)\n }\n },\n\n onPublishDuplicateMsg (topicStr: TopicStr): void {\n const topic = this.toTopic(topicStr)\n this.duplicateMsgIgnored.inc({ topic }, 1)\n },\n\n onPeerReadStreamError (): void {\n this.peerReadStreamError.inc(1)\n },\n\n onRpcRecvError (): void {\n this.rpcRecvError.inc(1)\n },\n\n onRpcDataError (): void {\n this.rpcDataError.inc(1)\n },\n\n onRpcRecv (rpc: RPC, rpcBytes: number): void {\n this.rpcRecvBytes.inc(rpcBytes)\n this.rpcRecvCount.inc(1)\n if (rpc.subscriptions != null) this.rpcRecvSubscription.inc(rpc.subscriptions.length)\n if (rpc.messages != null) this.rpcRecvMessage.inc(rpc.messages.length)\n if (rpc.control != null) {\n this.rpcRecvControl.inc(1)\n if (rpc.control.ihave != null) this.rpcRecvIHave.inc(rpc.control.ihave.length)\n if (rpc.control.iwant != null) this.rpcRecvIWant.inc(rpc.control.iwant.length)\n if (rpc.control.graft != null) this.rpcRecvGraft.inc(rpc.control.graft.length)\n if (rpc.control.prune != null) this.rpcRecvPrune.inc(rpc.control.prune.length)\n }\n },\n\n onRpcSent (rpc: RPC, rpcBytes: number): void {\n this.rpcSentBytes.inc(rpcBytes)\n this.rpcSentCount.inc(1)\n if (rpc.subscriptions != null) this.rpcSentSubscription.inc(rpc.subscriptions.length)\n if (rpc.messages != null) this.rpcSentMessage.inc(rpc.messages.length)\n if (rpc.control != null) {\n const ihave = rpc.control.ihave?.length ?? 0\n const iwant = rpc.control.iwant?.length ?? 0\n const graft = rpc.control.graft?.length ?? 0\n const prune = rpc.control.prune?.length ?? 0\n if (ihave > 0) this.rpcSentIHave.inc(ihave)\n if (iwant > 0) this.rpcSentIWant.inc(iwant)\n if (graft > 0) this.rpcSentGraft.inc(graft)\n if (prune > 0) this.rpcSentPrune.inc(prune)\n if (ihave > 0 || iwant > 0 || graft > 0 || prune > 0) this.rpcSentControl.inc(1)\n }\n },\n\n registerScores (scores: number[], scoreThresholds: PeerScoreThresholds): void {\n let graylist = 0\n let publish = 0\n let gossip = 0\n let mesh = 0\n\n for (const score of scores) {\n if (score >= scoreThresholds.graylistThreshold) graylist++\n if (score >= scoreThresholds.publishThreshold) publish++\n if (score >= scoreThresholds.gossipThreshold) gossip++\n if (score >= 0) mesh++\n }\n\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.graylist }, graylist)\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.publish }, publish)\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.gossip }, gossip)\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.mesh }, mesh)\n\n // Register full score too\n this.score.set(scores)\n },\n\n registerScoreWeights (sw: ScoreWeights): void {\n for (const [topic, wsTopic] of sw.byTopic) {\n this.scoreWeights.set({ topic, p: 'p1' }, wsTopic.p1w)\n this.scoreWeights.set({ topic, p: 'p2' }, wsTopic.p2w)\n this.scoreWeights.set({ topic, p: 'p3' }, wsTopic.p3w)\n this.scoreWeights.set({ topic, p: 'p3b' }, wsTopic.p3bw)\n this.scoreWeights.set({ topic, p: 'p4' }, wsTopic.p4w)\n }\n\n this.scoreWeights.set({ p: 'p5' }, sw.p5w)\n this.scoreWeights.set({ p: 'p6' }, sw.p6w)\n this.scoreWeights.set({ p: 'p7' }, sw.p7w)\n },\n\n registerScorePerMesh (mesh: Map>, scoreByPeer: Map): void {\n const peersPerTopicLabel = new Map>()\n\n mesh.forEach((peers, topicStr) => {\n // Aggregate by known topicLabel or throw to 'unknown'. This prevent too high cardinality\n const topicLabel = this.topicStrToLabel.get(topicStr) ?? 'unknown'\n let peersInMesh = peersPerTopicLabel.get(topicLabel)\n if (peersInMesh == null) {\n peersInMesh = new Set()\n peersPerTopicLabel.set(topicLabel, peersInMesh)\n }\n peers.forEach((p) => peersInMesh?.add(p))\n })\n\n for (const [topic, peers] of peersPerTopicLabel) {\n const meshScores: number[] = []\n peers.forEach((peer) => {\n meshScores.push(scoreByPeer.get(peer) ?? 0)\n })\n this.scorePerMesh.set({ topic }, meshScores)\n }\n }\n }\n}\n","import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n\n this.code = code\n }\n}\n","import type { RPC } from './message/rpc.js'\nimport type { MessageId, MsgIdStr, PeerIdStr, TopicStr, MsgIdToStrFn } from './types.js'\n\nexport type CacheEntry = MessageId & {\n topic: TopicStr\n}\n\nexport type MessageCacheRecord = Pick\n\ninterface MessageCacheEntry {\n message: RPC.Message\n /**\n * Tracks if the message has been validated by the app layer and thus forwarded\n */\n validated: boolean\n /**\n * Tracks peers that sent this message before it has been validated by the app layer\n */\n originatingPeers: Set\n /**\n * For every message and peer the number of times this peer asked for the message\n */\n iwantCounts: Map\n}\n\nexport class MessageCache {\n msgs = new Map()\n\n msgIdToStrFn: MsgIdToStrFn\n\n history: CacheEntry[][] = []\n\n /** Track with accounting of messages in the mcache that are not yet validated */\n notValidatedCount = 0\n\n /**\n * Holds history of messages in timebounded history arrays\n */\n constructor (\n /**\n * The number of indices in the cache history used for gossiping. That means that a message\n * won't get gossiped anymore when shift got called `gossip` many times after inserting the\n * message in the cache.\n */\n private readonly gossip: number,\n historyCapacity: number,\n msgIdToStrFn: MsgIdToStrFn\n ) {\n this.msgIdToStrFn = msgIdToStrFn\n for (let i = 0; i < historyCapacity; i++) {\n this.history[i] = []\n }\n }\n\n get size (): number {\n return this.msgs.size\n }\n\n /**\n * Adds a message to the current window and the cache\n * Returns true if the message is not known and is inserted in the cache\n */\n put (messageId: MessageId, msg: RPC.Message, validated = false): boolean {\n const { msgIdStr } = messageId\n // Don't add duplicate entries to the cache.\n if (this.msgs.has(msgIdStr)) {\n return false\n }\n\n this.msgs.set(msgIdStr, {\n message: msg,\n validated,\n originatingPeers: new Set(),\n iwantCounts: new Map()\n })\n\n this.history[0].push({ ...messageId, topic: msg.topic })\n\n if (!validated) {\n this.notValidatedCount++\n }\n\n return true\n }\n\n observeDuplicate (msgId: MsgIdStr, fromPeerIdStr: PeerIdStr): void {\n const entry = this.msgs.get(msgId)\n\n if (\n (entry != null) &&\n // if the message is already validated, we don't need to store extra peers sending us\n // duplicates as the message has already been forwarded\n !entry.validated\n ) {\n entry.originatingPeers.add(fromPeerIdStr)\n }\n }\n\n /**\n * Retrieves a message from the cache by its ID, if it is still present\n */\n get (msgId: Uint8Array): RPC.Message | undefined {\n return this.msgs.get(this.msgIdToStrFn(msgId))?.message\n }\n\n /**\n * Increases the iwant count for the given message by one and returns the message together\n * with the iwant if the message exists.\n */\n getWithIWantCount (msgIdStr: string, p: string): { msg: RPC.Message, count: number } | null {\n const msg = this.msgs.get(msgIdStr)\n if (msg == null) {\n return null\n }\n\n const count = (msg.iwantCounts.get(p) ?? 0) + 1\n msg.iwantCounts.set(p, count)\n\n return { msg: msg.message, count }\n }\n\n /**\n * Retrieves a list of message IDs for a set of topics\n */\n getGossipIDs (topics: Set): Map {\n const msgIdsByTopic = new Map()\n for (let i = 0; i < this.gossip; i++) {\n this.history[i].forEach((entry) => {\n const msg = this.msgs.get(entry.msgIdStr)\n if ((msg?.validated ?? false) && topics.has(entry.topic)) {\n let msgIds = msgIdsByTopic.get(entry.topic)\n if (msgIds == null) {\n msgIds = []\n msgIdsByTopic.set(entry.topic, msgIds)\n }\n msgIds.push(entry.msgId)\n }\n })\n }\n\n return msgIdsByTopic\n }\n\n /**\n * Gets a message with msgId and tags it as validated.\n * This function also returns the known peers that have sent us this message. This is used to\n * prevent us sending redundant messages to peers who have already propagated it.\n */\n validate (msgId: MsgIdStr): MessageCacheRecord | null {\n const entry = this.msgs.get(msgId)\n if (entry == null) {\n return null\n }\n\n if (!entry.validated) {\n this.notValidatedCount--\n }\n\n const { message, originatingPeers } = entry\n entry.validated = true\n // Clear the known peers list (after a message is validated, it is forwarded and we no\n // longer need to store the originating peers).\n entry.originatingPeers = new Set()\n return { message, originatingPeers }\n }\n\n /**\n * Shifts the current window, discarding messages older than this.history.length of the cache\n */\n shift (): void {\n const lastCacheEntries = this.history[this.history.length - 1]\n lastCacheEntries.forEach((cacheEntry) => {\n const entry = this.msgs.get(cacheEntry.msgIdStr)\n if (entry != null) {\n this.msgs.delete(cacheEntry.msgIdStr)\n if (!entry.validated) {\n this.notValidatedCount--\n }\n }\n })\n\n this.history.pop()\n this.history.unshift([])\n }\n\n remove (msgId: MsgIdStr): MessageCacheRecord | null {\n const entry = this.msgs.get(msgId)\n if (entry == null) {\n return null\n }\n\n // Keep the message on the history vector, it will be dropped on a shift()\n this.msgs.delete(msgId)\n return entry\n }\n}\n","export const ERR_INVALID_PEER_SCORE_PARAMS = 'ERR_INVALID_PEER_SCORE_PARAMS'\nexport const ERR_INVALID_PEER_SCORE_THRESHOLDS = 'ERR_INVALID_PEER_SCORE_THRESHOLDS'\n","import { CodeError } from '@libp2p/interface'\nimport { ERR_INVALID_PEER_SCORE_PARAMS } from './constants.js'\n\n// This file defines PeerScoreParams and TopicScoreParams interfaces\n// as well as constructors, default constructors, and validation functions\n// for these interfaces\n\nexport interface PeerScoreParams {\n /**\n * Score parameters per topic.\n */\n topics: Record\n\n /**\n * Aggregate topic score cap; this limits the total contribution of topics towards a positive\n * score. It must be positive (or 0 for no cap).\n */\n topicScoreCap: number\n\n /**\n * P5: Application-specific peer scoring\n */\n appSpecificScore(p: string): number\n appSpecificWeight: number\n\n /**\n * P6: IP-colocation factor.\n * The parameter has an associated counter which counts the number of peers with the same IP.\n * If the number of peers in the same IP exceeds IPColocationFactorThreshold, then the value\n * is the square of the difference, ie (PeersInSameIP - IPColocationThreshold)^2.\n * If the number of peers in the same IP is less than the threshold, then the value is 0.\n * The weight of the parameter MUST be negative, unless you want to disable for testing.\n * Note: In order to simulate many IPs in a managable manner when testing, you can set the weight to 0\n * thus disabling the IP colocation penalty.\n */\n IPColocationFactorWeight: number\n IPColocationFactorThreshold: number\n IPColocationFactorWhitelist: Set\n\n /**\n * P7: behavioural pattern penalties.\n * This parameter has an associated counter which tracks misbehaviour as detected by the\n * router. The router currently applies penalties for the following behaviors:\n * - attempting to re-graft before the prune backoff time has elapsed.\n * - not following up in IWANT requests for messages advertised with IHAVE.\n *\n * The value of the parameter is the square of the counter, which decays with BehaviourPenaltyDecay.\n * The weight of the parameter MUST be negative (or zero to disable).\n */\n behaviourPenaltyWeight: number\n behaviourPenaltyThreshold: number\n behaviourPenaltyDecay: number\n\n /**\n * the decay interval for parameter counters.\n */\n decayInterval: number\n\n /**\n * counter value below which it is considered 0.\n */\n decayToZero: number\n\n /**\n * time to remember counters for a disconnected peer.\n */\n retainScore: number\n}\n\nexport interface TopicScoreParams {\n /**\n * The weight of the topic.\n */\n topicWeight: number\n\n /**\n * P1: time in the mesh\n * This is the time the peer has ben grafted in the mesh.\n * The value of the parameter is the time/TimeInMeshQuantum, capped by TimeInMeshCap\n * The weight of the parameter MUST be positive (or zero to disable).\n */\n timeInMeshWeight: number\n timeInMeshQuantum: number\n timeInMeshCap: number\n\n /**\n * P2: first message deliveries\n * This is the number of message deliveries in the topic.\n * The value of the parameter is a counter, decaying with FirstMessageDeliveriesDecay, and capped\n * by FirstMessageDeliveriesCap.\n * The weight of the parameter MUST be positive (or zero to disable).\n */\n firstMessageDeliveriesWeight: number\n firstMessageDeliveriesDecay: number\n firstMessageDeliveriesCap: number\n\n /**\n * P3: mesh message deliveries\n * This is the number of message deliveries in the mesh, within the MeshMessageDeliveriesWindow of\n * message validation; deliveries during validation also count and are retroactively applied\n * when validation succeeds.\n * This window accounts for the minimum time before a hostile mesh peer trying to game the score\n * could replay back a valid message we just sent them.\n * It effectively tracks first and near-first deliveries, ie a message seen from a mesh peer\n * before we have forwarded it to them.\n * The parameter has an associated counter, decaying with MeshMessageDeliveriesDecay.\n * If the counter exceeds the threshold, its value is 0.\n * If the counter is below the MeshMessageDeliveriesThreshold, the value is the square of\n * the deficit, ie (MessageDeliveriesThreshold - counter)^2\n * The penalty is only activated after MeshMessageDeliveriesActivation time in the mesh.\n * The weight of the parameter MUST be negative (or zero to disable).\n */\n meshMessageDeliveriesWeight: number\n meshMessageDeliveriesDecay: number\n meshMessageDeliveriesCap: number\n meshMessageDeliveriesThreshold: number\n meshMessageDeliveriesWindow: number\n meshMessageDeliveriesActivation: number\n\n /**\n * P3b: sticky mesh propagation failures\n * This is a sticky penalty that applies when a peer gets pruned from the mesh with an active\n * mesh message delivery penalty.\n * The weight of the parameter MUST be negative (or zero to disable)\n */\n meshFailurePenaltyWeight: number\n meshFailurePenaltyDecay: number\n\n /**\n * P4: invalid messages\n * This is the number of invalid messages in the topic.\n * The value of the parameter is the square of the counter, decaying with\n * InvalidMessageDeliveriesDecay.\n * The weight of the parameter MUST be negative (or zero to disable).\n */\n invalidMessageDeliveriesWeight: number\n invalidMessageDeliveriesDecay: number\n}\n\nexport const defaultPeerScoreParams: PeerScoreParams = {\n topics: {},\n topicScoreCap: 10.0,\n appSpecificScore: () => 0.0,\n appSpecificWeight: 10.0,\n IPColocationFactorWeight: -5.0,\n IPColocationFactorThreshold: 10.0,\n IPColocationFactorWhitelist: new Set(),\n behaviourPenaltyWeight: -10.0,\n behaviourPenaltyThreshold: 0.0,\n behaviourPenaltyDecay: 0.2,\n decayInterval: 1000.0,\n decayToZero: 0.1,\n retainScore: 3600 * 1000\n}\n\nexport const defaultTopicScoreParams: TopicScoreParams = {\n topicWeight: 0.5,\n timeInMeshWeight: 1,\n timeInMeshQuantum: 1,\n timeInMeshCap: 3600,\n\n firstMessageDeliveriesWeight: 1,\n firstMessageDeliveriesDecay: 0.5,\n firstMessageDeliveriesCap: 2000,\n\n meshMessageDeliveriesWeight: -1,\n meshMessageDeliveriesDecay: 0.5,\n meshMessageDeliveriesCap: 100,\n meshMessageDeliveriesThreshold: 20,\n meshMessageDeliveriesWindow: 10,\n meshMessageDeliveriesActivation: 5000,\n\n meshFailurePenaltyWeight: -1,\n meshFailurePenaltyDecay: 0.5,\n\n invalidMessageDeliveriesWeight: -1,\n invalidMessageDeliveriesDecay: 0.3\n}\n\nexport function createPeerScoreParams (p: Partial = {}): PeerScoreParams {\n return {\n ...defaultPeerScoreParams,\n ...p,\n topics: (p.topics != null)\n ? Object.entries(p.topics).reduce>((topics, [topic, topicScoreParams]) => {\n topics[topic] = createTopicScoreParams(topicScoreParams)\n return topics\n }, {})\n : {}\n }\n}\n\nexport function createTopicScoreParams (p: Partial = {}): TopicScoreParams {\n return {\n ...defaultTopicScoreParams,\n ...p\n }\n}\n\n// peer score parameter validation\nexport function validatePeerScoreParams (p: PeerScoreParams): void {\n for (const [topic, params] of Object.entries(p.topics)) {\n try {\n validateTopicScoreParams(params)\n } catch (e) {\n throw new CodeError(\n `invalid score parameters for topic ${topic}: ${(e as Error).message}`,\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n }\n\n // check that the topic score is 0 or something positive\n if (p.topicScoreCap < 0) {\n throw new CodeError('invalid topic score cap; must be positive (or 0 for no cap)', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check that we have an app specific score; the weight can be anything (but expected positive)\n if (p.appSpecificScore === null || p.appSpecificScore === undefined) {\n throw new CodeError('missing application specific score function', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check the IP colocation factor\n if (p.IPColocationFactorWeight > 0) {\n throw new CodeError(\n 'invalid IPColocationFactorWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.IPColocationFactorWeight !== 0 && p.IPColocationFactorThreshold < 1) {\n throw new CodeError('invalid IPColocationFactorThreshold; must be at least 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check the behaviour penalty\n if (p.behaviourPenaltyWeight > 0) {\n throw new CodeError(\n 'invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.behaviourPenaltyWeight !== 0 && (p.behaviourPenaltyDecay <= 0 || p.behaviourPenaltyDecay >= 1)) {\n throw new CodeError('invalid BehaviourPenaltyDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check the decay parameters\n if (p.decayInterval < 1000) {\n throw new CodeError('invalid DecayInterval; must be at least 1s', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.decayToZero <= 0 || p.decayToZero >= 1) {\n throw new CodeError('invalid DecayToZero; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // no need to check the score retention; a value of 0 means that we don't retain scores\n}\n\n// eslint-disable-next-line complexity\nexport function validateTopicScoreParams (p: TopicScoreParams): void {\n // make sure we have a sane topic weight\n if (p.topicWeight < 0) {\n throw new CodeError('invalid topic weight; must be >= 0', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P1\n if (p.timeInMeshQuantum === 0) {\n throw new CodeError('invalid TimeInMeshQuantum; must be non zero', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.timeInMeshWeight < 0) {\n throw new CodeError('invalid TimeInMeshWeight; must be positive (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.timeInMeshWeight !== 0 && p.timeInMeshQuantum <= 0) {\n throw new CodeError('invalid TimeInMeshQuantum; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.timeInMeshWeight !== 0 && p.timeInMeshCap <= 0) {\n throw new CodeError('invalid TimeInMeshCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P2\n if (p.firstMessageDeliveriesWeight < 0) {\n throw new CodeError(\n 'invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (\n p.firstMessageDeliveriesWeight !== 0 &&\n (p.firstMessageDeliveriesDecay <= 0 || p.firstMessageDeliveriesDecay >= 1)\n ) {\n throw new CodeError('invalid FirstMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.firstMessageDeliveriesWeight !== 0 && p.firstMessageDeliveriesCap <= 0) {\n throw new CodeError('invalid FirstMessageDeliveriesCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P3\n if (p.meshMessageDeliveriesWeight > 0) {\n throw new CodeError(\n 'invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.meshMessageDeliveriesWeight !== 0 && (p.meshMessageDeliveriesDecay <= 0 || p.meshMessageDeliveriesDecay >= 1)) {\n throw new CodeError('invalid MeshMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesCap <= 0) {\n throw new CodeError('invalid MeshMessageDeliveriesCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesThreshold <= 0) {\n throw new CodeError('invalid MeshMessageDeliveriesThreshold; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWindow < 0) {\n throw new CodeError('invalid MeshMessageDeliveriesWindow; must be non-negative', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesActivation < 1000) {\n throw new CodeError('invalid MeshMessageDeliveriesActivation; must be at least 1s', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P3b\n if (p.meshFailurePenaltyWeight > 0) {\n throw new CodeError(\n 'invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.meshFailurePenaltyWeight !== 0 && (p.meshFailurePenaltyDecay <= 0 || p.meshFailurePenaltyDecay >= 1)) {\n throw new CodeError('invalid MeshFailurePenaltyDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P4\n if (p.invalidMessageDeliveriesWeight > 0) {\n throw new CodeError(\n 'invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.invalidMessageDeliveriesDecay <= 0 || p.invalidMessageDeliveriesDecay >= 1) {\n throw new CodeError('invalid InvalidMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { ERR_INVALID_PEER_SCORE_THRESHOLDS } from './constants.js'\n\n// This file defines PeerScoreThresholds interface\n// as well as a constructor, default constructor, and validation function\n// for this interface\n\nexport interface PeerScoreThresholds {\n /**\n * gossipThreshold is the score threshold below which gossip propagation is supressed;\n * should be negative.\n */\n gossipThreshold: number\n\n /**\n * publishThreshold is the score threshold below which we shouldn't publish when using flood\n * publishing (also applies to fanout and floodsub peers); should be negative and <= GossipThreshold.\n */\n publishThreshold: number\n\n /**\n * graylistThreshold is the score threshold below which message processing is supressed altogether,\n * implementing an effective graylist according to peer score; should be negative and <= PublisThreshold.\n */\n graylistThreshold: number\n\n /**\n * acceptPXThreshold is the score threshold below which PX will be ignored; this should be positive\n * and limited to scores attainable by bootstrappers and other trusted nodes.\n */\n acceptPXThreshold: number\n\n /**\n * opportunisticGraftThreshold is the median mesh score threshold before triggering opportunistic\n * grafting; this should have a small positive value.\n */\n opportunisticGraftThreshold: number\n}\n\nexport const defaultPeerScoreThresholds: PeerScoreThresholds = {\n gossipThreshold: -10,\n publishThreshold: -50,\n graylistThreshold: -80,\n acceptPXThreshold: 10,\n opportunisticGraftThreshold: 20\n}\n\nexport function createPeerScoreThresholds (p: Partial = {}): PeerScoreThresholds {\n return {\n ...defaultPeerScoreThresholds,\n ...p\n }\n}\n\nexport function validatePeerScoreThresholds (p: PeerScoreThresholds): void {\n if (p.gossipThreshold > 0) {\n throw new CodeError('invalid gossip threshold; it must be <= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS)\n }\n if (p.publishThreshold > 0 || p.publishThreshold > p.gossipThreshold) {\n throw new CodeError(\n 'invalid publish threshold; it must be <= 0 and <= gossip threshold',\n ERR_INVALID_PEER_SCORE_THRESHOLDS\n )\n }\n if (p.graylistThreshold > 0 || p.graylistThreshold > p.publishThreshold) {\n throw new CodeError(\n 'invalid graylist threshold; it must be <= 0 and <= publish threshold',\n ERR_INVALID_PEER_SCORE_THRESHOLDS\n )\n }\n if (p.acceptPXThreshold < 0) {\n throw new CodeError('invalid accept PX threshold; it must be >= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS)\n }\n if (p.opportunisticGraftThreshold < 0) {\n throw new CodeError('invalid opportunistic grafting threshold; it must be >= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS)\n }\n}\n","/**\n * Exclude up to `ineed` items from a set if item meets condition `cond`\n */\nexport function removeItemsFromSet (\n superSet: Set,\n ineed: number,\n cond: (peer: T) => boolean = () => true\n): Set {\n const subset = new Set()\n if (ineed <= 0) return subset\n\n for (const id of superSet) {\n if (subset.size >= ineed) break\n if (cond(id)) {\n subset.add(id)\n superSet.delete(id)\n }\n }\n\n return subset\n}\n\n/**\n * Exclude up to `ineed` items from a set\n */\nexport function removeFirstNItemsFromSet (superSet: Set, ineed: number): Set {\n return removeItemsFromSet(superSet, ineed, () => true)\n}\n\nexport class MapDef extends Map {\n constructor (private readonly getDefault: () => V) {\n super()\n }\n\n getOrDefault (key: K): V {\n let value = super.get(key)\n if (value === undefined) {\n value = this.getDefault()\n this.set(key, value)\n }\n return value\n }\n}\n","import type { PeerScoreParams } from './peer-score-params.js'\nimport type { PeerStats } from './peer-stats.js'\n\nexport function computeScore (\n peer: string,\n pstats: PeerStats,\n params: PeerScoreParams,\n peerIPs: Map>\n): number {\n let score = 0\n\n // topic stores\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n // the topic parameters\n const topicParams = params.topics[topic]\n if (topicParams === undefined) {\n // we are not scoring this topic\n return\n }\n\n let topicScore = 0\n\n // P1: time in Mesh\n if (tstats.inMesh) {\n let p1 = tstats.meshTime / topicParams.timeInMeshQuantum\n if (p1 > topicParams.timeInMeshCap) {\n p1 = topicParams.timeInMeshCap\n }\n topicScore += p1 * topicParams.timeInMeshWeight\n }\n\n // P2: first message deliveries\n let p2 = tstats.firstMessageDeliveries\n if (p2 > topicParams.firstMessageDeliveriesCap) {\n p2 = topicParams.firstMessageDeliveriesCap\n }\n topicScore += p2 * topicParams.firstMessageDeliveriesWeight\n\n // P3: mesh message deliveries\n if (\n tstats.meshMessageDeliveriesActive &&\n tstats.meshMessageDeliveries < topicParams.meshMessageDeliveriesThreshold\n ) {\n const deficit = topicParams.meshMessageDeliveriesThreshold - tstats.meshMessageDeliveries\n const p3 = deficit * deficit\n topicScore += p3 * topicParams.meshMessageDeliveriesWeight\n }\n\n // P3b:\n // NOTE: the weight of P3b is negative (validated in validateTopicScoreParams) so this detracts\n const p3b = tstats.meshFailurePenalty\n topicScore += p3b * topicParams.meshFailurePenaltyWeight\n\n // P4: invalid messages\n // NOTE: the weight of P4 is negative (validated in validateTopicScoreParams) so this detracts\n const p4 = tstats.invalidMessageDeliveries * tstats.invalidMessageDeliveries\n topicScore += p4 * topicParams.invalidMessageDeliveriesWeight\n\n // update score, mixing with topic weight\n score += topicScore * topicParams.topicWeight\n })\n\n // apply the topic score cap, if any\n if (params.topicScoreCap > 0 && score > params.topicScoreCap) {\n score = params.topicScoreCap\n }\n\n // P5: application-specific score\n const p5 = params.appSpecificScore(peer)\n score += p5 * params.appSpecificWeight\n\n // P6: IP colocation factor\n pstats.knownIPs.forEach((ip) => {\n if (params.IPColocationFactorWhitelist.has(ip)) {\n return\n }\n\n // P6 has a cliff (IPColocationFactorThreshold)\n // It's only applied if at least that many peers are connected to us from that source IP addr.\n // It is quadratic, and the weight is negative (validated in validatePeerScoreParams)\n const peersInIP = peerIPs.get(ip)\n const numPeersInIP = (peersInIP != null) ? peersInIP.size : 0\n if (numPeersInIP > params.IPColocationFactorThreshold) {\n const surplus = numPeersInIP - params.IPColocationFactorThreshold\n const p6 = surplus * surplus\n score += p6 * params.IPColocationFactorWeight\n }\n })\n\n // P7: behavioural pattern penalty\n if (pstats.behaviourPenalty > params.behaviourPenaltyThreshold) {\n const excess = pstats.behaviourPenalty - params.behaviourPenaltyThreshold\n const p7 = excess * excess\n score += p7 * params.behaviourPenaltyWeight\n }\n\n return score\n}\n","import Denque from 'denque'\nimport { TimeCacheDuration } from '../constants.js'\n\nexport enum DeliveryRecordStatus {\n /**\n * we don't know (yet) if the message is valid\n */\n unknown,\n /**\n * we know the message is valid\n */\n valid,\n /**\n * we know the message is invalid\n */\n invalid,\n /**\n * we were instructed by the validator to ignore the message\n */\n ignored\n}\n\nexport interface DeliveryRecord {\n status: DeliveryRecordStatus\n firstSeenTsMs: number\n validated: number\n peers: Set\n}\n\ninterface DeliveryQueueEntry {\n msgId: string\n expire: number\n}\n\n/**\n * Map of canonical message ID to DeliveryRecord\n *\n * Maintains an internal queue for efficient gc of old messages\n */\nexport class MessageDeliveries {\n private readonly records: Map\n public queue: Denque\n\n constructor () {\n this.records = new Map()\n this.queue = new Denque()\n }\n\n getRecord (msgIdStr: string): DeliveryRecord | undefined {\n return this.records.get(msgIdStr)\n }\n\n ensureRecord (msgIdStr: string): DeliveryRecord {\n let drec = this.records.get(msgIdStr)\n if (drec != null) {\n return drec\n }\n\n // record doesn't exist yet\n // create record\n drec = {\n status: DeliveryRecordStatus.unknown,\n firstSeenTsMs: Date.now(),\n validated: 0,\n peers: new Set()\n }\n this.records.set(msgIdStr, drec)\n\n // and add msgId to the queue\n const entry: DeliveryQueueEntry = {\n msgId: msgIdStr,\n expire: Date.now() + TimeCacheDuration\n }\n this.queue.push(entry)\n\n return drec\n }\n\n gc (): void {\n const now = Date.now()\n // queue is sorted by expiry time\n // remove expired messages, remove from queue until first un-expired message found\n let head = this.queue.peekFront()\n while ((head != null) && head.expire < now) {\n this.records.delete(head.msgId)\n this.queue.shift()\n head = this.queue.peekFront()\n }\n }\n\n clear (): void {\n this.records.clear()\n this.queue.clear()\n }\n}\n","import { type MsgIdStr, type PeerIdStr, RejectReason, type TopicStr, type IPStr } from '../types.js'\nimport { MapDef } from '../utils/set.js'\nimport { computeScore } from './compute-score.js'\nimport { MessageDeliveries, DeliveryRecordStatus } from './message-deliveries.js'\nimport { type PeerScoreParams, validatePeerScoreParams } from './peer-score-params.js'\nimport type { PeerStats, TopicStats } from './peer-stats.js'\nimport type { Metrics, ScorePenalty } from '../metrics.js'\nimport type { ComponentLogger, Logger } from '@libp2p/interface'\n\ninterface PeerScoreOpts {\n /**\n * Miliseconds to cache computed score per peer\n */\n scoreCacheValidityMs: number\n\n computeScore?: typeof computeScore\n}\n\ninterface ScoreCacheEntry {\n /** The cached score */\n score: number\n /** Unix timestamp in miliseconds, the time after which the cached score for a peer is no longer valid */\n cacheUntil: number\n}\n\nexport type PeerScoreStatsDump = Record\n\nexport class PeerScore {\n /**\n * Per-peer stats for score calculation\n */\n readonly peerStats = new Map()\n /**\n * IP colocation tracking; maps IP => set of peers.\n */\n readonly peerIPs = new MapDef>(() => new Set())\n /**\n * Cache score up to decayInterval if topic stats are unchanged.\n */\n readonly scoreCache = new Map()\n /**\n * Recent message delivery timing/participants\n */\n readonly deliveryRecords = new MessageDeliveries()\n\n _backgroundInterval?: ReturnType\n\n private readonly scoreCacheValidityMs: number\n private readonly computeScore: typeof computeScore\n private readonly log: Logger\n\n constructor (readonly params: PeerScoreParams, private readonly metrics: Metrics | null, componentLogger: ComponentLogger, opts: PeerScoreOpts) {\n validatePeerScoreParams(params)\n this.scoreCacheValidityMs = opts.scoreCacheValidityMs\n this.computeScore = opts.computeScore ?? computeScore\n this.log = componentLogger.forComponent('libp2p:gossipsub:score')\n }\n\n get size (): number {\n return this.peerStats.size\n }\n\n /**\n * Start PeerScore instance\n */\n start (): void {\n if (this._backgroundInterval != null) {\n this.log('Peer score already running')\n return\n }\n this._backgroundInterval = setInterval(() => { this.background() }, this.params.decayInterval)\n this.log('started')\n }\n\n /**\n * Stop PeerScore instance\n */\n stop (): void {\n if (this._backgroundInterval == null) {\n this.log('Peer score already stopped')\n return\n }\n clearInterval(this._backgroundInterval)\n delete this._backgroundInterval\n this.peerIPs.clear()\n this.peerStats.clear()\n this.deliveryRecords.clear()\n this.log('stopped')\n }\n\n /**\n * Periodic maintenance\n */\n background (): void {\n this.refreshScores()\n this.deliveryRecords.gc()\n }\n\n dumpPeerScoreStats (): PeerScoreStatsDump {\n return Object.fromEntries(Array.from(this.peerStats.entries()).map(([peer, stats]) => [peer, stats]))\n }\n\n messageFirstSeenTimestampMs (msgIdStr: MsgIdStr): number | null {\n const drec = this.deliveryRecords.getRecord(msgIdStr)\n return (drec != null) ? drec.firstSeenTsMs : null\n }\n\n /**\n * Decays scores, and purges score records for disconnected peers once their expiry has elapsed.\n */\n public refreshScores (): void {\n const now = Date.now()\n const decayToZero = this.params.decayToZero\n\n this.peerStats.forEach((pstats, id) => {\n if (!pstats.connected) {\n // has the retention period expired?\n if (now > pstats.expire) {\n // yes, throw it away (but clean up the IP tracking first)\n this.removeIPsForPeer(id, pstats.knownIPs)\n this.peerStats.delete(id)\n this.scoreCache.delete(id)\n }\n\n // we don't decay retained scores, as the peer is not active.\n // this way the peer cannot reset a negative score by simply disconnecting and reconnecting,\n // unless the retention period has elapsed.\n // similarly, a well behaved peer does not lose its score by getting disconnected.\n return\n }\n\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n const tparams = this.params.topics[topic]\n if (tparams === undefined) {\n // we are not scoring this topic\n // should be unreachable, we only add scored topics to pstats\n return\n }\n\n // decay counters\n tstats.firstMessageDeliveries *= tparams.firstMessageDeliveriesDecay\n if (tstats.firstMessageDeliveries < decayToZero) {\n tstats.firstMessageDeliveries = 0\n }\n\n tstats.meshMessageDeliveries *= tparams.meshMessageDeliveriesDecay\n if (tstats.meshMessageDeliveries < decayToZero) {\n tstats.meshMessageDeliveries = 0\n }\n\n tstats.meshFailurePenalty *= tparams.meshFailurePenaltyDecay\n if (tstats.meshFailurePenalty < decayToZero) {\n tstats.meshFailurePenalty = 0\n }\n\n tstats.invalidMessageDeliveries *= tparams.invalidMessageDeliveriesDecay\n if (tstats.invalidMessageDeliveries < decayToZero) {\n tstats.invalidMessageDeliveries = 0\n }\n\n // update mesh time and activate mesh message delivery parameter if need be\n if (tstats.inMesh) {\n tstats.meshTime = now - tstats.graftTime\n if (tstats.meshTime > tparams.meshMessageDeliveriesActivation) {\n tstats.meshMessageDeliveriesActive = true\n }\n }\n })\n\n // decay P7 counter\n pstats.behaviourPenalty *= this.params.behaviourPenaltyDecay\n if (pstats.behaviourPenalty < decayToZero) {\n pstats.behaviourPenalty = 0\n }\n })\n }\n\n /**\n * Return the score for a peer\n */\n score (id: PeerIdStr): number {\n this.metrics?.scoreFnCalls.inc()\n\n const pstats = this.peerStats.get(id)\n if (pstats == null) {\n return 0\n }\n\n const now = Date.now()\n const cacheEntry = this.scoreCache.get(id)\n\n // Found cached score within validity period\n if ((cacheEntry != null) && cacheEntry.cacheUntil > now) {\n return cacheEntry.score\n }\n\n this.metrics?.scoreFnRuns.inc()\n\n const score = this.computeScore(id, pstats, this.params, this.peerIPs)\n const cacheUntil = now + this.scoreCacheValidityMs\n\n if (cacheEntry != null) {\n this.metrics?.scoreCachedDelta.observe(Math.abs(score - cacheEntry.score))\n cacheEntry.score = score\n cacheEntry.cacheUntil = cacheUntil\n } else {\n this.scoreCache.set(id, { score, cacheUntil })\n }\n\n return score\n }\n\n /**\n * Apply a behavioural penalty to a peer\n */\n addPenalty (id: PeerIdStr, penalty: number, penaltyLabel: ScorePenalty): void {\n const pstats = this.peerStats.get(id)\n if (pstats != null) {\n pstats.behaviourPenalty += penalty\n this.metrics?.onScorePenalty(penaltyLabel)\n }\n }\n\n addPeer (id: PeerIdStr): void {\n // create peer stats (not including topic stats for each topic to be scored)\n // topic stats will be added as needed\n const pstats: PeerStats = {\n connected: true,\n expire: 0,\n topics: {},\n knownIPs: new Set(),\n behaviourPenalty: 0\n }\n this.peerStats.set(id, pstats)\n }\n\n /** Adds a new IP to a peer, if the peer is not known the update is ignored */\n addIP (id: PeerIdStr, ip: string): void {\n const pstats = this.peerStats.get(id)\n if (pstats != null) {\n pstats.knownIPs.add(ip)\n }\n\n this.peerIPs.getOrDefault(ip).add(id)\n }\n\n /** Remove peer association with IP */\n removeIP (id: PeerIdStr, ip: string): void {\n const pstats = this.peerStats.get(id)\n if (pstats != null) {\n pstats.knownIPs.delete(ip)\n }\n\n const peersWithIP = this.peerIPs.get(ip)\n if (peersWithIP != null) {\n peersWithIP.delete(id)\n if (peersWithIP.size === 0) {\n this.peerIPs.delete(ip)\n }\n }\n }\n\n removePeer (id: PeerIdStr): void {\n const pstats = this.peerStats.get(id)\n if (pstats == null) {\n return\n }\n\n // decide whether to retain the score; this currently only retains non-positive scores\n // to dissuade attacks on the score function.\n if (this.score(id) > 0) {\n this.removeIPsForPeer(id, pstats.knownIPs)\n this.peerStats.delete(id)\n return\n }\n\n // furthermore, when we decide to retain the score, the firstMessageDelivery counters are\n // reset to 0 and mesh delivery penalties applied.\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n tstats.firstMessageDeliveries = 0\n\n const threshold = this.params.topics[topic].meshMessageDeliveriesThreshold\n if (tstats.inMesh && tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold) {\n const deficit = threshold - tstats.meshMessageDeliveries\n tstats.meshFailurePenalty += deficit * deficit\n }\n\n tstats.inMesh = false\n tstats.meshMessageDeliveriesActive = false\n })\n\n pstats.connected = false\n pstats.expire = Date.now() + this.params.retainScore\n }\n\n /** Handles scoring functionality as a peer GRAFTs to a topic. */\n graft (id: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(id)\n if (pstats != null) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats != null) {\n // if we are scoring the topic, update the mesh status.\n tstats.inMesh = true\n tstats.graftTime = Date.now()\n tstats.meshTime = 0\n tstats.meshMessageDeliveriesActive = false\n }\n }\n }\n\n /** Handles scoring functionality as a peer PRUNEs from a topic. */\n prune (id: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(id)\n if (pstats != null) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats != null) {\n // sticky mesh delivery rate failure penalty\n const threshold = this.params.topics[topic].meshMessageDeliveriesThreshold\n if (tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold) {\n const deficit = threshold - tstats.meshMessageDeliveries\n tstats.meshFailurePenalty += deficit * deficit\n }\n tstats.meshMessageDeliveriesActive = false\n tstats.inMesh = false\n\n // TODO: Consider clearing score cache on important penalties\n // this.scoreCache.delete(id)\n }\n }\n }\n\n validateMessage (msgIdStr: MsgIdStr): void {\n this.deliveryRecords.ensureRecord(msgIdStr)\n }\n\n deliverMessage (from: PeerIdStr, msgIdStr: MsgIdStr, topic: TopicStr): void {\n this.markFirstMessageDelivery(from, topic)\n\n const drec = this.deliveryRecords.ensureRecord(msgIdStr)\n const now = Date.now()\n\n // defensive check that this is the first delivery trace -- delivery status should be unknown\n if (drec.status !== DeliveryRecordStatus.unknown) {\n this.log(\n 'unexpected delivery: message from %s was first seen %s ago and has delivery status %s',\n from,\n now - drec.firstSeenTsMs,\n DeliveryRecordStatus[drec.status]\n )\n return\n }\n\n // mark the message as valid and reward mesh peers that have already forwarded it to us\n drec.status = DeliveryRecordStatus.valid\n drec.validated = now\n drec.peers.forEach((p) => {\n // this check is to make sure a peer can't send us a message twice and get a double count\n // if it is a first delivery.\n if (p !== from.toString()) {\n this.markDuplicateMessageDelivery(p, topic)\n }\n })\n }\n\n /**\n * Similar to `rejectMessage` except does not require the message id or reason for an invalid message.\n */\n rejectInvalidMessage (from: PeerIdStr, topic: TopicStr): void {\n this.markInvalidMessageDelivery(from, topic)\n }\n\n rejectMessage (from: PeerIdStr, msgIdStr: MsgIdStr, topic: TopicStr, reason: RejectReason): void {\n // eslint-disable-next-line default-case\n switch (reason) {\n // these messages are not tracked, but the peer is penalized as they are invalid\n case RejectReason.Error:\n this.markInvalidMessageDelivery(from, topic)\n return\n\n // we ignore those messages, so do nothing.\n case RejectReason.Blacklisted:\n return\n\n // the rest are handled after record creation\n }\n\n const drec = this.deliveryRecords.ensureRecord(msgIdStr)\n\n // defensive check that this is the first rejection -- delivery status should be unknown\n if (drec.status !== DeliveryRecordStatus.unknown) {\n this.log(\n 'unexpected rejection: message from %s was first seen %s ago and has delivery status %d',\n from,\n Date.now() - drec.firstSeenTsMs,\n DeliveryRecordStatus[drec.status]\n )\n return\n }\n\n if (reason === RejectReason.Ignore) {\n // we were explicitly instructed by the validator to ignore the message but not penalize the peer\n drec.status = DeliveryRecordStatus.ignored\n drec.peers.clear()\n return\n }\n\n // mark the message as invalid and penalize peers that have already forwarded it.\n drec.status = DeliveryRecordStatus.invalid\n\n this.markInvalidMessageDelivery(from, topic)\n drec.peers.forEach((p) => {\n this.markInvalidMessageDelivery(p, topic)\n })\n\n // release the delivery time tracking map to free some memory early\n drec.peers.clear()\n }\n\n duplicateMessage (from: PeerIdStr, msgIdStr: MsgIdStr, topic: TopicStr): void {\n const drec = this.deliveryRecords.ensureRecord(msgIdStr)\n\n if (drec.peers.has(from)) {\n // we have already seen this duplicate\n return\n }\n\n // eslint-disable-next-line default-case\n switch (drec.status) {\n case DeliveryRecordStatus.unknown:\n // the message is being validated; track the peer delivery and wait for\n // the Deliver/Reject/Ignore notification.\n drec.peers.add(from)\n break\n\n case DeliveryRecordStatus.valid:\n // mark the peer delivery time to only count a duplicate delivery once.\n drec.peers.add(from)\n this.markDuplicateMessageDelivery(from, topic, drec.validated)\n break\n\n case DeliveryRecordStatus.invalid:\n // we no longer track delivery time\n this.markInvalidMessageDelivery(from, topic)\n break\n\n case DeliveryRecordStatus.ignored:\n // the message was ignored; do nothing (we don't know if it was valid)\n break\n }\n }\n\n /**\n * Increments the \"invalid message deliveries\" counter for all scored topics the message is published in.\n */\n public markInvalidMessageDelivery (from: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(from)\n if (pstats != null) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats != null) {\n tstats.invalidMessageDeliveries += 1\n }\n }\n }\n\n /**\n * Increments the \"first message deliveries\" counter for all scored topics the message is published in,\n * as well as the \"mesh message deliveries\" counter, if the peer is in the mesh for the topic.\n * Messages already known (with the seenCache) are counted with markDuplicateMessageDelivery()\n */\n public markFirstMessageDelivery (from: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(from)\n if (pstats != null) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats != null) {\n let cap = this.params.topics[topic].firstMessageDeliveriesCap\n tstats.firstMessageDeliveries = Math.min(cap, tstats.firstMessageDeliveries + 1)\n\n if (tstats.inMesh) {\n cap = this.params.topics[topic].meshMessageDeliveriesCap\n tstats.meshMessageDeliveries = Math.min(cap, tstats.meshMessageDeliveries + 1)\n }\n }\n }\n }\n\n /**\n * Increments the \"mesh message deliveries\" counter for messages we've seen before,\n * as long the message was received within the P3 window.\n */\n public markDuplicateMessageDelivery (from: PeerIdStr, topic: TopicStr, validatedTime?: number): void {\n const pstats = this.peerStats.get(from)\n if (pstats != null) {\n const now = validatedTime !== undefined ? Date.now() : 0\n\n const tstats = this.getPtopicStats(pstats, topic)\n // eslint-disable-next-line @typescript-eslint/prefer-optional-chain\n if (tstats != null && tstats.inMesh) {\n const tparams = this.params.topics[topic]\n\n // check against the mesh delivery window -- if the validated time is passed as 0, then\n // the message was received before we finished validation and thus falls within the mesh\n // delivery window.\n if (validatedTime !== undefined) {\n const deliveryDelayMs = now - validatedTime\n const isLateDelivery = deliveryDelayMs > tparams.meshMessageDeliveriesWindow\n this.metrics?.onDuplicateMsgDelivery(topic, deliveryDelayMs, isLateDelivery)\n\n if (isLateDelivery) {\n return\n }\n }\n\n const cap = tparams.meshMessageDeliveriesCap\n tstats.meshMessageDeliveries = Math.min(cap, tstats.meshMessageDeliveries + 1)\n }\n }\n }\n\n /**\n * Removes an IP list from the tracking list for a peer.\n */\n private removeIPsForPeer (id: PeerIdStr, ipsToRemove: Set): void {\n for (const ipToRemove of ipsToRemove) {\n const peerSet = this.peerIPs.get(ipToRemove)\n if (peerSet != null) {\n peerSet.delete(id)\n if (peerSet.size === 0) {\n this.peerIPs.delete(ipToRemove)\n }\n }\n }\n }\n\n /**\n * Returns topic stats if they exist, otherwise if the supplied parameters score the\n * topic, inserts the default stats and returns a reference to those. If neither apply, returns None.\n */\n private getPtopicStats (pstats: PeerStats, topic: TopicStr): TopicStats | null {\n let topicStats: TopicStats | undefined = pstats.topics[topic]\n\n if (topicStats !== undefined) {\n return topicStats\n }\n\n if (this.params.topics[topic] !== undefined) {\n topicStats = {\n inMesh: false,\n graftTime: 0,\n meshTime: 0,\n firstMessageDeliveries: 0,\n meshMessageDeliveries: 0,\n meshMessageDeliveriesActive: false,\n meshFailurePenalty: 0,\n invalidMessageDeliveries: 0\n }\n pstats.topics[topic] = topicStats\n\n return topicStats\n }\n\n return null\n }\n}\n","import type { PeerScoreParams } from './peer-score-params.js'\nimport type { PeerStats } from './peer-stats.js'\n\ntype TopicLabel = string\ntype TopicStr = string\ntype TopicStrToLabel = Map\n\nexport interface TopicScoreWeights {\n p1w: T\n p2w: T\n p3w: T\n p3bw: T\n p4w: T\n}\nexport interface ScoreWeights {\n byTopic: Map>\n p5w: T\n p6w: T\n p7w: T\n score: T\n}\n\nexport function computeScoreWeights (\n peer: string,\n pstats: PeerStats,\n params: PeerScoreParams,\n peerIPs: Map>,\n topicStrToLabel: TopicStrToLabel\n): ScoreWeights {\n let score = 0\n\n const byTopic = new Map>()\n\n // topic stores\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n // the topic parameters\n // Aggregate by known topicLabel or throw to 'unknown'. This prevent too high cardinality\n const topicLabel = topicStrToLabel.get(topic) ?? 'unknown'\n const topicParams = params.topics[topic]\n if (topicParams === undefined) {\n // we are not scoring this topic\n return\n }\n\n let topicScores = byTopic.get(topicLabel)\n if (topicScores == null) {\n topicScores = {\n p1w: 0,\n p2w: 0,\n p3w: 0,\n p3bw: 0,\n p4w: 0\n }\n byTopic.set(topicLabel, topicScores)\n }\n\n let p1w = 0\n let p2w = 0\n let p3w = 0\n let p3bw = 0\n let p4w = 0\n\n // P1: time in Mesh\n if (tstats.inMesh) {\n const p1 = Math.max(tstats.meshTime / topicParams.timeInMeshQuantum, topicParams.timeInMeshCap)\n p1w += p1 * topicParams.timeInMeshWeight\n }\n\n // P2: first message deliveries\n let p2 = tstats.firstMessageDeliveries\n if (p2 > topicParams.firstMessageDeliveriesCap) {\n p2 = topicParams.firstMessageDeliveriesCap\n }\n p2w += p2 * topicParams.firstMessageDeliveriesWeight\n\n // P3: mesh message deliveries\n if (\n tstats.meshMessageDeliveriesActive &&\n tstats.meshMessageDeliveries < topicParams.meshMessageDeliveriesThreshold\n ) {\n const deficit = topicParams.meshMessageDeliveriesThreshold - tstats.meshMessageDeliveries\n const p3 = deficit * deficit\n p3w += p3 * topicParams.meshMessageDeliveriesWeight\n }\n\n // P3b:\n // NOTE: the weight of P3b is negative (validated in validateTopicScoreParams) so this detracts\n const p3b = tstats.meshFailurePenalty\n p3bw += p3b * topicParams.meshFailurePenaltyWeight\n\n // P4: invalid messages\n // NOTE: the weight of P4 is negative (validated in validateTopicScoreParams) so this detracts\n const p4 = tstats.invalidMessageDeliveries * tstats.invalidMessageDeliveries\n p4w += p4 * topicParams.invalidMessageDeliveriesWeight\n\n // update score, mixing with topic weight\n score += (p1w + p2w + p3w + p3bw + p4w) * topicParams.topicWeight\n\n topicScores.p1w += p1w\n topicScores.p2w += p2w\n topicScores.p3w += p3w\n topicScores.p3bw += p3bw\n topicScores.p4w += p4w\n })\n\n // apply the topic score cap, if any\n if (params.topicScoreCap > 0 && score > params.topicScoreCap) {\n score = params.topicScoreCap\n\n // Proportionally apply cap to all individual contributions\n const capF = params.topicScoreCap / score\n for (const ws of byTopic.values()) {\n ws.p1w *= capF\n ws.p2w *= capF\n ws.p3w *= capF\n ws.p3bw *= capF\n ws.p4w *= capF\n }\n }\n\n let p5w = 0\n let p6w = 0\n let p7w = 0\n\n // P5: application-specific score\n const p5 = params.appSpecificScore(peer)\n p5w += p5 * params.appSpecificWeight\n\n // P6: IP colocation factor\n pstats.knownIPs.forEach((ip) => {\n if (params.IPColocationFactorWhitelist.has(ip)) {\n return\n }\n\n // P6 has a cliff (IPColocationFactorThreshold)\n // It's only applied if at least that many peers are connected to us from that source IP addr.\n // It is quadratic, and the weight is negative (validated in validatePeerScoreParams)\n const peersInIP = peerIPs.get(ip)\n const numPeersInIP = (peersInIP != null) ? peersInIP.size : 0\n if (numPeersInIP > params.IPColocationFactorThreshold) {\n const surplus = numPeersInIP - params.IPColocationFactorThreshold\n const p6 = surplus * surplus\n p6w += p6 * params.IPColocationFactorWeight\n }\n })\n\n // P7: behavioural pattern penalty\n const p7 = pstats.behaviourPenalty * pstats.behaviourPenalty\n p7w += p7 * params.behaviourPenaltyWeight\n\n score += p5w + p6w + p7w\n\n return {\n byTopic,\n p5w,\n p6w,\n p7w,\n score\n }\n}\n\nexport function computeAllPeersScoreWeights (\n peerIdStrs: Iterable,\n peerStats: Map,\n params: PeerScoreParams,\n peerIPs: Map>,\n topicStrToLabel: TopicStrToLabel\n): ScoreWeights {\n const sw: ScoreWeights = {\n byTopic: new Map(),\n p5w: [],\n p6w: [],\n p7w: [],\n score: []\n }\n\n for (const peerIdStr of peerIdStrs) {\n const pstats = peerStats.get(peerIdStr)\n if (pstats != null) {\n const swPeer = computeScoreWeights(peerIdStr, pstats, params, peerIPs, topicStrToLabel)\n\n for (const [topic, swPeerTopic] of swPeer.byTopic) {\n let swTopic = sw.byTopic.get(topic)\n if (swTopic == null) {\n swTopic = {\n p1w: [],\n p2w: [],\n p3w: [],\n p3bw: [],\n p4w: []\n }\n sw.byTopic.set(topic, swTopic)\n }\n\n swTopic.p1w.push(swPeerTopic.p1w)\n swTopic.p2w.push(swPeerTopic.p2w)\n swTopic.p3w.push(swPeerTopic.p3w)\n swTopic.p3bw.push(swPeerTopic.p3bw)\n swTopic.p4w.push(swPeerTopic.p4w)\n }\n\n sw.p5w.push(swPeer.p5w)\n sw.p6w.push(swPeer.p6w)\n sw.p7w.push(swPeer.p7w)\n sw.score.push(swPeer.score)\n } else {\n sw.p5w.push(0)\n sw.p6w.push(0)\n sw.p7w.push(0)\n sw.score.push(0)\n }\n }\n\n return sw\n}\n","import { encode, decode } from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport { pushable, type Pushable } from 'it-pushable'\nimport type { Stream } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\ninterface OutboundStreamOpts {\n /** Max size in bytes for pushable buffer. If full, will throw on .push */\n maxBufferSize?: number\n}\n\ninterface InboundStreamOpts {\n /** Max size in bytes for reading messages from the stream */\n maxDataLength?: number\n}\n\nexport class OutboundStream {\n private readonly pushable: Pushable\n private readonly closeController: AbortController\n private readonly maxBufferSize: number\n\n constructor (private readonly rawStream: Stream, errCallback: (e: Error) => void, opts: OutboundStreamOpts) {\n this.pushable = pushable()\n this.closeController = new AbortController()\n this.maxBufferSize = opts.maxBufferSize ?? Infinity\n\n this.closeController.signal.addEventListener('abort', () => {\n rawStream.close()\n .catch(err => {\n rawStream.abort(err)\n })\n })\n\n pipe(\n this.pushable,\n this.rawStream\n ).catch(errCallback)\n }\n\n get protocol (): string {\n // TODO remove this non-nullish assertion after https://github.com/libp2p/js-libp2p-interfaces/pull/265 is incorporated\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.rawStream.protocol!\n }\n\n push (data: Uint8Array): void {\n if (this.pushable.readableLength > this.maxBufferSize) {\n throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`)\n }\n\n this.pushable.push(encode.single(data))\n }\n\n /**\n * Same to push() but this is prefixed data so no need to encode length prefixed again\n */\n pushPrefixed (data: Uint8ArrayList): void {\n if (this.pushable.readableLength > this.maxBufferSize) {\n throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`)\n }\n this.pushable.push(data)\n }\n\n async close (): Promise {\n this.closeController.abort()\n // similar to pushable.end() but clear the internal buffer\n await this.pushable.return()\n }\n}\n\nexport class InboundStream {\n public readonly source: AsyncIterable\n\n private readonly rawStream: Stream\n private readonly closeController: AbortController\n\n constructor (rawStream: Stream, opts: InboundStreamOpts = {}) {\n this.rawStream = rawStream\n this.closeController = new AbortController()\n\n this.closeController.signal.addEventListener('abort', () => {\n rawStream.close()\n .catch(err => {\n rawStream.abort(err)\n })\n })\n\n this.source = pipe(\n this.rawStream,\n (source) => decode(source, opts)\n )\n }\n\n async close (): Promise {\n this.closeController.abort()\n }\n}\n","import { type MsgIdStr, type MsgIdToStrFn, type PeerIdStr, RejectReason } from './types.js'\nimport type { Metrics } from './metrics.js'\n\n/**\n * IWantTracer is an internal tracer that tracks IWANT requests in order to penalize\n * peers who don't follow up on IWANT requests after an IHAVE advertisement.\n * The tracking of promises is probabilistic to avoid using too much memory.\n *\n * Note: Do not confuse these 'promises' with JS Promise objects.\n * These 'promises' are merely expectations of a peer's behavior.\n */\nexport class IWantTracer {\n /**\n * Promises to deliver a message\n * Map per message id, per peer, promise expiration time\n */\n private readonly promises = new Map>()\n /**\n * First request time by msgId. Used for metrics to track expire times.\n * Necessary to know if peers are actually breaking promises or simply sending them a bit later\n */\n private readonly requestMsByMsg = new Map()\n private readonly requestMsByMsgExpire: number\n\n constructor (\n private readonly gossipsubIWantFollowupMs: number,\n private readonly msgIdToStrFn: MsgIdToStrFn,\n private readonly metrics: Metrics | null\n ) {\n this.requestMsByMsgExpire = 10 * gossipsubIWantFollowupMs\n }\n\n get size (): number {\n return this.promises.size\n }\n\n get requestMsByMsgSize (): number {\n return this.requestMsByMsg.size\n }\n\n /**\n * Track a promise to deliver a message from a list of msgIds we are requesting\n */\n addPromise (from: PeerIdStr, msgIds: Uint8Array[]): void {\n // pick msgId randomly from the list\n const ix = Math.floor(Math.random() * msgIds.length)\n const msgId = msgIds[ix]\n const msgIdStr = this.msgIdToStrFn(msgId)\n\n let expireByPeer = this.promises.get(msgIdStr)\n if (expireByPeer == null) {\n expireByPeer = new Map()\n this.promises.set(msgIdStr, expireByPeer)\n }\n\n const now = Date.now()\n\n // If a promise for this message id and peer already exists we don't update the expiry\n if (!expireByPeer.has(from)) {\n expireByPeer.set(from, now + this.gossipsubIWantFollowupMs)\n\n if (this.metrics != null) {\n this.metrics.iwantPromiseStarted.inc(1)\n if (!this.requestMsByMsg.has(msgIdStr)) {\n this.requestMsByMsg.set(msgIdStr, now)\n }\n }\n }\n }\n\n /**\n * Returns the number of broken promises for each peer who didn't follow up on an IWANT request.\n *\n * This should be called not too often relative to the expire times, since it iterates over the whole data.\n */\n getBrokenPromises (): Map {\n const now = Date.now()\n const result = new Map()\n\n let brokenPromises = 0\n\n this.promises.forEach((expireByPeer, msgId) => {\n expireByPeer.forEach((expire, p) => {\n // the promise has been broken\n if (expire < now) {\n // add 1 to result\n result.set(p, (result.get(p) ?? 0) + 1)\n // delete from tracked promises\n expireByPeer.delete(p)\n // for metrics\n brokenPromises++\n }\n })\n // clean up empty promises for a msgId\n if (expireByPeer.size === 0) {\n this.promises.delete(msgId)\n }\n })\n\n this.metrics?.iwantPromiseBroken.inc(brokenPromises)\n\n return result\n }\n\n /**\n * Someone delivered a message, stop tracking promises for it\n */\n deliverMessage (msgIdStr: MsgIdStr, isDuplicate = false): void {\n this.trackMessage(msgIdStr)\n\n const expireByPeer = this.promises.get(msgIdStr)\n\n // Expired promise, check requestMsByMsg\n if (expireByPeer != null) {\n this.promises.delete(msgIdStr)\n\n if (this.metrics != null) {\n this.metrics.iwantPromiseResolved.inc(1)\n if (isDuplicate) this.metrics.iwantPromiseResolvedFromDuplicate.inc(1)\n this.metrics.iwantPromiseResolvedPeers.inc(expireByPeer.size)\n }\n }\n }\n\n /**\n * A message got rejected, so we can stop tracking promises and let the score penalty apply from invalid message delivery,\n * unless its an obviously invalid message.\n */\n rejectMessage (msgIdStr: MsgIdStr, reason: RejectReason): void {\n this.trackMessage(msgIdStr)\n\n // A message got rejected, so we can stop tracking promises and let the score penalty apply.\n // With the expection of obvious invalid messages\n switch (reason) {\n case RejectReason.Error:\n return\n default:\n break\n }\n\n this.promises.delete(msgIdStr)\n }\n\n clear (): void {\n this.promises.clear()\n }\n\n prune (): void {\n const maxMs = Date.now() - this.requestMsByMsgExpire\n let count = 0\n\n for (const [k, v] of this.requestMsByMsg.entries()) {\n if (v < maxMs) {\n // messages that stay too long in the requestMsByMsg map, delete\n this.requestMsByMsg.delete(k)\n count++\n } else {\n // recent messages, keep them\n // sort by insertion order\n break\n }\n }\n\n this.metrics?.iwantMessagePruned.inc(count)\n }\n\n private trackMessage (msgIdStr: MsgIdStr): void {\n if (this.metrics != null) {\n const requestMs = this.requestMsByMsg.get(msgIdStr)\n if (requestMs !== undefined) {\n this.metrics.iwantPromiseDeliveryTime.observe((Date.now() - requestMs) / 1000)\n this.requestMsByMsg.delete(msgIdStr)\n }\n }\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH')\n }\n return randB(length)\n}\n","import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n\nexport function isPromise (thing: any): thing is Promise {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n","import { ed25519 as ed } from '@noble/curves/ed25519'\nimport type { Uint8ArrayKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32\nconst PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed (seed: Uint8Array): Uint8ArrayKeyPair {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw)\n}\n\nexport function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH)\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i]\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i]\n }\n return privateKey\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","/* eslint-env browser */\n\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get (win = globalThis) {\n const nativeCrypto = win.crypto\n\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n 'Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n","import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\n\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' }\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions): AESCipher {\n const algorithm = opts?.algorithm ?? 'AES-GCM'\n let keyLength = opts?.keyLength ?? 16\n const nonceLength = opts?.nonceLength ?? 12\n const digest = opts?.digest ?? 'SHA-256'\n const saltLength = opts?.saltLength ?? 16\n const iterations = opts?.iterations ?? 32767\n\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n }\n } else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt'])\n }\n\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data)\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)])\n }\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = data.subarray(0, saltLength)\n const nonce = data.subarray(saltLength, saltLength + nonceLength)\n const ciphertext = data.subarray(saltLength + nonceLength)\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt'])\n }\n } else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt'])\n }\n\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext)\n return new Uint8Array(plaintext)\n }\n\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n","import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\nimport type { Multibase } from 'multiformats'\n\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter (privateKey: Uint8Array, password: string): Promise> {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = (): Codec => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { isPromise } from '../util.js'\nimport * as crypto from './ed25519.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Ed25519PublicKey {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id (): Promise {\n const encoding = identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n }\n\n bytes = ensureKey(bytes, crypto.privateKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const { privateKey, publicKey } = crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array): Promise {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE')\n }\n return key\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport * as utils from './rsa-utils.js'\nimport type { JWKKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport { utils }\n\nexport async function generateKey (bits: number): Promise {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey): Promise {\n return webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\nexport function keySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE')\n } else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n","import { CodeError } from '@libp2p/interface'\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2'\nimport { sha512 } from '@noble/hashes/sha512'\nimport * as asn1js from 'asn1js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport { type RsaPrivateKey, unmarshalRsaPrivateKey } from './rsa-class.js'\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value\n\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n }\n\n return key\n}\n\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value\n\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n }\n}\n\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\nfunction bnToBuf (bn: bigint): Uint8Array {\n let hex = bn.toString(16)\n\n if (hex.length % 2 > 0) {\n hex = `0${hex}`\n }\n\n const len = hex.length / 2\n const u8 = new Uint8Array(len)\n\n let i = 0\n let j = 0\n\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16)\n i += 1\n j += 2\n }\n\n return u8\n}\n\nfunction bufToBn (u8: Uint8Array): bigint {\n const hex: string[] = []\n\n u8.forEach(function (i) {\n let h = i.toString(16)\n\n if (h.length % 2 > 0) {\n h = `0${h}`\n }\n\n hex.push(h)\n })\n\n return BigInt('0x' + hex.join(''))\n}\n\nconst SALT_LENGTH = 16\nconst KEY_SIZE = 32\nconst ITERATIONS = 10000\n\nexport async function exportToPem (privateKey: RsaPrivateKey, password: string): Promise {\n const crypto = webcrypto.get()\n\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n })\n\n const keyBuf = keyWrapper.toBER()\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength)\n const salt = randomBytes(SALT_LENGTH)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n }\n )\n\n const iv = randomBytes(16)\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt'])\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr)\n\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n })\n\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n })\n\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n })\n\n const finalWrapperBuf = finalWrapper.toBER()\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength)\n\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n')\n}\n\nexport async function importFromPem (pem: string, password: string): Promise {\n const crypto = webcrypto.get()\n let plaintext: Uint8Array\n\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n const {\n iv,\n salt,\n iterations,\n keySize,\n cipherText\n } = findEncryptedPEMData(result)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: iterations,\n dkLen: keySize\n }\n )\n\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt'])\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText))\n\n const { result: decryptedResult } = asn1js.fromBER(decrypted)\n plaintext = findPEMData(decryptedResult)\n } else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n plaintext = findPEMData(result)\n } else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS')\n }\n\n return unmarshalRsaPrivateKey(plaintext)\n}\n\nfunction findEncryptedPEMData (root: any): { cipherText: Uint8Array, iv: Uint8Array, salt: Uint8Array, iterations: number, keySize: number } {\n const encryptionAlgorithm = root.valueBlock.value[0]\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString()\n\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS')\n }\n\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0]\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString()\n\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS')\n }\n\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1]\n\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue())\n\n let iterations = ITERATIONS\n let keySize = KEY_SIZE\n\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number((pbkdf2Params.valueBlock.value[1] as asn1js.Integer).toBigInt())\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt())\n } else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS')\n }\n\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1]\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString()\n\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n } else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS')\n }\n\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue())\n\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n }\n}\n\nfunction findPEMData (seq: any): Uint8Array {\n return toUint8Array(seq.valueBlock.value[2].getValue())\n}\n\nfunction toUint8Array (buf: ArrayBuffer): Uint8Array {\n return new Uint8Array(buf, 0, buf.byteLength)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport * as crypto from './rsa.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const MAX_RSA_KEY_SIZE = 8192\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean | boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret (): Uint8Array {\n return crypto.getRandomValues(16)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): RsaPublicKey {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export (password: string, format = 'pkcs-8'): Promise> {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password)\n } else if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array): Promise {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array): RsaPublicKey {\n const jwk = crypto.utils.pkixToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey): Promise {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number): Promise {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.generateKey(bits)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { isPromise } from '../util.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign (key: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.sign(p.digest, key).toDERRawBytes()\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.verify(sig, p.digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array): void {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array): void {\n try {\n secp.ProjectivePoint.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\nimport * as crypto from './secp256k1.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Secp256k1PublicKey {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const privateKeyBytes = crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport * as Ed25519 from './ed25519-class.js'\nimport generateEphemeralKeyPair from './ephemeral-keys.js'\nimport { importer } from './importer.js'\nimport { keyStretcher } from './key-stretcher.js'\nimport * as keysPBM from './keys.js'\nimport * as RSA from './rsa-class.js'\nimport { importFromPem } from './rsa-utils.js'\nimport * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js'\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js'\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js'\nexport type { JWKKeyPair } from './interface.js'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string): CodeError> {\n const supported = Object.keys(supportedKeys).join(' / ')\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE')\n}\n\nfunction typeToKey (type: string): typeof RSA | typeof Ed25519 | typeof Secp256k1 {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise {\n return typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE')\n }\n\n return Ed25519.generateKeyPairFromSeed(seed)\n}\n\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown')\n }\n}\n\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise {\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA')\n }\n}\n\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey (encryptedKey: string, password: string): Promise {\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT')\n }\n\n return importFromPem(encryptedKey, password)\n}\n","import { randomBytes } from '@libp2p/crypto'\nimport { marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { StrictSign, StrictNoSign, type Message, type PublicKey, type PeerId } from '@libp2p/interface'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RPC } from '../message/rpc.js'\nimport { type PublishConfig, PublishConfigType, type TopicStr, ValidateError } from '../types.js'\n\nexport const SignPrefix = uint8ArrayFromString('libp2p-pubsub:')\n\nexport interface RawMessageAndMessage {\n raw: RPC.Message\n msg: Message\n}\n\nexport async function buildRawMessage (\n publishConfig: PublishConfig,\n topic: TopicStr,\n originalData: Uint8Array,\n transformedData: Uint8Array\n): Promise {\n switch (publishConfig.type) {\n case PublishConfigType.Signing: {\n const rpcMsg: RPC.Message = {\n from: publishConfig.author.toBytes(),\n data: transformedData,\n seqno: randomBytes(8),\n topic,\n signature: undefined, // Exclude signature field for signing\n key: undefined // Exclude key field for signing\n }\n\n // Get the message in bytes, and prepend with the pubsub prefix\n // the signature is over the bytes \"libp2p-pubsub:\"\n const bytes = uint8ArrayConcat([SignPrefix, RPC.Message.encode(rpcMsg)])\n\n rpcMsg.signature = await publishConfig.privateKey.sign(bytes)\n rpcMsg.key = publishConfig.key\n\n const msg: Message = {\n type: 'signed',\n from: publishConfig.author,\n data: originalData,\n sequenceNumber: BigInt(`0x${uint8ArrayToString(rpcMsg.seqno as Uint8Array, 'base16')}`),\n topic,\n signature: rpcMsg.signature,\n key: rpcMsg.key\n }\n return {\n raw: rpcMsg,\n msg\n }\n }\n\n case PublishConfigType.Anonymous: {\n return {\n raw: {\n from: undefined,\n data: transformedData,\n seqno: undefined,\n topic,\n signature: undefined,\n key: undefined\n },\n msg: {\n type: 'unsigned',\n data: originalData,\n topic\n }\n }\n }\n\n default:\n throw new Error('Unreachable')\n }\n}\n\nexport type ValidationResult = { valid: true, message: Message } | { valid: false, error: ValidateError }\n\nexport async function validateToRawMessage (\n signaturePolicy: typeof StrictNoSign | typeof StrictSign,\n msg: RPC.Message\n): Promise {\n // If strict-sign, verify all\n // If anonymous (no-sign), ensure no preven\n\n switch (signaturePolicy) {\n case StrictNoSign:\n if (msg.signature != null) return { valid: false, error: ValidateError.SignaturePresent }\n if (msg.seqno != null) return { valid: false, error: ValidateError.SeqnoPresent }\n if (msg.key != null) return { valid: false, error: ValidateError.FromPresent }\n\n return { valid: true, message: { type: 'unsigned', topic: msg.topic, data: msg.data ?? new Uint8Array(0) } }\n\n case StrictSign: {\n // Verify seqno\n if (msg.seqno == null) return { valid: false, error: ValidateError.InvalidSeqno }\n if (msg.seqno.length !== 8) {\n return { valid: false, error: ValidateError.InvalidSeqno }\n }\n\n if (msg.signature == null) return { valid: false, error: ValidateError.InvalidSignature }\n if (msg.from == null) return { valid: false, error: ValidateError.InvalidPeerId }\n\n let fromPeerId: PeerId\n try {\n // TODO: Fix PeerId types\n fromPeerId = peerIdFromBytes(msg.from)\n } catch (e) {\n return { valid: false, error: ValidateError.InvalidPeerId }\n }\n\n // - check from defined\n // - transform source to PeerId\n // - parse signature\n // - get .key, else from source\n // - check key == source if present\n // - verify sig\n\n let publicKey: PublicKey\n if (msg.key != null) {\n publicKey = unmarshalPublicKey(msg.key)\n // TODO: Should `fromPeerId.pubKey` be optional?\n if (fromPeerId.publicKey !== undefined && !uint8ArrayEquals(publicKey.bytes, fromPeerId.publicKey)) {\n return { valid: false, error: ValidateError.InvalidPeerId }\n }\n } else {\n if (fromPeerId.publicKey == null) {\n return { valid: false, error: ValidateError.InvalidPeerId }\n }\n publicKey = unmarshalPublicKey(fromPeerId.publicKey)\n }\n\n const rpcMsgPreSign: RPC.Message = {\n from: msg.from,\n data: msg.data,\n seqno: msg.seqno,\n topic: msg.topic,\n signature: undefined, // Exclude signature field for signing\n key: undefined // Exclude key field for signing\n }\n\n // Get the message in bytes, and prepend with the pubsub prefix\n // the signature is over the bytes \"libp2p-pubsub:\"\n const bytes = uint8ArrayConcat([SignPrefix, RPC.Message.encode(rpcMsgPreSign)])\n\n if (!(await publicKey.verify(bytes, msg.signature))) {\n return { valid: false, error: ValidateError.InvalidSignature }\n }\n\n return {\n valid: true,\n message: {\n type: 'signed',\n from: fromPeerId,\n data: msg.data ?? new Uint8Array(0),\n sequenceNumber: BigInt(`0x${uint8ArrayToString(msg.seqno, 'base16')}`),\n topic: msg.topic,\n signature: msg.signature,\n key: msg.key ?? marshalPublicKey(publicKey)\n }\n }\n }\n\n default:\n throw new Error('Unreachable')\n }\n}\n","import type { RPC } from '../message/rpc.js'\n\n/**\n * Create a gossipsub RPC object\n */\nexport function createGossipRpc (messages: RPC.Message[] = [], control?: Partial): RPC {\n return {\n subscriptions: [],\n messages,\n control: control !== undefined\n ? {\n graft: control.graft ?? [],\n prune: control.prune ?? [],\n ihave: control.ihave ?? [],\n iwant: control.iwant ?? []\n }\n : undefined\n }\n}\n\nexport function ensureControl (rpc: RPC): Required {\n if (rpc.control === undefined) {\n rpc.control = {\n graft: [],\n prune: [],\n ihave: [],\n iwant: []\n }\n }\n\n return rpc as Required\n}\n","import { toString } from 'uint8arrays/to-string'\n\n/**\n * Browser friendly function to convert Uint8Array message id to base64 string.\n */\nexport function messageIdToString (msgId: Uint8Array): string {\n return toString(msgId, 'base64')\n}\n","/**\n * Pseudo-randomly shuffles an array\n *\n * Mutates the input array\n */\nexport function shuffle (arr: T[]): T[] {\n if (arr.length <= 1) {\n return arr\n }\n const randInt = (): number => {\n return Math.floor(Math.random() * Math.floor(arr.length))\n }\n\n for (let i = 0; i < arr.length; i++) {\n const j = randInt()\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n }\n return arr\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { randomBytes } from '@libp2p/crypto'\nimport { CodeError } from '@libp2p/interface'\nimport { peerIdFromBytes, peerIdFromKeys } from '@libp2p/peer-id'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { codes } from './errors.js'\nimport type { Message, PubSubRPCMessage } from '@libp2p/interface'\n\n/**\n * Generate a random sequence number\n */\nexport function randomSeqno (): bigint {\n return BigInt(`0x${uint8ArrayToString(randomBytes(8), 'base16')}`)\n}\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport const msgId = (key: Uint8Array, seqno: bigint): Uint8Array => {\n const seqnoBytes = uint8ArrayFromString(seqno.toString(16).padStart(16, '0'), 'base16')\n\n const msgId = new Uint8Array(key.length + seqnoBytes.length)\n msgId.set(key, 0)\n msgId.set(seqnoBytes, key.length)\n\n return msgId\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport const noSignMsgId = (data: Uint8Array): Uint8Array | Promise => {\n return sha256.encode(data)\n}\n\n/**\n * Check if any member of the first set is also a member\n * of the second set\n */\nexport const anyMatch = (a: Set | number[], b: Set | number[]): boolean => {\n let bHas\n if (Array.isArray(b)) {\n bHas = (val: number) => b.includes(val)\n } else {\n bHas = (val: number) => b.has(val)\n }\n\n for (const val of a) {\n if (bHas(val)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Make everything an array\n */\nexport const ensureArray = function (maybeArray: T | T[]): T[] {\n if (!Array.isArray(maybeArray)) {\n return [maybeArray]\n }\n\n return maybeArray\n}\n\nconst isSigned = async (message: PubSubRPCMessage): Promise => {\n if ((message.sequenceNumber == null) || (message.from == null) || (message.signature == null)) {\n return false\n }\n // if a public key is present in the `from` field, the message should be signed\n const fromID = peerIdFromBytes(message.from)\n if (fromID.publicKey != null) {\n return true\n }\n\n if (message.key != null) {\n const signingID = await peerIdFromKeys(message.key)\n return signingID.equals(fromID)\n }\n\n return false\n}\n\nexport const toMessage = async (message: PubSubRPCMessage): Promise => {\n if (message.from == null) {\n throw new CodeError('RPC message was missing from', codes.ERR_MISSING_FROM)\n }\n\n if (!await isSigned(message)) {\n return {\n type: 'unsigned',\n topic: message.topic ?? '',\n data: message.data ?? new Uint8Array(0)\n }\n }\n\n const from = peerIdFromBytes(message.from)\n\n const msg: Message = {\n type: 'signed',\n from: peerIdFromBytes(message.from),\n topic: message.topic ?? '',\n sequenceNumber: bigIntFromBytes(message.sequenceNumber ?? new Uint8Array(0)),\n data: message.data ?? new Uint8Array(0),\n signature: message.signature ?? new Uint8Array(0),\n key: message.key ?? from.publicKey ?? new Uint8Array(0)\n }\n\n if (msg.key.length === 0) {\n throw new CodeError('Signed RPC message was missing key', codes.ERR_MISSING_KEY)\n }\n\n return msg\n}\n\nexport const toRpcMessage = (message: Message): PubSubRPCMessage => {\n if (message.type === 'signed') {\n return {\n from: message.from.multihash.bytes,\n data: message.data,\n sequenceNumber: bigIntToBytes(message.sequenceNumber),\n topic: message.topic,\n signature: message.signature,\n key: message.key\n }\n }\n\n return {\n data: message.data,\n topic: message.topic\n }\n}\n\nexport const bigIntToBytes = (num: bigint): Uint8Array => {\n let str = num.toString(16)\n\n if (str.length % 2 !== 0) {\n str = `0${str}`\n }\n\n return uint8ArrayFromString(str, 'base16')\n}\n\nexport const bigIntFromBytes = (num: Uint8Array): bigint => {\n return BigInt(`0x${uint8ArrayToString(num, 'base16')}`)\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import { msgId } from '@libp2p/pubsub/utils'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport type { Message } from '@libp2p/interface'\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport function msgIdFnStrictSign (msg: Message): Uint8Array {\n if (msg.type !== 'signed') {\n throw new Error('expected signed message type')\n }\n // Should never happen\n if (msg.sequenceNumber == null) throw Error('missing seqno field')\n\n // TODO: Should use .from here or key?\n return msgId(msg.from.toBytes(), msg.sequenceNumber)\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport async function msgIdFnStrictNoSign (msg: Message): Promise {\n return sha256.encode(msg.data)\n}\n","import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16)\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n","import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [777, V, 'memory']\n]\n\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\n}\n\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol (proto: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n","/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport { IpNet } from '@chainsafe/netmask'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf)\n case 42: // ipv6zone\n return bytes2str(buf)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf)\n\n case 421: // ipfs\n return bytes2mh(buf)\n case 444: // onion\n return bytes2onion(buf)\n case 445: // onion3\n return bytes2onion(buf)\n case 466: // certhash\n return bytes2mb(buf)\n default:\n return uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str)\n case 41: // ipv6\n return ip2bytes(str)\n case 42: // ipv6zone\n return str2bytes(str)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str)\n\n case 421: // ipfs\n return mh2bytes(str)\n case 444: // onion\n return onion2bytes(str)\n case 445: // onion3\n return onion32bytes(str)\n case 466: // certhash\n return mb2bytes(str)\n default:\n return uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value\n }\n if (code === ipcidrProtocol.code) {\n mask = value\n }\n })\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr')\n }\n return new IpNet(addr, mask)\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length)\n if (ipString == null) {\n throw new Error('ipBuff is required')\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ipString\n}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.encodingLength(size))\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\n\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length))\n return uint8ArrayConcat([size, mh], size.length + mh.length)\n}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\n const mb = anybaseDecoder.decode(mbstr)\n const size = Uint8Array.from(varint.encode(mb.length))\n return uint8ArrayConcat([size, mb], size.length + mb.length)\n}\nfunction bytes2mb (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.encodingLength(size))\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.encodingLength(size))\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.slice(0, buf.length - 2)\n const portBytes = buf.slice(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n","import { convertToString } from '@multiformats/multiaddr/convert'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n// Protocols https://github.com/multiformats/multiaddr/blob/master/protocols.csv\n// code size name\n// 4 32 ip4\n// 41 128 ip6\nenum Protocol {\n ip4 = 4,\n ip6 = 41\n}\n\nexport function multiaddrToIPStr (multiaddr: Multiaddr): string | null {\n for (const tuple of multiaddr.tuples()) {\n switch (tuple[0]) {\n case Protocol.ip4:\n case Protocol.ip6:\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return convertToString(tuple[0], tuple[1]!)\n default:\n break\n }\n }\n\n return null\n}\n","interface SimpleTimeCacheOpts {\n validityMs: number\n}\n\ninterface CacheValue {\n value: T\n validUntilMs: number\n}\n\n/**\n * This is similar to https://github.com/daviddias/time-cache/blob/master/src/index.js\n * for our own need, we don't use lodash throttle to improve performance.\n * This gives 4x - 5x performance gain compared to npm TimeCache\n */\nexport class SimpleTimeCache {\n private readonly entries = new Map>()\n private readonly validityMs: number\n\n constructor (opts: SimpleTimeCacheOpts) {\n this.validityMs = opts.validityMs\n\n // allow negative validityMs so that this does not cache anything, spec test compliance.spec.js\n // sends duplicate messages and expect peer to receive all. Application likely uses positive validityMs\n }\n\n get size (): number {\n return this.entries.size\n }\n\n /** Returns true if there was a key collision and the entry is dropped */\n put (key: string | number, value: T): boolean {\n if (this.entries.has(key)) {\n // Key collisions break insertion order in the entries cache, which break prune logic.\n // prune relies on each iterated entry to have strictly ascending validUntilMs, else it\n // won't prune expired entries and SimpleTimeCache will grow unexpectedly.\n // As of Oct 2022 NodeJS v16, inserting the same key twice with different value does not\n // change the key position in the iterator stream. A unit test asserts this behaviour.\n return true\n }\n\n this.entries.set(key, { value, validUntilMs: Date.now() + this.validityMs })\n return false\n }\n\n prune (): void {\n const now = Date.now()\n\n for (const [k, v] of this.entries.entries()) {\n if (v.validUntilMs < now) {\n this.entries.delete(k)\n } else {\n // Entries are inserted with strictly ascending validUntilMs.\n // Stop early to save iterations\n break\n }\n }\n }\n\n has (key: string): boolean {\n return this.entries.has(key)\n }\n\n get (key: string | number): T | undefined {\n const value = this.entries.get(key)\n return (value != null) && value.validUntilMs >= Date.now() ? value.value : undefined\n }\n\n clear (): void {\n this.entries.clear()\n }\n}\n","import { CustomEvent, TypedEventEmitter, StrictSign, StrictNoSign, TopicValidatorResult } from '@libp2p/interface'\nimport { peerIdFromBytes, peerIdFromString } from '@libp2p/peer-id'\nimport { encode } from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport { pushable } from 'it-pushable'\nimport * as constants from './constants.js'\nimport {\n ACCEPT_FROM_WHITELIST_DURATION_MS,\n ACCEPT_FROM_WHITELIST_MAX_MESSAGES,\n ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE,\n BACKOFF_SLACK\n} from './constants.js'\nimport { type DecodeRPCLimits, defaultDecodeRpcLimits } from './message/decodeRpc.js'\nimport { RPC } from './message/rpc.js'\nimport { MessageCache, type MessageCacheRecord } from './message-cache.js'\nimport {\n ChurnReason,\n getMetrics,\n IHaveIgnoreReason,\n InclusionReason,\n type Metrics,\n type MetricsRegister,\n ScorePenalty,\n type TopicStrToLabel,\n type ToSendGroupCount\n} from './metrics.js'\nimport {\n PeerScore,\n type PeerScoreParams,\n type PeerScoreThresholds,\n createPeerScoreParams,\n createPeerScoreThresholds,\n type PeerScoreStatsDump\n} from './score/index.js'\nimport { computeAllPeersScoreWeights } from './score/scoreMetrics.js'\nimport { InboundStream, OutboundStream } from './stream.js'\nimport { IWantTracer } from './tracer.js'\nimport {\n type MsgIdFn,\n type PublishConfig,\n type TopicStr,\n type MsgIdStr,\n ValidateError,\n type PeerIdStr,\n MessageStatus,\n RejectReason,\n type RejectReasonObj,\n type FastMsgIdFn,\n type AddrInfo,\n type DataTransform,\n rejectReasonFromAcceptance,\n type MsgIdToStrFn,\n type MessageId,\n type PublishOpts\n} from './types.js'\nimport { buildRawMessage, validateToRawMessage } from './utils/buildRawMessage.js'\nimport { createGossipRpc, ensureControl } from './utils/create-gossip-rpc.js'\nimport { shuffle, messageIdToString } from './utils/index.js'\nimport { msgIdFnStrictNoSign, msgIdFnStrictSign } from './utils/msgIdFn.js'\nimport { multiaddrToIPStr } from './utils/multiaddr.js'\nimport { getPublishConfigFromPeerId } from './utils/publishConfig.js'\nimport { removeFirstNItemsFromSet, removeItemsFromSet } from './utils/set.js'\nimport { SimpleTimeCache } from './utils/time-cache.js'\nimport type { GossipsubOptsSpec } from './config.js'\nimport type {\n Connection, Stream, PeerId, Peer, PeerStore,\n Message,\n PublishResult,\n PubSub,\n PubSubEvents,\n PubSubInit,\n SubscriptionChangeData,\n TopicValidatorFn,\n Logger,\n ComponentLogger,\n Topology\n} from '@libp2p/interface'\nimport type { ConnectionManager, IncomingStreamData, Registrar } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\ntype ConnectionDirection = 'inbound' | 'outbound'\n\ntype ReceivedMessageResult =\n | { code: MessageStatus.duplicate, msgIdStr: MsgIdStr }\n | ({ code: MessageStatus.invalid, msgIdStr?: MsgIdStr } & RejectReasonObj)\n | { code: MessageStatus.valid, messageId: MessageId, msg: Message }\n\nexport const multicodec: string = constants.GossipsubIDv11\n\nexport interface GossipsubOpts extends GossipsubOptsSpec, PubSubInit {\n /** if dial should fallback to floodsub */\n fallbackToFloodsub: boolean\n /** if self-published messages should be sent to all peers */\n floodPublish: boolean\n /** serialize message once and send to all peers without control messages */\n batchPublish: boolean\n /** whether PX is enabled; this should be enabled in bootstrappers and other well connected/trusted nodes. */\n doPX: boolean\n /** peers with which we will maintain direct connections */\n directPeers: AddrInfo[]\n /**\n * If true will not forward messages to mesh peers until reportMessageValidationResult() is called.\n * Messages will be cached in mcache for some time after which they are evicted. Calling\n * reportMessageValidationResult() after the message is dropped from mcache won't forward the message.\n */\n asyncValidation: boolean\n /** Do not throw `InsufficientPeers` error if publishing to zero peers */\n allowPublishToZeroPeers: boolean\n /** Do not throw `PublishError.Duplicate` if publishing duplicate messages */\n ignoreDuplicatePublishError: boolean\n /** For a single stream, await processing each RPC before processing the next */\n awaitRpcHandler: boolean\n /** For a single RPC, await processing each message before processing the next */\n awaitRpcMessageHandler: boolean\n\n /** message id function */\n msgIdFn: MsgIdFn\n /** fast message id function */\n fastMsgIdFn: FastMsgIdFn\n /** Uint8Array message id to string function */\n msgIdToStrFn: MsgIdToStrFn\n /** override the default MessageCache */\n messageCache: MessageCache\n /** peer score parameters */\n scoreParams: Partial\n /** peer score thresholds */\n scoreThresholds: Partial\n /** customize GossipsubIWantFollowupTime in order not to apply IWANT penalties */\n gossipsubIWantFollowupMs: number\n\n /** override constants for fine tuning */\n prunePeers?: number\n pruneBackoff?: number\n unsubcribeBackoff?: number\n graftFloodThreshold?: number\n opportunisticGraftPeers?: number\n opportunisticGraftTicks?: number\n directConnectTicks?: number\n\n dataTransform?: DataTransform\n metricsRegister?: MetricsRegister | null\n metricsTopicStrToLabel?: TopicStrToLabel\n\n // Debug\n /** Prefix tag for debug logs */\n debugName?: string\n\n /**\n * Specify the maximum number of inbound gossipsub protocol\n * streams that are allowed to be open concurrently\n */\n maxInboundStreams?: number\n\n /**\n * Specify the maximum number of outbound gossipsub protocol\n * streams that are allowed to be open concurrently\n */\n maxOutboundStreams?: number\n\n /**\n * Pass true to run on transient connections - data or time-limited\n * connections that may be closed at any time such as circuit relay\n * connections.\n *\n * @default false\n */\n runOnTransientConnection?: boolean\n\n /**\n * Specify max buffer size in bytes for OutboundStream.\n * If full it will throw and reject sending any more data.\n */\n maxOutboundBufferSize?: number\n\n /**\n * Specify max size to skip decoding messages whose data\n * section exceeds this size.\n *\n */\n maxInboundDataLength?: number\n\n /**\n * If provided, only allow topics in this list\n */\n allowedTopics?: string[] | Set\n\n /**\n * Limits to bound protobuf decoding\n */\n decodeRpcLimits?: DecodeRPCLimits\n}\n\nexport interface GossipsubMessage {\n propagationSource: PeerId\n msgId: MsgIdStr\n msg: Message\n}\n\nexport interface GossipsubEvents extends PubSubEvents {\n 'gossipsub:heartbeat': CustomEvent\n 'gossipsub:message': CustomEvent\n}\n\nenum GossipStatusCode {\n started,\n stopped\n}\n\ntype GossipStatus =\n | {\n code: GossipStatusCode.started\n registrarTopologyIds: string[]\n heartbeatTimeout: ReturnType\n hearbeatStartMs: number\n }\n | {\n code: GossipStatusCode.stopped\n }\n\ninterface GossipOptions extends GossipsubOpts {\n scoreParams: PeerScoreParams\n scoreThresholds: PeerScoreThresholds\n}\n\ninterface AcceptFromWhitelistEntry {\n /** number of messages accepted since recomputing the peer's score */\n messagesAccepted: number\n /** have to recompute score after this time */\n acceptUntil: number\n}\n\nexport interface GossipSubComponents {\n peerId: PeerId\n peerStore: PeerStore\n registrar: Registrar\n connectionManager: ConnectionManager\n logger: ComponentLogger\n}\n\nexport class GossipSub extends TypedEventEmitter implements PubSub {\n /**\n * The signature policy to follow by default\n */\n public readonly globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n public multicodecs: string[] = [constants.GossipsubIDv11, constants.GossipsubIDv10]\n\n private publishConfig: PublishConfig | undefined\n\n private readonly dataTransform: DataTransform | undefined\n\n // State\n\n public readonly peers = new Set()\n public readonly streamsInbound = new Map()\n public readonly streamsOutbound = new Map()\n\n /** Ensures outbound streams are created sequentially */\n private outboundInflightQueue = pushable<{ peerId: PeerId, connection: Connection }>({ objectMode: true })\n\n /** Direct peers */\n public readonly direct = new Set()\n\n /** Floodsub peers */\n private readonly floodsubPeers = new Set()\n\n /** Cache of seen messages */\n private readonly seenCache: SimpleTimeCache\n\n /**\n * Map of peer id and AcceptRequestWhileListEntry\n */\n private readonly acceptFromWhitelist = new Map()\n\n /**\n * Map of topics to which peers are subscribed to\n */\n private readonly topics = new Map>()\n\n /**\n * List of our subscriptions\n */\n private readonly subscriptions = new Set()\n\n /**\n * Map of topic meshes\n * topic => peer id set\n */\n public readonly mesh = new Map>()\n\n /**\n * Map of topics to set of peers. These mesh peers are the ones to which we are publishing without a topic membership\n * topic => peer id set\n */\n public readonly fanout = new Map>()\n\n /**\n * Map of last publish time for fanout topics\n * topic => last publish time\n */\n private readonly fanoutLastpub = new Map()\n\n /**\n * Map of pending messages to gossip\n * peer id => control messages\n */\n public readonly gossip = new Map()\n\n /**\n * Map of control messages\n * peer id => control message\n */\n public readonly control = new Map()\n\n /**\n * Number of IHAVEs received from peer in the last heartbeat\n */\n private readonly peerhave = new Map()\n\n /** Number of messages we have asked from peer in the last heartbeat */\n private readonly iasked = new Map()\n\n /** Prune backoff map */\n private readonly backoff = new Map>()\n\n /**\n * Connection direction cache, marks peers with outbound connections\n * peer id => direction\n */\n private readonly outbound = new Map()\n private readonly msgIdFn: MsgIdFn\n\n /**\n * A fast message id function used for internal message de-duplication\n */\n private readonly fastMsgIdFn: FastMsgIdFn | undefined\n\n private readonly msgIdToStrFn: MsgIdToStrFn\n\n /** Maps fast message-id to canonical message-id */\n private readonly fastMsgIdCache: SimpleTimeCache | undefined\n\n /**\n * Short term cache for published message ids. This is used for penalizing peers sending\n * our own messages back if the messages are anonymous or use a random author.\n */\n private readonly publishedMessageIds: SimpleTimeCache\n\n /**\n * A message cache that contains the messages for last few heartbeat ticks\n */\n private readonly mcache: MessageCache\n\n /** Peer score tracking */\n public readonly score: PeerScore\n\n /**\n * Custom validator function per topic.\n * Must return or resolve quickly (< 100ms) to prevent causing penalties for late messages.\n * If you need to apply validation that may require longer times use `asyncValidation` option and callback the\n * validation result through `Gossipsub.reportValidationResult`\n */\n public readonly topicValidators = new Map()\n\n /**\n * Make this protected so child class may want to redirect to its own log.\n */\n protected readonly log: Logger\n\n /**\n * Number of heartbeats since the beginning of time\n * This allows us to amortize some resource cleanup -- eg: backoff cleanup\n */\n private heartbeatTicks = 0\n\n /**\n * Tracks IHAVE/IWANT promises broken by peers\n */\n readonly gossipTracer: IWantTracer\n\n private readonly components: GossipSubComponents\n\n private directPeerInitial: ReturnType | null = null\n\n public static multicodec: string = constants.GossipsubIDv11\n\n // Options\n readonly opts: Required\n private readonly decodeRpcLimits: DecodeRPCLimits\n\n private readonly metrics: Metrics | null\n private status: GossipStatus = { code: GossipStatusCode.stopped }\n private readonly maxInboundStreams?: number\n private readonly maxOutboundStreams?: number\n private readonly runOnTransientConnection?: boolean\n private readonly allowedTopics: Set | null\n\n private heartbeatTimer: {\n _intervalId: ReturnType | undefined\n runPeriodically(fn: () => void, period: number): void\n cancel(): void\n } | null = null\n\n constructor (components: GossipSubComponents, options: Partial = {}) {\n super()\n\n const opts = {\n fallbackToFloodsub: true,\n floodPublish: true,\n batchPublish: false,\n doPX: false,\n directPeers: [],\n D: constants.GossipsubD,\n Dlo: constants.GossipsubDlo,\n Dhi: constants.GossipsubDhi,\n Dscore: constants.GossipsubDscore,\n Dout: constants.GossipsubDout,\n Dlazy: constants.GossipsubDlazy,\n heartbeatInterval: constants.GossipsubHeartbeatInterval,\n fanoutTTL: constants.GossipsubFanoutTTL,\n mcacheLength: constants.GossipsubHistoryLength,\n mcacheGossip: constants.GossipsubHistoryGossip,\n seenTTL: constants.GossipsubSeenTTL,\n gossipsubIWantFollowupMs: constants.GossipsubIWantFollowupTime,\n prunePeers: constants.GossipsubPrunePeers,\n pruneBackoff: constants.GossipsubPruneBackoff,\n unsubcribeBackoff: constants.GossipsubUnsubscribeBackoff,\n graftFloodThreshold: constants.GossipsubGraftFloodThreshold,\n opportunisticGraftPeers: constants.GossipsubOpportunisticGraftPeers,\n opportunisticGraftTicks: constants.GossipsubOpportunisticGraftTicks,\n directConnectTicks: constants.GossipsubDirectConnectTicks,\n ...options,\n scoreParams: createPeerScoreParams(options.scoreParams),\n scoreThresholds: createPeerScoreThresholds(options.scoreThresholds)\n }\n\n this.components = components\n this.decodeRpcLimits = opts.decodeRpcLimits ?? defaultDecodeRpcLimits\n\n this.globalSignaturePolicy = opts.globalSignaturePolicy ?? StrictSign\n\n // Also wants to get notified of peers connected using floodsub\n if (opts.fallbackToFloodsub) {\n this.multicodecs.push(constants.FloodsubID)\n }\n\n // From pubsub\n this.log = components.logger.forComponent(opts.debugName ?? 'libp2p:gossipsub')\n\n // Gossipsub\n\n this.opts = opts as Required\n this.direct = new Set(opts.directPeers.map((p) => p.id.toString()))\n this.seenCache = new SimpleTimeCache({ validityMs: opts.seenTTL })\n this.publishedMessageIds = new SimpleTimeCache({ validityMs: opts.seenTTL })\n\n if (options.msgIdFn != null) {\n // Use custom function\n this.msgIdFn = options.msgIdFn\n } else {\n switch (this.globalSignaturePolicy) {\n case StrictSign:\n this.msgIdFn = msgIdFnStrictSign\n break\n case StrictNoSign:\n this.msgIdFn = msgIdFnStrictNoSign\n break\n default:\n throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)\n }\n }\n\n if (options.fastMsgIdFn != null) {\n this.fastMsgIdFn = options.fastMsgIdFn\n this.fastMsgIdCache = new SimpleTimeCache({ validityMs: opts.seenTTL })\n }\n\n // By default, gossipsub only provide a browser friendly function to convert Uint8Array message id to string.\n this.msgIdToStrFn = options.msgIdToStrFn ?? messageIdToString\n\n this.mcache = options.messageCache ?? new MessageCache(opts.mcacheGossip, opts.mcacheLength, this.msgIdToStrFn)\n\n if (options.dataTransform != null) {\n this.dataTransform = options.dataTransform\n }\n\n if (options.metricsRegister != null) {\n if (options.metricsTopicStrToLabel == null) {\n throw Error('Must set metricsTopicStrToLabel with metrics')\n }\n\n // in theory, each topic has its own meshMessageDeliveriesWindow param\n // however in lodestar, we configure it mostly the same so just pick the max of positive ones\n // (some topics have meshMessageDeliveriesWindow as 0)\n const maxMeshMessageDeliveriesWindowMs = Math.max(\n ...Object.values(opts.scoreParams.topics).map((topicParam) => topicParam.meshMessageDeliveriesWindow),\n constants.DEFAULT_METRIC_MESH_MESSAGE_DELIVERIES_WINDOWS\n )\n\n const metrics = getMetrics(options.metricsRegister, options.metricsTopicStrToLabel, {\n gossipPromiseExpireSec: this.opts.gossipsubIWantFollowupMs / 1000,\n behaviourPenaltyThreshold: opts.scoreParams.behaviourPenaltyThreshold,\n maxMeshMessageDeliveriesWindowSec: maxMeshMessageDeliveriesWindowMs / 1000\n })\n\n metrics.mcacheSize.addCollect(() => { this.onScrapeMetrics(metrics) })\n for (const protocol of this.multicodecs) {\n metrics.protocolsEnabled.set({ protocol }, 1)\n }\n\n this.metrics = metrics\n } else {\n this.metrics = null\n }\n\n this.gossipTracer = new IWantTracer(this.opts.gossipsubIWantFollowupMs, this.msgIdToStrFn, this.metrics)\n\n /**\n * libp2p\n */\n this.score = new PeerScore(this.opts.scoreParams, this.metrics, this.components.logger, {\n scoreCacheValidityMs: opts.heartbeatInterval\n })\n\n this.maxInboundStreams = options.maxInboundStreams\n this.maxOutboundStreams = options.maxOutboundStreams\n this.runOnTransientConnection = options.runOnTransientConnection\n\n this.allowedTopics = (opts.allowedTopics != null) ? new Set(opts.allowedTopics) : null\n }\n\n getPeers (): PeerId[] {\n return [...this.peers.keys()].map((str) => peerIdFromString(str))\n }\n\n isStarted (): boolean {\n return this.status.code === GossipStatusCode.started\n }\n\n // LIFECYCLE METHODS\n\n /**\n * Mounts the gossipsub protocol onto the libp2p node and sends our\n * our subscriptions to every peer connected\n */\n async start (): Promise {\n // From pubsub\n if (this.isStarted()) {\n return\n }\n\n this.log('starting')\n\n this.publishConfig = await getPublishConfigFromPeerId(this.globalSignaturePolicy, this.components.peerId)\n\n // Create the outbound inflight queue\n // This ensures that outbound stream creation happens sequentially\n this.outboundInflightQueue = pushable({ objectMode: true })\n pipe(this.outboundInflightQueue, async (source) => {\n for await (const { peerId, connection } of source) {\n await this.createOutboundStream(peerId, connection)\n }\n }).catch((e) => { this.log.error('outbound inflight queue error', e) })\n\n // set direct peer addresses in the address book\n await Promise.all(\n this.opts.directPeers.map(async (p) => {\n await this.components.peerStore.merge(p.id, {\n multiaddrs: p.addrs\n })\n })\n )\n\n const registrar = this.components.registrar\n // Incoming streams\n // Called after a peer dials us\n await Promise.all(\n this.multicodecs.map(async (multicodec) =>\n registrar.handle(multicodec, this.onIncomingStream.bind(this), {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n })\n )\n )\n\n // # How does Gossipsub interact with libp2p? Rough guide from Mar 2022\n //\n // ## Setup:\n // Gossipsub requests libp2p to callback, TBD\n //\n // `this.libp2p.handle()` registers a handler for `/meshsub/1.1.0` and other Gossipsub protocols\n // The handler callback is registered in libp2p Upgrader.protocols map.\n //\n // Upgrader receives an inbound connection from some transport and (`Upgrader.upgradeInbound`):\n // - Adds encryption (NOISE in our case)\n // - Multiplex stream\n // - Create a muxer and register that for each new stream call Upgrader.protocols handler\n //\n // ## Topology\n // - new instance of Topology (unlinked to libp2p) with handlers\n // - registar.register(topology)\n\n // register protocol with topology\n // Topology callbacks called on connection manager changes\n const topology: Topology = {\n onConnect: this.onPeerConnected.bind(this),\n onDisconnect: this.onPeerDisconnected.bind(this),\n notifyOnTransient: this.runOnTransientConnection\n }\n const registrarTopologyIds = await Promise.all(\n this.multicodecs.map(async (multicodec) => registrar.register(multicodec, topology))\n )\n\n // Schedule to start heartbeat after `GossipsubHeartbeatInitialDelay`\n const heartbeatTimeout = setTimeout(this.runHeartbeat, constants.GossipsubHeartbeatInitialDelay)\n // Then, run heartbeat every `heartbeatInterval` offset by `GossipsubHeartbeatInitialDelay`\n\n this.status = {\n code: GossipStatusCode.started,\n registrarTopologyIds,\n heartbeatTimeout,\n hearbeatStartMs: Date.now() + constants.GossipsubHeartbeatInitialDelay\n }\n\n this.score.start()\n // connect to direct peers\n this.directPeerInitial = setTimeout(() => {\n Promise.resolve()\n .then(async () => {\n await Promise.all(Array.from(this.direct).map(async (id) => this.connect(id)))\n })\n .catch((err) => {\n this.log(err)\n })\n }, constants.GossipsubDirectConnectInitialDelay)\n\n this.log('started')\n }\n\n /**\n * Unmounts the gossipsub protocol and shuts down every connection\n */\n async stop (): Promise {\n this.log('stopping')\n // From pubsub\n\n if (this.status.code !== GossipStatusCode.started) {\n return\n }\n\n const { registrarTopologyIds } = this.status\n this.status = { code: GossipStatusCode.stopped }\n\n // unregister protocol and handlers\n const registrar = this.components.registrar\n await Promise.all(this.multicodecs.map(async (multicodec) => registrar.unhandle(multicodec)))\n registrarTopologyIds.forEach((id) => { registrar.unregister(id) })\n\n this.outboundInflightQueue.end()\n\n const closePromises = []\n for (const outboundStream of this.streamsOutbound.values()) {\n closePromises.push(outboundStream.close())\n }\n this.streamsOutbound.clear()\n\n for (const inboundStream of this.streamsInbound.values()) {\n closePromises.push(inboundStream.close())\n }\n this.streamsInbound.clear()\n\n await Promise.all(closePromises)\n\n this.peers.clear()\n this.subscriptions.clear()\n\n // Gossipsub\n\n if (this.heartbeatTimer != null) {\n this.heartbeatTimer.cancel()\n this.heartbeatTimer = null\n }\n\n this.score.stop()\n\n this.mesh.clear()\n this.fanout.clear()\n this.fanoutLastpub.clear()\n this.gossip.clear()\n this.control.clear()\n this.peerhave.clear()\n this.iasked.clear()\n this.backoff.clear()\n this.outbound.clear()\n this.gossipTracer.clear()\n this.seenCache.clear()\n if (this.fastMsgIdCache != null) this.fastMsgIdCache.clear()\n if (this.directPeerInitial != null) clearTimeout(this.directPeerInitial)\n\n this.log('stopped')\n }\n\n /** FOR DEBUG ONLY - Dump peer stats for all peers. Data is cloned, safe to mutate */\n dumpPeerScoreStats (): PeerScoreStatsDump {\n return this.score.dumpPeerScoreStats()\n }\n\n /**\n * On an inbound stream opened\n */\n private onIncomingStream ({ stream, connection }: IncomingStreamData): void {\n if (!this.isStarted()) {\n return\n }\n\n const peerId = connection.remotePeer\n // add peer to router\n this.addPeer(peerId, connection.direction, connection.remoteAddr)\n // create inbound stream\n this.createInboundStream(peerId, stream)\n // attempt to create outbound stream\n this.outboundInflightQueue.push({ peerId, connection })\n }\n\n /**\n * Registrar notifies an established connection with pubsub protocol\n */\n private onPeerConnected (peerId: PeerId, connection: Connection): void {\n this.metrics?.newConnectionCount.inc({ status: connection.status })\n // libp2p may emit a closed connection and never issue peer:disconnect event\n // see https://github.com/ChainSafe/js-libp2p-gossipsub/issues/398\n if (!this.isStarted() || connection.status !== 'open') {\n return\n }\n\n this.addPeer(peerId, connection.direction, connection.remoteAddr)\n this.outboundInflightQueue.push({ peerId, connection })\n }\n\n /**\n * Registrar notifies a closing connection with pubsub protocol\n */\n private onPeerDisconnected (peerId: PeerId): void {\n this.log('connection ended %p', peerId)\n this.removePeer(peerId)\n }\n\n private async createOutboundStream (peerId: PeerId, connection: Connection): Promise {\n if (!this.isStarted()) {\n return\n }\n\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n return\n }\n\n // TODO make this behavior more robust\n // This behavior is different than for inbound streams\n // If an outbound stream already exists, don't create a new stream\n if (this.streamsOutbound.has(id)) {\n return\n }\n\n try {\n const stream = new OutboundStream(\n await connection.newStream(this.multicodecs, {\n runOnTransientConnection: this.runOnTransientConnection\n }),\n (e) => { this.log.error('outbound pipe error', e) },\n { maxBufferSize: this.opts.maxOutboundBufferSize }\n )\n\n this.log('create outbound stream %p', peerId)\n\n this.streamsOutbound.set(id, stream)\n\n const protocol = stream.protocol\n if (protocol === constants.FloodsubID) {\n this.floodsubPeers.add(id)\n }\n this.metrics?.peersPerProtocol.inc({ protocol }, 1)\n\n // Immediately send own subscriptions via the newly attached stream\n if (this.subscriptions.size > 0) {\n this.log('send subscriptions to', id)\n this.sendSubscriptions(id, Array.from(this.subscriptions), true)\n }\n } catch (e) {\n this.log.error('createOutboundStream error', e)\n }\n }\n\n private createInboundStream (peerId: PeerId, stream: Stream): void {\n if (!this.isStarted()) {\n return\n }\n\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n return\n }\n\n // TODO make this behavior more robust\n // This behavior is different than for outbound streams\n // If a peer initiates a new inbound connection\n // we assume that one is the new canonical inbound stream\n const priorInboundStream = this.streamsInbound.get(id)\n if (priorInboundStream !== undefined) {\n this.log('replacing existing inbound steam %s', id)\n priorInboundStream.close().catch((err) => { this.log.error(err) })\n }\n\n this.log('create inbound stream %s', id)\n\n const inboundStream = new InboundStream(stream, { maxDataLength: this.opts.maxInboundDataLength })\n this.streamsInbound.set(id, inboundStream)\n\n this.pipePeerReadStream(peerId, inboundStream.source).catch((err) => { this.log(err) })\n }\n\n /**\n * Add a peer to the router\n */\n private addPeer (peerId: PeerId, direction: ConnectionDirection, addr: Multiaddr): void {\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n this.log('new peer %p', peerId)\n\n this.peers.add(id)\n\n // Add to peer scoring\n this.score.addPeer(id)\n const currentIP = multiaddrToIPStr(addr)\n if (currentIP !== null) {\n this.score.addIP(id, currentIP)\n } else {\n this.log('Added peer has no IP in current address %s %s', id, addr.toString())\n }\n\n // track the connection direction. Don't allow to unset outbound\n if (!this.outbound.has(id)) {\n this.outbound.set(id, direction === 'outbound')\n }\n }\n }\n\n /**\n * Removes a peer from the router\n */\n private removePeer (peerId: PeerId): void {\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n return\n }\n\n // delete peer\n this.log('delete peer %p', peerId)\n this.peers.delete(id)\n\n const outboundStream = this.streamsOutbound.get(id)\n const inboundStream = this.streamsInbound.get(id)\n\n if (outboundStream != null) {\n this.metrics?.peersPerProtocol.inc({ protocol: outboundStream.protocol }, -1)\n }\n\n // close streams\n outboundStream?.close().catch((err) => { this.log.error(err) })\n inboundStream?.close().catch((err) => { this.log.error(err) })\n\n // remove streams\n this.streamsOutbound.delete(id)\n this.streamsInbound.delete(id)\n\n // remove peer from topics map\n for (const peers of this.topics.values()) {\n peers.delete(id)\n }\n\n // Remove this peer from the mesh\n for (const [topicStr, peers] of this.mesh) {\n if (peers.delete(id)) {\n this.metrics?.onRemoveFromMesh(topicStr, ChurnReason.Dc, 1)\n }\n }\n\n // Remove this peer from the fanout\n for (const peers of this.fanout.values()) {\n peers.delete(id)\n }\n\n // Remove from floodsubPeers\n this.floodsubPeers.delete(id)\n // Remove from gossip mapping\n this.gossip.delete(id)\n // Remove from control mapping\n this.control.delete(id)\n // Remove from backoff mapping\n this.outbound.delete(id)\n\n // Remove from peer scoring\n this.score.removePeer(id)\n\n this.acceptFromWhitelist.delete(id)\n }\n\n // API METHODS\n\n get started (): boolean {\n return this.status.code === GossipStatusCode.started\n }\n\n /**\n * Get a the peer-ids in a topic mesh\n */\n getMeshPeers (topic: TopicStr): PeerIdStr[] {\n const peersInTopic = this.mesh.get(topic)\n return (peersInTopic != null) ? Array.from(peersInTopic) : []\n }\n\n /**\n * Get a list of the peer-ids that are subscribed to one topic.\n */\n getSubscribers (topic: TopicStr): PeerId[] {\n const peersInTopic = this.topics.get(topic)\n return ((peersInTopic != null) ? Array.from(peersInTopic) : []).map((str) => peerIdFromString(str))\n }\n\n /**\n * Get the list of topics which the peer is subscribed to.\n */\n getTopics (): TopicStr[] {\n return Array.from(this.subscriptions)\n }\n\n // TODO: Reviewing Pubsub API\n\n // MESSAGE METHODS\n\n /**\n * Responsible for processing each RPC message received by other peers.\n */\n private async pipePeerReadStream (peerId: PeerId, stream: AsyncIterable): Promise {\n try {\n await pipe(stream, async (source) => {\n for await (const data of source) {\n try {\n // TODO: Check max gossip message size, before decodeRpc()\n const rpcBytes = data.subarray()\n // Note: This function may throw, it must be wrapped in a try {} catch {} to prevent closing the stream.\n // TODO: What should we do if the entire RPC is invalid?\n const rpc = RPC.decode(rpcBytes, {\n limits: {\n subscriptions: this.decodeRpcLimits.maxSubscriptions,\n messages: this.decodeRpcLimits.maxMessages,\n control$: {\n ihave: this.decodeRpcLimits.maxIhaveMessageIDs,\n iwant: this.decodeRpcLimits.maxIwantMessageIDs,\n graft: this.decodeRpcLimits.maxControlMessages,\n prune: this.decodeRpcLimits.maxControlMessages,\n prune$: {\n peers: this.decodeRpcLimits.maxPeerInfos\n }\n }\n }\n })\n\n this.metrics?.onRpcRecv(rpc, rpcBytes.length)\n\n // Since processRpc may be overridden entirely in unsafe ways,\n // the simplest/safest option here is to wrap in a function and capture all errors\n // to prevent a top-level unhandled exception\n // This processing of rpc messages should happen without awaiting full validation/execution of prior messages\n if (this.opts.awaitRpcHandler) {\n try {\n await this.handleReceivedRpc(peerId, rpc)\n } catch (err) {\n this.metrics?.onRpcRecvError()\n this.log(err)\n }\n } else {\n this.handleReceivedRpc(peerId, rpc).catch((err) => {\n this.metrics?.onRpcRecvError()\n this.log(err)\n })\n }\n } catch (e) {\n this.metrics?.onRpcDataError()\n this.log(e as Error)\n }\n }\n })\n } catch (err) {\n this.metrics?.onPeerReadStreamError()\n this.handlePeerReadStreamError(err as Error, peerId)\n }\n }\n\n /**\n * Handle error when read stream pipe throws, less of the functional use but more\n * to for testing purposes to spy on the error handling\n * */\n private handlePeerReadStreamError (err: Error, peerId: PeerId): void {\n this.log.error(err)\n this.onPeerDisconnected(peerId)\n }\n\n /**\n * Handles an rpc request from a peer\n */\n public async handleReceivedRpc (from: PeerId, rpc: RPC): Promise {\n // Check if peer is graylisted in which case we ignore the event\n if (!this.acceptFrom(from.toString())) {\n this.log('received message from unacceptable peer %p', from)\n this.metrics?.rpcRecvNotAccepted.inc()\n return\n }\n\n const subscriptions = (rpc.subscriptions != null) ? rpc.subscriptions.length : 0\n const messages = (rpc.messages != null) ? rpc.messages.length : 0\n let ihave = 0\n let iwant = 0\n let graft = 0\n let prune = 0\n if (rpc.control != null) {\n if (rpc.control.ihave != null) ihave = rpc.control.ihave.length\n if (rpc.control.iwant != null) iwant = rpc.control.iwant.length\n if (rpc.control.graft != null) graft = rpc.control.graft.length\n if (rpc.control.prune != null) prune = rpc.control.prune.length\n }\n this.log(\n `rpc.from ${from.toString()} subscriptions ${subscriptions} messages ${messages} ihave ${ihave} iwant ${iwant} graft ${graft} prune ${prune}`\n )\n\n // Handle received subscriptions\n if ((rpc.subscriptions != null) && rpc.subscriptions.length > 0) {\n // update peer subscriptions\n\n const subscriptions: Array<{ topic: TopicStr, subscribe: boolean }> = []\n\n rpc.subscriptions.forEach((subOpt) => {\n const topic = subOpt.topic\n const subscribe = subOpt.subscribe === true\n\n if (topic != null) {\n if ((this.allowedTopics != null) && !this.allowedTopics.has(topic)) {\n // Not allowed: subscription data-structures are not bounded by topic count\n // TODO: Should apply behaviour penalties?\n return\n }\n\n this.handleReceivedSubscription(from, topic, subscribe)\n\n subscriptions.push({ topic, subscribe })\n }\n })\n\n this.safeDispatchEvent('subscription-change', {\n detail: { peerId: from, subscriptions }\n })\n }\n\n // Handle messages\n // TODO: (up to limit)\n for (const message of rpc.messages) {\n if ((this.allowedTopics != null) && !this.allowedTopics.has(message.topic)) {\n // Not allowed: message cache data-structures are not bounded by topic count\n // TODO: Should apply behaviour penalties?\n continue\n }\n\n const handleReceivedMessagePromise = this.handleReceivedMessage(from, message)\n // Should never throw, but handle just in case\n .catch((err) => {\n this.metrics?.onMsgRecvError(message.topic)\n this.log(err)\n })\n\n if (this.opts.awaitRpcMessageHandler) {\n await handleReceivedMessagePromise\n }\n }\n\n // Handle control messages\n if (rpc.control != null) {\n await this.handleControlMessage(from.toString(), rpc.control)\n }\n }\n\n /**\n * Handles a subscription change from a peer\n */\n private handleReceivedSubscription (from: PeerId, topic: TopicStr, subscribe: boolean): void {\n this.log('subscription update from %p topic %s', from, topic)\n\n let topicSet = this.topics.get(topic)\n if (topicSet == null) {\n topicSet = new Set()\n this.topics.set(topic, topicSet)\n }\n\n if (subscribe) {\n // subscribe peer to new topic\n topicSet.add(from.toString())\n } else {\n // unsubscribe from existing topic\n topicSet.delete(from.toString())\n }\n\n // TODO: rust-libp2p has A LOT more logic here\n }\n\n /**\n * Handles a newly received message from an RPC.\n * May forward to all peers in the mesh.\n */\n private async handleReceivedMessage (from: PeerId, rpcMsg: RPC.Message): Promise {\n this.metrics?.onMsgRecvPreValidation(rpcMsg.topic)\n\n const validationResult = await this.validateReceivedMessage(from, rpcMsg)\n\n this.metrics?.onPrevalidationResult(rpcMsg.topic, validationResult.code)\n\n const validationCode = validationResult.code\n switch (validationCode) {\n case MessageStatus.duplicate:\n // Report the duplicate\n this.score.duplicateMessage(from.toString(), validationResult.msgIdStr, rpcMsg.topic)\n // due to the collision of fastMsgIdFn, 2 different messages may end up the same fastMsgId\n // so we need to also mark the duplicate message as delivered or the promise is not resolved\n // and peer gets penalized. See https://github.com/ChainSafe/js-libp2p-gossipsub/pull/385\n this.gossipTracer.deliverMessage(validationResult.msgIdStr, true)\n this.mcache.observeDuplicate(validationResult.msgIdStr, from.toString())\n return\n\n case MessageStatus.invalid:\n // invalid messages received\n // metrics.register_invalid_message(&raw_message.topic)\n // Tell peer_score about reject\n // Reject the original source, and any duplicates we've seen from other peers.\n if (validationResult.msgIdStr != null) {\n const msgIdStr = validationResult.msgIdStr\n this.score.rejectMessage(from.toString(), msgIdStr, rpcMsg.topic, validationResult.reason)\n this.gossipTracer.rejectMessage(msgIdStr, validationResult.reason)\n } else {\n this.score.rejectInvalidMessage(from.toString(), rpcMsg.topic)\n }\n\n this.metrics?.onMsgRecvInvalid(rpcMsg.topic, validationResult)\n return\n\n case MessageStatus.valid:\n // Tells score that message arrived (but is maybe not fully validated yet).\n // Consider the message as delivered for gossip promises.\n this.score.validateMessage(validationResult.messageId.msgIdStr)\n this.gossipTracer.deliverMessage(validationResult.messageId.msgIdStr)\n\n // Add the message to our memcache\n // if no validation is required, mark the message as validated\n this.mcache.put(validationResult.messageId, rpcMsg, !this.opts.asyncValidation)\n\n // Dispatch the message to the user if we are subscribed to the topic\n if (this.subscriptions.has(rpcMsg.topic)) {\n const isFromSelf = this.components.peerId.equals(from)\n\n if (!isFromSelf || this.opts.emitSelf) {\n super.dispatchEvent(\n new CustomEvent('gossipsub:message', {\n detail: {\n propagationSource: from,\n msgId: validationResult.messageId.msgIdStr,\n msg: validationResult.msg\n }\n })\n )\n // TODO: Add option to switch between emit per topic or all messages in one\n super.dispatchEvent(new CustomEvent('message', { detail: validationResult.msg }))\n }\n }\n\n // Forward the message to mesh peers, if no validation is required\n // If asyncValidation is ON, expect the app layer to call reportMessageValidationResult(), then forward\n if (!this.opts.asyncValidation) {\n // TODO: in rust-libp2p\n // .forward_msg(&msg_id, raw_message, Some(propagation_source))\n this.forwardMessage(validationResult.messageId.msgIdStr, rpcMsg, from.toString())\n }\n break\n default:\n throw new Error(`Invalid validation result: ${validationCode}`)\n }\n }\n\n /**\n * Handles a newly received message from an RPC.\n * May forward to all peers in the mesh.\n */\n private async validateReceivedMessage (\n propagationSource: PeerId,\n rpcMsg: RPC.Message\n ): Promise {\n // Fast message ID stuff\n const fastMsgIdStr = this.fastMsgIdFn?.(rpcMsg)\n const msgIdCached = fastMsgIdStr !== undefined ? this.fastMsgIdCache?.get(fastMsgIdStr) : undefined\n\n if (msgIdCached != null) {\n // This message has been seen previously. Ignore it\n return { code: MessageStatus.duplicate, msgIdStr: msgIdCached }\n }\n\n // Perform basic validation on message and convert to RawGossipsubMessage for fastMsgIdFn()\n const validationResult = await validateToRawMessage(this.globalSignaturePolicy, rpcMsg)\n\n if (!validationResult.valid) {\n return { code: MessageStatus.invalid, reason: RejectReason.Error, error: validationResult.error }\n }\n\n const msg = validationResult.message\n\n // Try and perform the data transform to the message. If it fails, consider it invalid.\n try {\n if (this.dataTransform != null) {\n msg.data = this.dataTransform.inboundTransform(rpcMsg.topic, msg.data)\n }\n } catch (e) {\n this.log('Invalid message, transform failed', e)\n return { code: MessageStatus.invalid, reason: RejectReason.Error, error: ValidateError.TransformFailed }\n }\n\n // TODO: Check if message is from a blacklisted source or propagation origin\n // - Reject any message from a blacklisted peer\n // - Also reject any message that originated from a blacklisted peer\n // - reject messages claiming to be from ourselves but not locally published\n\n // Calculate the message id on the transformed data.\n const msgId = await this.msgIdFn(msg)\n const msgIdStr = this.msgIdToStrFn(msgId)\n const messageId = { msgId, msgIdStr }\n\n // Add the message to the duplicate caches\n if (fastMsgIdStr !== undefined && (this.fastMsgIdCache != null)) {\n const collision = this.fastMsgIdCache.put(fastMsgIdStr, msgIdStr)\n if (collision) {\n this.metrics?.fastMsgIdCacheCollision.inc()\n }\n }\n\n if (this.seenCache.has(msgIdStr)) {\n return { code: MessageStatus.duplicate, msgIdStr }\n } else {\n this.seenCache.put(msgIdStr)\n }\n\n // (Optional) Provide custom validation here with dynamic validators per topic\n // NOTE: This custom topicValidator() must resolve fast (< 100ms) to allow scores\n // to not penalize peers for long validation times.\n const topicValidator = this.topicValidators.get(rpcMsg.topic)\n if (topicValidator != null) {\n let acceptance: TopicValidatorResult\n // Use try {} catch {} in case topicValidator() is synchronous\n try {\n acceptance = await topicValidator(propagationSource, msg)\n } catch (e) {\n const errCode = (e as { code: string }).code\n if (errCode === constants.ERR_TOPIC_VALIDATOR_IGNORE) acceptance = TopicValidatorResult.Ignore\n if (errCode === constants.ERR_TOPIC_VALIDATOR_REJECT) acceptance = TopicValidatorResult.Reject\n else acceptance = TopicValidatorResult.Ignore\n }\n\n if (acceptance !== TopicValidatorResult.Accept) {\n return { code: MessageStatus.invalid, reason: rejectReasonFromAcceptance(acceptance), msgIdStr }\n }\n }\n\n return { code: MessageStatus.valid, messageId, msg }\n }\n\n /**\n * Return score of a peer.\n */\n getScore (peerId: PeerIdStr): number {\n return this.score.score(peerId)\n }\n\n /**\n * Send an rpc object to a peer with subscriptions\n */\n private sendSubscriptions (toPeer: PeerIdStr, topics: string[], subscribe: boolean): void {\n this.sendRpc(toPeer, {\n subscriptions: topics.map((topic) => ({ topic, subscribe })),\n messages: []\n })\n }\n\n /**\n * Handles an rpc control message from a peer\n */\n private async handleControlMessage (id: PeerIdStr, controlMsg: RPC.ControlMessage): Promise {\n if (controlMsg === undefined) {\n return\n }\n\n const iwant = (controlMsg.ihave != null) ? this.handleIHave(id, controlMsg.ihave) : []\n const ihave = (controlMsg.iwant != null) ? this.handleIWant(id, controlMsg.iwant) : []\n const prune = (controlMsg.graft != null) ? await this.handleGraft(id, controlMsg.graft) : []\n ;(controlMsg.prune != null) && (await this.handlePrune(id, controlMsg.prune))\n\n if ((iwant.length === 0) && (ihave.length === 0) && (prune.length === 0)) {\n return\n }\n\n const sent = this.sendRpc(id, createGossipRpc(ihave, { iwant, prune }))\n const iwantMessageIds = iwant[0]?.messageIDs\n if (iwantMessageIds != null) {\n if (sent) {\n this.gossipTracer.addPromise(id, iwantMessageIds)\n } else {\n this.metrics?.iwantPromiseUntracked.inc(1)\n }\n }\n }\n\n /**\n * Whether to accept a message from a peer\n */\n public acceptFrom (id: PeerIdStr): boolean {\n if (this.direct.has(id)) {\n return true\n }\n\n const now = Date.now()\n const entry = this.acceptFromWhitelist.get(id)\n\n if ((entry != null) && entry.messagesAccepted < ACCEPT_FROM_WHITELIST_MAX_MESSAGES && entry.acceptUntil >= now) {\n entry.messagesAccepted += 1\n return true\n }\n\n const score = this.score.score(id)\n if (score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE) {\n // peer is unlikely to be able to drop its score to `graylistThreshold`\n // after 128 messages or 1s\n this.acceptFromWhitelist.set(id, {\n messagesAccepted: 0,\n acceptUntil: now + ACCEPT_FROM_WHITELIST_DURATION_MS\n })\n } else {\n this.acceptFromWhitelist.delete(id)\n }\n\n return score >= this.opts.scoreThresholds.graylistThreshold\n }\n\n /**\n * Handles IHAVE messages\n */\n private handleIHave (id: PeerIdStr, ihave: RPC.ControlIHave[]): RPC.ControlIWant[] {\n if (ihave.length === 0) {\n return []\n }\n\n // we ignore IHAVE gossip from any peer whose score is below the gossips threshold\n const score = this.score.score(id)\n if (score < this.opts.scoreThresholds.gossipThreshold) {\n this.log('IHAVE: ignoring peer %s with score below threshold [ score = %d ]', id, score)\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.LowScore })\n return []\n }\n\n // IHAVE flood protection\n const peerhave = (this.peerhave.get(id) ?? 0) + 1\n this.peerhave.set(id, peerhave)\n if (peerhave > constants.GossipsubMaxIHaveMessages) {\n this.log(\n 'IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring',\n id,\n peerhave\n )\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.MaxIhave })\n return []\n }\n\n const iasked = this.iasked.get(id) ?? 0\n if (iasked >= constants.GossipsubMaxIHaveLength) {\n this.log('IHAVE: peer %s has already advertised too many messages (%d); ignoring', id, iasked)\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.MaxIasked })\n return []\n }\n\n // string msgId => msgId\n const iwant = new Map()\n\n ihave.forEach(({ topicID, messageIDs }) => {\n if (topicID == null || (messageIDs == null) || !this.mesh.has(topicID)) {\n return\n }\n\n let idonthave = 0\n\n messageIDs.forEach((msgId) => {\n const msgIdStr = this.msgIdToStrFn(msgId)\n if (!this.seenCache.has(msgIdStr)) {\n iwant.set(msgIdStr, msgId)\n idonthave++\n }\n })\n\n this.metrics?.onIhaveRcv(topicID, messageIDs.length, idonthave)\n })\n\n if (iwant.size === 0) {\n return []\n }\n\n let iask = iwant.size\n if (iask + iasked > constants.GossipsubMaxIHaveLength) {\n iask = constants.GossipsubMaxIHaveLength - iasked\n }\n\n this.log('IHAVE: Asking for %d out of %d messages from %s', iask, iwant.size, id)\n\n let iwantList = Array.from(iwant.values())\n // ask in random order\n shuffle(iwantList)\n\n // truncate to the messages we are actually asking for and update the iasked counter\n iwantList = iwantList.slice(0, iask)\n this.iasked.set(id, iasked + iask)\n\n // do not add gossipTracer promise here until a successful sendRpc()\n\n return [\n {\n messageIDs: iwantList\n }\n ]\n }\n\n /**\n * Handles IWANT messages\n * Returns messages to send back to peer\n */\n private handleIWant (id: PeerIdStr, iwant: RPC.ControlIWant[]): RPC.Message[] {\n if (iwant.length === 0) {\n return []\n }\n\n // we don't respond to IWANT requests from any per whose score is below the gossip threshold\n const score = this.score.score(id)\n if (score < this.opts.scoreThresholds.gossipThreshold) {\n this.log('IWANT: ignoring peer %s with score below threshold [score = %d]', id, score)\n return []\n }\n\n const ihave = new Map()\n const iwantByTopic = new Map()\n let iwantDonthave = 0\n\n iwant.forEach(({ messageIDs }) => {\n messageIDs?.forEach((msgId) => {\n const msgIdStr = this.msgIdToStrFn(msgId)\n const entry = this.mcache.getWithIWantCount(msgIdStr, id)\n if (entry == null) {\n iwantDonthave++\n return\n }\n\n iwantByTopic.set(entry.msg.topic, 1 + (iwantByTopic.get(entry.msg.topic) ?? 0))\n\n if (entry.count > constants.GossipsubGossipRetransmission) {\n this.log('IWANT: Peer %s has asked for message %s too many times: ignoring request', id, msgId)\n return\n }\n\n ihave.set(msgIdStr, entry.msg)\n })\n })\n\n this.metrics?.onIwantRcv(iwantByTopic, iwantDonthave)\n\n if (ihave.size === 0) {\n this.log('IWANT: Could not provide any wanted messages to %s', id)\n return []\n }\n\n this.log('IWANT: Sending %d messages to %s', ihave.size, id)\n\n return Array.from(ihave.values())\n }\n\n /**\n * Handles Graft messages\n */\n private async handleGraft (id: PeerIdStr, graft: RPC.ControlGraft[]): Promise {\n const prune: TopicStr[] = []\n const score = this.score.score(id)\n const now = Date.now()\n let doPX = this.opts.doPX\n\n graft.forEach(({ topicID }) => {\n if (topicID == null) {\n return\n }\n const peersInMesh = this.mesh.get(topicID)\n if (peersInMesh == null) {\n // don't do PX when there is an unknown topic to avoid leaking our peers\n doPX = false\n // spam hardening: ignore GRAFTs for unknown topics\n return\n }\n\n // check if peer is already in the mesh; if so do nothing\n if (peersInMesh.has(id)) {\n return\n }\n\n // we don't GRAFT to/from direct peers; complain loudly if this happens\n if (this.direct.has(id)) {\n this.log('GRAFT: ignoring request from direct peer %s', id)\n // this is possibly a bug from a non-reciprical configuration; send a PRUNE\n prune.push(topicID)\n // but don't px\n doPX = false\n return\n }\n\n // make sure we are not backing off that peer\n const expire = this.backoff.get(topicID)?.get(id)\n if (typeof expire === 'number' && now < expire) {\n this.log('GRAFT: ignoring backed off peer %s', id)\n // add behavioral penalty\n this.score.addPenalty(id, 1, ScorePenalty.GraftBackoff)\n // no PX\n doPX = false\n // check the flood cutoff -- is the GRAFT coming too fast?\n const floodCutoff = expire + this.opts.graftFloodThreshold - this.opts.pruneBackoff\n if (now < floodCutoff) {\n // extra penalty\n this.score.addPenalty(id, 1, ScorePenalty.GraftBackoff)\n }\n // refresh the backoff\n this.addBackoff(id, topicID)\n prune.push(topicID)\n return\n }\n\n // check the score\n if (score < 0) {\n // we don't GRAFT peers with negative score\n this.log('GRAFT: ignoring peer %s with negative score: score=%d, topic=%s', id, score, topicID)\n // we do send them PRUNE however, because it's a matter of protocol correctness\n prune.push(topicID)\n // but we won't PX to them\n doPX = false\n // add/refresh backoff so that we don't reGRAFT too early even if the score decays\n this.addBackoff(id, topicID)\n return\n }\n\n // check the number of mesh peers; if it is at (or over) Dhi, we only accept grafts\n // from peers with outbound connections; this is a defensive check to restrict potential\n // mesh takeover attacks combined with love bombing\n if (peersInMesh.size >= this.opts.Dhi && !(this.outbound.get(id) ?? false)) {\n prune.push(topicID)\n this.addBackoff(id, topicID)\n return\n }\n\n this.log('GRAFT: Add mesh link from %s in %s', id, topicID)\n this.score.graft(id, topicID)\n peersInMesh.add(id)\n\n this.metrics?.onAddToMesh(topicID, InclusionReason.Subscribed, 1)\n })\n\n if (prune.length === 0) {\n return []\n }\n\n const onUnsubscribe = false\n return Promise.all(prune.map(async (topic) => this.makePrune(id, topic, doPX, onUnsubscribe)))\n }\n\n /**\n * Handles Prune messages\n */\n private async handlePrune (id: PeerIdStr, prune: RPC.ControlPrune[]): Promise {\n const score = this.score.score(id)\n\n for (const { topicID, backoff, peers } of prune) {\n if (topicID == null) {\n continue\n }\n\n const peersInMesh = this.mesh.get(topicID)\n if (peersInMesh == null) {\n return\n }\n\n this.log('PRUNE: Remove mesh link to %s in %s', id, topicID)\n this.score.prune(id, topicID)\n if (peersInMesh.has(id)) {\n peersInMesh.delete(id)\n this.metrics?.onRemoveFromMesh(topicID, ChurnReason.Prune, 1)\n }\n\n // is there a backoff specified by the peer? if so obey it\n if (typeof backoff === 'number' && backoff > 0) {\n this.doAddBackoff(id, topicID, backoff * 1000)\n } else {\n this.addBackoff(id, topicID)\n }\n\n // PX\n if ((peers != null) && (peers.length > 0)) {\n // we ignore PX from peers with insufficient scores\n if (score < this.opts.scoreThresholds.acceptPXThreshold) {\n this.log(\n 'PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]',\n id,\n score,\n topicID\n )\n continue\n }\n await this.pxConnect(peers)\n }\n }\n }\n\n /**\n * Add standard backoff log for a peer in a topic\n */\n private addBackoff (id: PeerIdStr, topic: TopicStr): void {\n this.doAddBackoff(id, topic, this.opts.pruneBackoff)\n }\n\n /**\n * Add backoff expiry interval for a peer in a topic\n *\n * @param id\n * @param topic\n * @param intervalMs - backoff duration in milliseconds\n */\n private doAddBackoff (id: PeerIdStr, topic: TopicStr, intervalMs: number): void {\n let backoff = this.backoff.get(topic)\n if (backoff == null) {\n backoff = new Map()\n this.backoff.set(topic, backoff)\n }\n const expire = Date.now() + intervalMs\n const existingExpire = backoff.get(id) ?? 0\n if (existingExpire < expire) {\n backoff.set(id, expire)\n }\n }\n\n /**\n * Apply penalties from broken IHAVE/IWANT promises\n */\n private applyIwantPenalties (): void {\n this.gossipTracer.getBrokenPromises().forEach((count, p) => {\n this.log(\"peer %s didn't follow up in %d IWANT requests; adding penalty\", p, count)\n this.score.addPenalty(p, count, ScorePenalty.BrokenPromise)\n })\n }\n\n /**\n * Clear expired backoff expiries\n */\n private clearBackoff (): void {\n // we only clear once every GossipsubPruneBackoffTicks ticks to avoid iterating over the maps too much\n if (this.heartbeatTicks % constants.GossipsubPruneBackoffTicks !== 0) {\n return\n }\n\n const now = Date.now()\n this.backoff.forEach((backoff, topic) => {\n backoff.forEach((expire, id) => {\n // add some slack time to the expiration, see https://github.com/libp2p/specs/pull/289\n if (expire + BACKOFF_SLACK * this.opts.heartbeatInterval < now) {\n backoff.delete(id)\n }\n })\n if (backoff.size === 0) {\n this.backoff.delete(topic)\n }\n })\n }\n\n /**\n * Maybe reconnect to direct peers\n */\n private async directConnect (): Promise {\n const toconnect: string[] = []\n this.direct.forEach((id) => {\n if (!this.streamsOutbound.has(id)) {\n toconnect.push(id)\n }\n })\n\n await Promise.all(toconnect.map(async (id) => this.connect(id)))\n }\n\n /**\n * Maybe attempt connection given signed peer records\n */\n private async pxConnect (peers: RPC.PeerInfo[]): Promise {\n if (peers.length > this.opts.prunePeers) {\n shuffle(peers)\n peers = peers.slice(0, this.opts.prunePeers)\n }\n const toconnect: string[] = []\n\n await Promise.all(\n peers.map(async (pi) => {\n if (pi.peerID == null) {\n return\n }\n\n const peer = peerIdFromBytes(pi.peerID)\n const p = peer.toString()\n\n if (this.peers.has(p)) {\n return\n }\n\n if (pi.signedPeerRecord == null) {\n toconnect.push(p)\n return\n }\n\n // The peer sent us a signed record\n // This is not a record from the peer who sent the record, but another peer who is connected with it\n // Ensure that it is valid\n try {\n if (!(await this.components.peerStore.consumePeerRecord(pi.signedPeerRecord, peer))) {\n this.log('bogus peer record obtained through px: could not add peer record to address book')\n return\n }\n toconnect.push(p)\n } catch (e) {\n this.log('bogus peer record obtained through px: invalid signature or not a peer record')\n }\n })\n )\n\n if (toconnect.length === 0) {\n return\n }\n\n await Promise.all(toconnect.map(async (id) => this.connect(id)))\n }\n\n /**\n * Connect to a peer using the gossipsub protocol\n */\n private async connect (id: PeerIdStr): Promise {\n this.log('Initiating connection with %s', id)\n const peerId = peerIdFromString(id)\n const connection = await this.components.connectionManager.openConnection(peerId)\n for (const multicodec of this.multicodecs) {\n for (const topology of this.components.registrar.getTopologies(multicodec)) {\n topology.onConnect?.(peerId, connection)\n }\n }\n }\n\n /**\n * Subscribes to a topic\n */\n subscribe (topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Pubsub has not started')\n }\n\n if (!this.subscriptions.has(topic)) {\n this.subscriptions.add(topic)\n\n for (const peerId of this.peers.keys()) {\n this.sendSubscriptions(peerId, [topic], true)\n }\n }\n\n this.join(topic)\n }\n\n /**\n * Unsubscribe to a topic\n */\n unsubscribe (topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Pubsub is not started')\n }\n\n const wasSubscribed = this.subscriptions.delete(topic)\n\n this.log('unsubscribe from %s - am subscribed %s', topic, wasSubscribed)\n\n if (wasSubscribed) {\n for (const peerId of this.peers.keys()) {\n this.sendSubscriptions(peerId, [topic], false)\n }\n }\n\n this.leave(topic)\n }\n\n /**\n * Join topic\n */\n private join (topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Gossipsub has not started')\n }\n\n // if we are already in the mesh, return\n if (this.mesh.has(topic)) {\n return\n }\n\n this.log('JOIN %s', topic)\n this.metrics?.onJoin(topic)\n\n const toAdd = new Set()\n const backoff = this.backoff.get(topic)\n\n // check if we have mesh_n peers in fanout[topic] and add them to the mesh if we do,\n // removing the fanout entry.\n const fanoutPeers = this.fanout.get(topic)\n if (fanoutPeers != null) {\n // Remove fanout entry and the last published time\n this.fanout.delete(topic)\n this.fanoutLastpub.delete(topic)\n\n // remove explicit peers, peers with negative scores, and backoffed peers\n fanoutPeers.forEach((id) => {\n if (!this.direct.has(id) && this.score.score(id) >= 0 && ((backoff == null) || !backoff.has(id))) {\n toAdd.add(id)\n }\n })\n\n this.metrics?.onAddToMesh(topic, InclusionReason.Fanout, toAdd.size)\n }\n\n // check if we need to get more peers, which we randomly select\n if (toAdd.size < this.opts.D) {\n const fanoutCount = toAdd.size\n const newPeers = this.getRandomGossipPeers(\n topic,\n this.opts.D,\n (id: PeerIdStr): boolean =>\n // filter direct peers and peers with negative score\n !toAdd.has(id) && !this.direct.has(id) && this.score.score(id) >= 0 && ((backoff == null) || !backoff.has(id))\n )\n\n newPeers.forEach((peer) => {\n toAdd.add(peer)\n })\n\n this.metrics?.onAddToMesh(topic, InclusionReason.Random, toAdd.size - fanoutCount)\n }\n\n this.mesh.set(topic, toAdd)\n\n toAdd.forEach((id) => {\n this.log('JOIN: Add mesh link to %s in %s', id, topic)\n this.sendGraft(id, topic)\n\n // rust-libp2p\n // - peer_score.graft()\n // - Self::control_pool_add()\n // - peer_added_to_mesh()\n })\n }\n\n /**\n * Leave topic\n */\n private leave (topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Gossipsub has not started')\n }\n\n this.log('LEAVE %s', topic)\n this.metrics?.onLeave(topic)\n\n // Send PRUNE to mesh peers\n const meshPeers = this.mesh.get(topic)\n if (meshPeers != null) {\n Promise.all(\n Array.from(meshPeers).map(async (id) => {\n this.log('LEAVE: Remove mesh link to %s in %s', id, topic)\n await this.sendPrune(id, topic)\n })\n ).catch((err) => {\n this.log('Error sending prunes to mesh peers', err)\n })\n this.mesh.delete(topic)\n }\n }\n\n private selectPeersToForward (topic: TopicStr, propagationSource?: PeerIdStr, excludePeers?: Set): Set {\n const tosend = new Set()\n\n // Add explicit peers\n const peersInTopic = this.topics.get(topic)\n if (peersInTopic != null) {\n this.direct.forEach((peer) => {\n if (peersInTopic.has(peer) && propagationSource !== peer && !(excludePeers?.has(peer) ?? false)) {\n tosend.add(peer)\n }\n })\n\n // As of Mar 2022, spec + golang-libp2p include this while rust-libp2p does not\n // rust-libp2p: https://github.com/libp2p/rust-libp2p/blob/6cc3b4ec52c922bfcf562a29b5805c3150e37c75/protocols/gossipsub/src/behaviour.rs#L2693\n // spec: https://github.com/libp2p/specs/blob/10712c55ab309086a52eec7d25f294df4fa96528/pubsub/gossipsub/gossipsub-v1.0.md?plain=1#L361\n this.floodsubPeers.forEach((peer) => {\n if (\n peersInTopic.has(peer) &&\n propagationSource !== peer &&\n !(excludePeers?.has(peer) ?? false) &&\n this.score.score(peer) >= this.opts.scoreThresholds.publishThreshold\n ) {\n tosend.add(peer)\n }\n })\n }\n\n // add mesh peers\n const meshPeers = this.mesh.get(topic)\n if ((meshPeers != null) && meshPeers.size > 0) {\n meshPeers.forEach((peer) => {\n if (propagationSource !== peer && !(excludePeers?.has(peer) ?? false)) {\n tosend.add(peer)\n }\n })\n }\n\n return tosend\n }\n\n private selectPeersToPublish (topic: TopicStr): {\n tosend: Set\n tosendCount: ToSendGroupCount\n } {\n const tosend = new Set()\n const tosendCount: ToSendGroupCount = {\n direct: 0,\n floodsub: 0,\n mesh: 0,\n fanout: 0\n }\n\n const peersInTopic = this.topics.get(topic)\n if (peersInTopic != null) {\n // flood-publish behavior\n // send to direct peers and _all_ peers meeting the publishThreshold\n if (this.opts.floodPublish) {\n peersInTopic.forEach((id) => {\n if (this.direct.has(id)) {\n tosend.add(id)\n tosendCount.direct++\n } else if (this.score.score(id) >= this.opts.scoreThresholds.publishThreshold) {\n tosend.add(id)\n tosendCount.floodsub++\n }\n })\n } else {\n // non-flood-publish behavior\n // send to direct peers, subscribed floodsub peers\n // and some mesh peers above publishThreshold\n\n // direct peers (if subscribed)\n this.direct.forEach((id) => {\n if (peersInTopic.has(id)) {\n tosend.add(id)\n tosendCount.direct++\n }\n })\n\n // floodsub peers\n // Note: if there are no floodsub peers, we save a loop through peersInTopic Map\n this.floodsubPeers.forEach((id) => {\n if (peersInTopic.has(id) && this.score.score(id) >= this.opts.scoreThresholds.publishThreshold) {\n tosend.add(id)\n tosendCount.floodsub++\n }\n })\n\n // Gossipsub peers handling\n const meshPeers = this.mesh.get(topic)\n if ((meshPeers != null) && meshPeers.size > 0) {\n meshPeers.forEach((peer) => {\n tosend.add(peer)\n tosendCount.mesh++\n })\n // eslint-disable-next-line @typescript-eslint/brace-style\n }\n\n // We are not in the mesh for topic, use fanout peers\n else {\n const fanoutPeers = this.fanout.get(topic)\n if ((fanoutPeers != null) && fanoutPeers.size > 0) {\n fanoutPeers.forEach((peer) => {\n tosend.add(peer)\n tosendCount.fanout++\n })\n // eslint-disable-next-line @typescript-eslint/brace-style\n }\n\n // We have no fanout peers, select mesh_n of them and add them to the fanout\n else {\n // If we are not in the fanout, then pick peers in topic above the publishThreshold\n const newFanoutPeers = this.getRandomGossipPeers(topic, this.opts.D, (id) => {\n return this.score.score(id) >= this.opts.scoreThresholds.publishThreshold\n })\n\n // eslint-disable-next-line max-depth\n if (newFanoutPeers.size > 0) {\n this.fanout.set(topic, newFanoutPeers)\n\n newFanoutPeers.forEach((peer) => {\n tosend.add(peer)\n tosendCount.fanout++\n })\n }\n }\n\n // We are publishing to fanout peers - update the time we published\n this.fanoutLastpub.set(topic, Date.now())\n }\n }\n }\n\n return { tosend, tosendCount }\n }\n\n /**\n * Forwards a message from our peers.\n *\n * For messages published by us (the app layer), this class uses `publish`\n */\n private forwardMessage (\n msgIdStr: string,\n rawMsg: RPC.Message,\n propagationSource?: PeerIdStr,\n excludePeers?: Set\n ): void {\n // message is fully validated inform peer_score\n if (propagationSource != null) {\n this.score.deliverMessage(propagationSource, msgIdStr, rawMsg.topic)\n }\n\n const tosend = this.selectPeersToForward(rawMsg.topic, propagationSource, excludePeers)\n\n // Note: Don't throw if tosend is empty, we can have a mesh with a single peer\n\n // forward the message to peers\n tosend.forEach((id) => {\n // sendRpc may mutate RPC message on piggyback, create a new message for each peer\n this.sendRpc(id, createGossipRpc([rawMsg]))\n })\n\n this.metrics?.onForwardMsg(rawMsg.topic, tosend.size)\n }\n\n /**\n * App layer publishes a message to peers, return number of peers this message is published to\n * Note: `async` due to crypto only if `StrictSign`, otherwise it's a sync fn.\n *\n * For messages not from us, this class uses `forwardMessage`.\n */\n async publish (topic: TopicStr, data: Uint8Array, opts?: PublishOpts): Promise {\n const startMs = Date.now()\n const transformedData = (this.dataTransform != null) ? this.dataTransform.outboundTransform(topic, data) : data\n\n if (this.publishConfig == null) {\n throw Error('PublishError.Uninitialized')\n }\n\n // Prepare raw message with user's publishConfig\n const { raw: rawMsg, msg } = await buildRawMessage(this.publishConfig, topic, data, transformedData)\n\n // calculate the message id from the un-transformed data\n const msgId = await this.msgIdFn(msg)\n const msgIdStr = this.msgIdToStrFn(msgId)\n\n // Current publish opt takes precedence global opts, while preserving false value\n const ignoreDuplicatePublishError = opts?.ignoreDuplicatePublishError ?? this.opts.ignoreDuplicatePublishError\n\n if (this.seenCache.has(msgIdStr)) {\n // This message has already been seen. We don't re-publish messages that have already\n // been published on the network.\n if (ignoreDuplicatePublishError) {\n this.metrics?.onPublishDuplicateMsg(topic)\n return { recipients: [] }\n }\n throw Error('PublishError.Duplicate')\n }\n\n const { tosend, tosendCount } = this.selectPeersToPublish(topic)\n const willSendToSelf = this.opts.emitSelf && this.subscriptions.has(topic)\n\n // Current publish opt takes precedence global opts, while preserving false value\n const allowPublishToZeroPeers = opts?.allowPublishToZeroPeers ?? this.opts.allowPublishToZeroPeers\n\n if (tosend.size === 0 && !allowPublishToZeroPeers && !willSendToSelf) {\n throw Error('PublishError.InsufficientPeers')\n }\n\n // If the message isn't a duplicate and we have sent it to some peers add it to the\n // duplicate cache and memcache.\n this.seenCache.put(msgIdStr)\n // all published messages are valid\n this.mcache.put({ msgId, msgIdStr }, rawMsg, true)\n\n // If the message is anonymous or has a random author add it to the published message ids cache.\n this.publishedMessageIds.put(msgIdStr)\n\n const batchPublish = opts?.batchPublish ?? this.opts.batchPublish\n const rpc = createGossipRpc([rawMsg])\n if (batchPublish) {\n this.sendRpcInBatch(tosend, rpc)\n } else {\n // Send to set of peers aggregated from direct, mesh, fanout\n for (const id of tosend) {\n // sendRpc may mutate RPC message on piggyback, create a new message for each peer\n const sent = this.sendRpc(id, rpc)\n\n // did not actually send the message\n if (!sent) {\n tosend.delete(id)\n }\n }\n }\n\n const durationMs = Date.now() - startMs\n this.metrics?.onPublishMsg(\n topic,\n tosendCount,\n tosend.size,\n rawMsg.data != null ? rawMsg.data.length : 0,\n durationMs\n )\n\n // Dispatch the message to the user if we are subscribed to the topic\n if (willSendToSelf) {\n tosend.add(this.components.peerId.toString())\n\n super.dispatchEvent(\n new CustomEvent('gossipsub:message', {\n detail: {\n propagationSource: this.components.peerId,\n msgId: msgIdStr,\n msg\n }\n })\n )\n // TODO: Add option to switch between emit per topic or all messages in one\n super.dispatchEvent(new CustomEvent('message', { detail: msg }))\n }\n\n return {\n recipients: Array.from(tosend.values()).map((str) => peerIdFromString(str))\n }\n }\n\n /**\n * Send the same data in batch to tosend list without considering cached control messages\n * This is not only faster but also avoid allocating memory for each peer\n * see https://github.com/ChainSafe/js-libp2p-gossipsub/issues/344\n */\n private sendRpcInBatch (tosend: Set, rpc: RPC): void {\n const rpcBytes = RPC.encode(rpc)\n const prefixedData = encode.single(rpcBytes)\n for (const id of tosend) {\n const outboundStream = this.streamsOutbound.get(id)\n if (outboundStream == null) {\n this.log(`Cannot send RPC to ${id} as there is no open stream to it available`)\n tosend.delete(id)\n continue\n }\n try {\n outboundStream.pushPrefixed(prefixedData)\n } catch (e) {\n tosend.delete(id)\n this.log.error(`Cannot send rpc to ${id}`, e)\n }\n\n this.metrics?.onRpcSent(rpc, rpcBytes.length)\n }\n }\n\n /**\n * This function should be called when `asyncValidation` is `true` after\n * the message got validated by the caller. Messages are stored in the `mcache` and\n * validation is expected to be fast enough that the messages should still exist in the cache.\n * There are three possible validation outcomes and the outcome is given in acceptance.\n *\n * If acceptance = `MessageAcceptance.Accept` the message will get propagated to the\n * network. The `propagation_source` parameter indicates who the message was received by and\n * will not be forwarded back to that peer.\n *\n * If acceptance = `MessageAcceptance.Reject` the message will be deleted from the memcache\n * and the P₄ penalty will be applied to the `propagationSource`.\n *\n * If acceptance = `MessageAcceptance.Ignore` the message will be deleted from the memcache\n * but no P₄ penalty will be applied.\n *\n * This function will return true if the message was found in the cache and false if was not\n * in the cache anymore.\n *\n * This should only be called once per message.\n */\n reportMessageValidationResult (msgId: MsgIdStr, propagationSource: PeerIdStr, acceptance: TopicValidatorResult): void {\n let cacheEntry: MessageCacheRecord | null\n\n if (acceptance === TopicValidatorResult.Accept) {\n cacheEntry = this.mcache.validate(msgId)\n\n if (cacheEntry != null) {\n const { message: rawMsg, originatingPeers } = cacheEntry\n // message is fully validated inform peer_score\n this.score.deliverMessage(propagationSource, msgId, rawMsg.topic)\n\n this.forwardMessage(msgId, cacheEntry.message, propagationSource, originatingPeers)\n }\n // else, Message not in cache. Ignoring forwarding\n // eslint-disable-next-line @typescript-eslint/brace-style\n }\n\n // Not valid\n else {\n cacheEntry = this.mcache.remove(msgId)\n\n if (cacheEntry != null) {\n const rejectReason = rejectReasonFromAcceptance(acceptance)\n const { message: rawMsg, originatingPeers } = cacheEntry\n\n // Tell peer_score about reject\n // Reject the original source, and any duplicates we've seen from other peers.\n this.score.rejectMessage(propagationSource, msgId, rawMsg.topic, rejectReason)\n for (const peer of originatingPeers) {\n this.score.rejectMessage(peer, msgId, rawMsg.topic, rejectReason)\n }\n }\n // else, Message not in cache. Ignoring forwarding\n }\n\n const firstSeenTimestampMs = this.score.messageFirstSeenTimestampMs(msgId)\n this.metrics?.onReportValidation(cacheEntry, acceptance, firstSeenTimestampMs)\n }\n\n /**\n * Sends a GRAFT message to a peer\n */\n private sendGraft (id: PeerIdStr, topic: string): void {\n const graft = [\n {\n topicID: topic\n }\n ]\n const out = createGossipRpc([], { graft })\n this.sendRpc(id, out)\n }\n\n /**\n * Sends a PRUNE message to a peer\n */\n private async sendPrune (id: PeerIdStr, topic: string): Promise {\n // this is only called from leave() function\n const onUnsubscribe = true\n const prune = [await this.makePrune(id, topic, this.opts.doPX, onUnsubscribe)]\n const out = createGossipRpc([], { prune })\n this.sendRpc(id, out)\n }\n\n /**\n * Send an rpc object to a peer\n */\n private sendRpc (id: PeerIdStr, rpc: RPC): boolean {\n const outboundStream = this.streamsOutbound.get(id)\n if (outboundStream == null) {\n this.log(`Cannot send RPC to ${id} as there is no open stream to it available`)\n return false\n }\n\n // piggyback control message retries\n const ctrl = this.control.get(id)\n if (ctrl != null) {\n this.piggybackControl(id, rpc, ctrl)\n this.control.delete(id)\n }\n\n // piggyback gossip\n const ihave = this.gossip.get(id)\n if (ihave != null) {\n this.piggybackGossip(id, rpc, ihave)\n this.gossip.delete(id)\n }\n\n const rpcBytes = RPC.encode(rpc)\n try {\n outboundStream.push(rpcBytes)\n } catch (e) {\n this.log.error(`Cannot send rpc to ${id}`, e)\n\n // if the peer had control messages or gossip, re-attach\n if (ctrl != null) {\n this.control.set(id, ctrl)\n }\n if (ihave != null) {\n this.gossip.set(id, ihave)\n }\n\n return false\n }\n\n this.metrics?.onRpcSent(rpc, rpcBytes.length)\n\n return true\n }\n\n /** Mutates `outRpc` adding graft and prune control messages */\n public piggybackControl (id: PeerIdStr, outRpc: RPC, ctrl: RPC.ControlMessage): void {\n const rpc = ensureControl(outRpc)\n for (const graft of ctrl.graft) {\n if (graft.topicID != null && (this.mesh.get(graft.topicID)?.has(id) ?? false)) {\n rpc.control.graft.push(graft)\n }\n }\n\n for (const prune of ctrl.prune) {\n if (prune.topicID != null && !(this.mesh.get(prune.topicID)?.has(id) ?? false)) {\n rpc.control.prune.push(prune)\n }\n }\n }\n\n /** Mutates `outRpc` adding ihave control messages */\n private piggybackGossip (id: PeerIdStr, outRpc: RPC, ihave: RPC.ControlIHave[]): void {\n const rpc = ensureControl(outRpc)\n rpc.control.ihave = ihave\n }\n\n /**\n * Send graft and prune messages\n *\n * @param tograft - peer id => topic[]\n * @param toprune - peer id => topic[]\n */\n private async sendGraftPrune (\n tograft: Map,\n toprune: Map,\n noPX: Map\n ): Promise {\n const doPX = this.opts.doPX\n const onUnsubscribe = false\n for (const [id, topics] of tograft) {\n const graft = topics.map((topicID) => ({ topicID }))\n let prune: RPC.ControlPrune[] = []\n // If a peer also has prunes, process them now\n const pruning = toprune.get(id)\n if (pruning != null) {\n prune = await Promise.all(\n pruning.map(\n async (topicID) => this.makePrune(id, topicID, doPX && !(noPX.get(id) ?? false), onUnsubscribe)\n )\n )\n toprune.delete(id)\n }\n\n this.sendRpc(id, createGossipRpc([], { graft, prune }))\n }\n for (const [id, topics] of toprune) {\n const prune = await Promise.all(\n topics.map(\n async (topicID) => this.makePrune(id, topicID, doPX && !(noPX.get(id) ?? false), onUnsubscribe)\n )\n )\n this.sendRpc(id, createGossipRpc([], { prune }))\n }\n }\n\n /**\n * Emits gossip - Send IHAVE messages to a random set of gossip peers\n */\n private emitGossip (peersToGossipByTopic: Map>): void {\n const gossipIDsByTopic = this.mcache.getGossipIDs(new Set(peersToGossipByTopic.keys()))\n for (const [topic, peersToGossip] of peersToGossipByTopic) {\n this.doEmitGossip(topic, peersToGossip, gossipIDsByTopic.get(topic) ?? [])\n }\n }\n\n /**\n * Send gossip messages to GossipFactor peers above threshold with a minimum of D_lazy\n * Peers are randomly selected from the heartbeat which exclude mesh + fanout peers\n * We also exclude direct peers, as there is no reason to emit gossip to them\n *\n * @param topic\n * @param candidateToGossip - peers to gossip\n * @param messageIDs - message ids to gossip\n */\n private doEmitGossip (topic: string, candidateToGossip: Set, messageIDs: Uint8Array[]): void {\n if (messageIDs.length === 0) {\n return\n }\n\n // shuffle to emit in random order\n shuffle(messageIDs)\n\n // if we are emitting more than GossipsubMaxIHaveLength ids, truncate the list\n if (messageIDs.length > constants.GossipsubMaxIHaveLength) {\n // we do the truncation (with shuffling) per peer below\n this.log('too many messages for gossip; will truncate IHAVE list (%d messages)', messageIDs.length)\n }\n\n if (candidateToGossip.size === 0) return\n let target = this.opts.Dlazy\n const factor = constants.GossipsubGossipFactor * candidateToGossip.size\n let peersToGossip: Set | PeerIdStr[] = candidateToGossip\n if (factor > target) {\n target = factor\n }\n if (target > peersToGossip.size) {\n target = peersToGossip.size\n } else {\n // only shuffle if needed\n peersToGossip = shuffle(Array.from(peersToGossip)).slice(0, target)\n }\n\n // Emit the IHAVE gossip to the selected peers up to the target\n peersToGossip.forEach((id) => {\n let peerMessageIDs = messageIDs\n if (messageIDs.length > constants.GossipsubMaxIHaveLength) {\n // shuffle and slice message IDs per peer so that we emit a different set for each peer\n // we have enough reduncancy in the system that this will significantly increase the message\n // coverage when we do truncate\n peerMessageIDs = shuffle(peerMessageIDs.slice()).slice(0, constants.GossipsubMaxIHaveLength)\n }\n this.pushGossip(id, {\n topicID: topic,\n messageIDs: peerMessageIDs\n })\n })\n }\n\n /**\n * Flush gossip and control messages\n */\n private flush (): void {\n // send gossip first, which will also piggyback control\n for (const [peer, ihave] of this.gossip.entries()) {\n this.gossip.delete(peer)\n this.sendRpc(peer, createGossipRpc([], { ihave }))\n }\n // send the remaining control messages\n for (const [peer, control] of this.control.entries()) {\n this.control.delete(peer)\n const out = createGossipRpc([], { graft: control.graft, prune: control.prune })\n this.sendRpc(peer, out)\n }\n }\n\n /**\n * Adds new IHAVE messages to pending gossip\n */\n private pushGossip (id: PeerIdStr, controlIHaveMsgs: RPC.ControlIHave): void {\n this.log('Add gossip to %s', id)\n const gossip = this.gossip.get(id) ?? []\n this.gossip.set(id, gossip.concat(controlIHaveMsgs))\n }\n\n /**\n * Make a PRUNE control message for a peer in a topic\n */\n private async makePrune (\n id: PeerIdStr,\n topic: string,\n doPX: boolean,\n onUnsubscribe: boolean\n ): Promise {\n this.score.prune(id, topic)\n if (this.streamsOutbound.get(id)?.protocol === constants.GossipsubIDv10) {\n // Gossipsub v1.0 -- no backoff, the peer won't be able to parse it anyway\n return {\n topicID: topic,\n peers: []\n }\n }\n // backoff is measured in seconds\n // GossipsubPruneBackoff and GossipsubUnsubscribeBackoff are measured in milliseconds\n // The protobuf has it as a uint64\n const backoffMs = onUnsubscribe ? this.opts.unsubcribeBackoff : this.opts.pruneBackoff\n const backoff = backoffMs / 1000\n this.doAddBackoff(id, topic, backoffMs)\n\n if (!doPX) {\n return {\n topicID: topic,\n peers: [],\n backoff\n }\n }\n\n // select peers for Peer eXchange\n const peers = this.getRandomGossipPeers(topic, this.opts.prunePeers, (xid) => {\n return xid !== id && this.score.score(xid) >= 0\n })\n const px = await Promise.all(\n Array.from(peers).map(async (peerId) => {\n // see if we have a signed record to send back; if we don't, just send\n // the peer ID and let the pruned peer find them in the DHT -- we can't trust\n // unsigned address records through PX anyways\n // Finding signed records in the DHT is not supported at the time of writing in js-libp2p\n const id = peerIdFromString(peerId)\n let peerInfo: Peer | undefined\n\n try {\n peerInfo = await this.components.peerStore.get(id)\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n return {\n peerID: id.toBytes(),\n signedPeerRecord: peerInfo?.peerRecordEnvelope\n }\n })\n )\n return {\n topicID: topic,\n peers: px,\n backoff\n }\n }\n\n private readonly runHeartbeat = (): void => {\n const timer = this.metrics?.heartbeatDuration.startTimer()\n\n this.heartbeat()\n .catch((err) => {\n this.log('Error running heartbeat', err)\n })\n .finally(() => {\n if (timer != null) {\n timer()\n }\n\n // Schedule the next run if still in started status\n if (this.status.code === GossipStatusCode.started) {\n // Clear previous timeout before overwriting `status.heartbeatTimeout`, it should be completed tho.\n clearTimeout(this.status.heartbeatTimeout)\n\n // NodeJS setInterval function is innexact, calls drift by a few miliseconds on each call.\n // To run the heartbeat precisely setTimeout() must be used recomputing the delay on every loop.\n let msToNextHeartbeat =\n this.opts.heartbeatInterval - ((Date.now() - this.status.hearbeatStartMs) % this.opts.heartbeatInterval)\n\n // If too close to next heartbeat, skip one\n if (msToNextHeartbeat < this.opts.heartbeatInterval * 0.25) {\n msToNextHeartbeat += this.opts.heartbeatInterval\n this.metrics?.heartbeatSkipped.inc()\n }\n\n this.status.heartbeatTimeout = setTimeout(this.runHeartbeat, msToNextHeartbeat)\n }\n })\n }\n\n /**\n * Maintains the mesh and fanout maps in gossipsub.\n */\n public async heartbeat (): Promise {\n const { D, Dlo, Dhi, Dscore, Dout, fanoutTTL } = this.opts\n\n this.heartbeatTicks++\n\n // cache scores throught the heartbeat\n const scores = new Map()\n const getScore = (id: string): number => {\n let s = scores.get(id)\n if (s === undefined) {\n s = this.score.score(id)\n scores.set(id, s)\n }\n return s\n }\n\n // peer id => topic[]\n const tograft = new Map()\n // peer id => topic[]\n const toprune = new Map()\n // peer id => don't px\n const noPX = new Map()\n\n // clean up expired backoffs\n this.clearBackoff()\n\n // clean up peerhave/iasked counters\n this.peerhave.clear()\n this.metrics?.cacheSize.set({ cache: 'iasked' }, this.iasked.size)\n this.iasked.clear()\n\n // apply IWANT request penalties\n this.applyIwantPenalties()\n\n // ensure direct peers are connected\n if (this.heartbeatTicks % this.opts.directConnectTicks === 0) {\n // we only do this every few ticks to allow pending connections to complete and account for restarts/downtime\n await this.directConnect()\n }\n\n // EXTRA: Prune caches\n this.fastMsgIdCache?.prune()\n this.seenCache.prune()\n this.gossipTracer.prune()\n this.publishedMessageIds.prune()\n\n /**\n * Instead of calling getRandomGossipPeers multiple times to:\n * + get more mesh peers\n * + more outbound peers\n * + oppportunistic grafting\n * + emitGossip\n *\n * We want to loop through the topic peers only a single time and prepare gossip peers for all topics to improve the performance\n */\n\n const peersToGossipByTopic = new Map>()\n // maintain the mesh for topics we have joined\n // eslint-disable-next-line complexity\n this.mesh.forEach((peers, topic) => {\n const peersInTopic = this.topics.get(topic)\n const candidateMeshPeers = new Set()\n const peersToGossip = new Set()\n peersToGossipByTopic.set(topic, peersToGossip)\n\n if (peersInTopic != null) {\n const shuffledPeers = shuffle(Array.from(peersInTopic))\n const backoff = this.backoff.get(topic)\n for (const id of shuffledPeers) {\n const peerStreams = this.streamsOutbound.get(id)\n if (\n (peerStreams != null) &&\n this.multicodecs.includes(peerStreams.protocol) &&\n !peers.has(id) &&\n !this.direct.has(id)\n ) {\n const score = getScore(id)\n if (((backoff == null) || !backoff.has(id)) && score >= 0) candidateMeshPeers.add(id)\n // instead of having to find gossip peers after heartbeat which require another loop\n // we prepare peers to gossip in a topic within heartbeat to improve performance\n if (score >= this.opts.scoreThresholds.gossipThreshold) peersToGossip.add(id)\n }\n }\n }\n\n // prune/graft helper functions (defined per topic)\n const prunePeer = (id: PeerIdStr, reason: ChurnReason): void => {\n this.log('HEARTBEAT: Remove mesh link to %s in %s', id, topic)\n // no need to update peer score here as we do it in makePrune\n // add prune backoff record\n this.addBackoff(id, topic)\n // remove peer from mesh\n peers.delete(id)\n // after pruning a peer from mesh, we want to gossip topic to it if its score meet the gossip threshold\n if (getScore(id) >= this.opts.scoreThresholds.gossipThreshold) peersToGossip.add(id)\n this.metrics?.onRemoveFromMesh(topic, reason, 1)\n // add to toprune\n const topics = toprune.get(id)\n if (topics == null) {\n toprune.set(id, [topic])\n } else {\n topics.push(topic)\n }\n }\n\n const graftPeer = (id: PeerIdStr, reason: InclusionReason): void => {\n this.log('HEARTBEAT: Add mesh link to %s in %s', id, topic)\n // update peer score\n this.score.graft(id, topic)\n // add peer to mesh\n peers.add(id)\n // when we add a new mesh peer, we don't want to gossip messages to it\n peersToGossip.delete(id)\n this.metrics?.onAddToMesh(topic, reason, 1)\n // add to tograft\n const topics = tograft.get(id)\n if (topics == null) {\n tograft.set(id, [topic])\n } else {\n topics.push(topic)\n }\n }\n\n // drop all peers with negative score, without PX\n peers.forEach((id) => {\n const score = getScore(id)\n\n // Record the score\n\n if (score < 0) {\n this.log('HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s', id, score, topic)\n prunePeer(id, ChurnReason.BadScore)\n noPX.set(id, true)\n }\n })\n\n // do we have enough peers?\n if (peers.size < Dlo) {\n const ineed = D - peers.size\n // slice up to first `ineed` items and remove them from candidateMeshPeers\n // same to `const newMeshPeers = candidateMeshPeers.slice(0, ineed)`\n const newMeshPeers = removeFirstNItemsFromSet(candidateMeshPeers, ineed)\n\n newMeshPeers.forEach((p) => {\n graftPeer(p, InclusionReason.NotEnough)\n })\n }\n\n // do we have to many peers?\n if (peers.size > Dhi) {\n let peersArray = Array.from(peers)\n // sort by score\n peersArray.sort((a, b) => getScore(b) - getScore(a))\n // We keep the first D_score peers by score and the remaining up to D randomly\n // under the constraint that we keep D_out peers in the mesh (if we have that many)\n peersArray = peersArray.slice(0, Dscore).concat(shuffle(peersArray.slice(Dscore)))\n\n // count the outbound peers we are keeping\n let outbound = 0\n peersArray.slice(0, D).forEach((p) => {\n if (this.outbound.get(p) ?? false) {\n outbound++\n }\n })\n\n // if it's less than D_out, bubble up some outbound peers from the random selection\n if (outbound < Dout) {\n const rotate = (i: number): void => {\n // rotate the peersArray to the right and put the ith peer in the front\n const p = peersArray[i]\n for (let j = i; j > 0; j--) {\n peersArray[j] = peersArray[j - 1]\n }\n peersArray[0] = p\n }\n\n // first bubble up all outbound peers already in the selection to the front\n if (outbound > 0) {\n let ihave = outbound\n for (let i = 1; i < D && ihave > 0; i++) {\n // eslint-disable-next-line max-depth\n if (this.outbound.get(peersArray[i]) ?? false) {\n rotate(i)\n ihave--\n }\n }\n }\n\n // now bubble up enough outbound peers outside the selection to the front\n let ineed = D - outbound\n for (let i = D; i < peersArray.length && ineed > 0; i++) {\n if (this.outbound.get(peersArray[i]) ?? false) {\n rotate(i)\n ineed--\n }\n }\n }\n\n // prune the excess peers\n peersArray.slice(D).forEach((p) => {\n prunePeer(p, ChurnReason.Excess)\n })\n }\n\n // do we have enough outbound peers?\n if (peers.size >= Dlo) {\n // count the outbound peers we have\n let outbound = 0\n peers.forEach((p) => {\n if (this.outbound.get(p) ?? false) {\n outbound++\n }\n })\n\n // if it's less than D_out, select some peers with outbound connections and graft them\n if (outbound < Dout) {\n const ineed = Dout - outbound\n const newMeshPeers = removeItemsFromSet(candidateMeshPeers, ineed, (id) => this.outbound.get(id) === true)\n\n newMeshPeers.forEach((p) => {\n graftPeer(p, InclusionReason.Outbound)\n })\n }\n }\n\n // should we try to improve the mesh with opportunistic grafting?\n if (this.heartbeatTicks % this.opts.opportunisticGraftTicks === 0 && peers.size > 1) {\n // Opportunistic grafting works as follows: we check the median score of peers in the\n // mesh; if this score is below the opportunisticGraftThreshold, we select a few peers at\n // random with score over the median.\n // The intention is to (slowly) improve an underperforming mesh by introducing good\n // scoring peers that may have been gossiping at us. This allows us to get out of sticky\n // situations where we are stuck with poor peers and also recover from churn of good peers.\n\n // now compute the median peer score in the mesh\n const peersList = Array.from(peers).sort((a, b) => getScore(a) - getScore(b))\n const medianIndex = Math.floor(peers.size / 2)\n const medianScore = getScore(peersList[medianIndex])\n\n // if the median score is below the threshold, select a better peer (if any) and GRAFT\n if (medianScore < this.opts.scoreThresholds.opportunisticGraftThreshold) {\n const ineed = this.opts.opportunisticGraftPeers\n const newMeshPeers = removeItemsFromSet(candidateMeshPeers, ineed, (id) => getScore(id) > medianScore)\n for (const id of newMeshPeers) {\n this.log('HEARTBEAT: Opportunistically graft peer %s on topic %s', id, topic)\n graftPeer(id, InclusionReason.Opportunistic)\n }\n }\n }\n })\n\n // expire fanout for topics we haven't published to in a while\n const now = Date.now()\n this.fanoutLastpub.forEach((lastpb, topic) => {\n if (lastpb + fanoutTTL < now) {\n this.fanout.delete(topic)\n this.fanoutLastpub.delete(topic)\n }\n })\n\n // maintain our fanout for topics we are publishing but we have not joined\n this.fanout.forEach((fanoutPeers, topic) => {\n // checks whether our peers are still in the topic and have a score above the publish threshold\n const topicPeers = this.topics.get(topic)\n fanoutPeers.forEach((id) => {\n if (!(topicPeers?.has(id) ?? false) || getScore(id) < this.opts.scoreThresholds.publishThreshold) {\n fanoutPeers.delete(id)\n }\n })\n\n const peersInTopic = this.topics.get(topic)\n const candidateFanoutPeers = []\n // the fanout map contains topics to which we are not subscribed.\n const peersToGossip = new Set()\n peersToGossipByTopic.set(topic, peersToGossip)\n\n if (peersInTopic != null) {\n const shuffledPeers = shuffle(Array.from(peersInTopic))\n for (const id of shuffledPeers) {\n const peerStreams = this.streamsOutbound.get(id)\n if (\n (peerStreams != null) &&\n this.multicodecs.includes(peerStreams.protocol) &&\n !fanoutPeers.has(id) &&\n !this.direct.has(id)\n ) {\n const score = getScore(id)\n if (score >= this.opts.scoreThresholds.publishThreshold) candidateFanoutPeers.push(id)\n // instead of having to find gossip peers after heartbeat which require another loop\n // we prepare peers to gossip in a topic within heartbeat to improve performance\n if (score >= this.opts.scoreThresholds.gossipThreshold) peersToGossip.add(id)\n }\n }\n }\n\n // do we need more peers?\n if (fanoutPeers.size < D) {\n const ineed = D - fanoutPeers.size\n candidateFanoutPeers.slice(0, ineed).forEach((id) => {\n fanoutPeers.add(id)\n peersToGossip?.delete(id)\n })\n }\n })\n\n this.emitGossip(peersToGossipByTopic)\n\n // send coalesced GRAFT/PRUNE messages (will piggyback gossip)\n await this.sendGraftPrune(tograft, toprune, noPX)\n\n // flush pending gossip that wasn't piggybacked above\n this.flush()\n\n // advance the message history window\n this.mcache.shift()\n\n this.dispatchEvent(new CustomEvent('gossipsub:heartbeat'))\n }\n\n /**\n * Given a topic, returns up to count peers subscribed to that topic\n * that pass an optional filter function\n *\n * @param topic\n * @param count\n * @param filter - a function to filter acceptable peers\n */\n private getRandomGossipPeers (\n topic: string,\n count: number,\n filter: (id: string) => boolean = () => true\n ): Set {\n const peersInTopic = this.topics.get(topic)\n\n if (peersInTopic == null) {\n return new Set()\n }\n\n // Adds all peers using our protocol\n // that also pass the filter function\n let peers: string[] = []\n peersInTopic.forEach((id) => {\n const peerStreams = this.streamsOutbound.get(id)\n if (peerStreams == null) {\n return\n }\n if (this.multicodecs.includes(peerStreams.protocol) && filter(id)) {\n peers.push(id)\n }\n })\n\n // Pseudo-randomly shuffles peers\n peers = shuffle(peers)\n if (count > 0 && peers.length > count) {\n peers = peers.slice(0, count)\n }\n\n return new Set(peers)\n }\n\n private onScrapeMetrics (metrics: Metrics): void {\n /* Data structure sizes */\n metrics.mcacheSize.set(this.mcache.size)\n metrics.mcacheNotValidatedCount.set(this.mcache.notValidatedCount)\n // Arbitrary size\n metrics.cacheSize.set({ cache: 'direct' }, this.direct.size)\n metrics.cacheSize.set({ cache: 'seenCache' }, this.seenCache.size)\n metrics.cacheSize.set({ cache: 'fastMsgIdCache' }, this.fastMsgIdCache?.size ?? 0)\n metrics.cacheSize.set({ cache: 'publishedMessageIds' }, this.publishedMessageIds.size)\n metrics.cacheSize.set({ cache: 'mcache' }, this.mcache.size)\n metrics.cacheSize.set({ cache: 'score' }, this.score.size)\n metrics.cacheSize.set({ cache: 'gossipTracer.promises' }, this.gossipTracer.size)\n metrics.cacheSize.set({ cache: 'gossipTracer.requests' }, this.gossipTracer.requestMsByMsgSize)\n // Bounded by topic\n metrics.cacheSize.set({ cache: 'topics' }, this.topics.size)\n metrics.cacheSize.set({ cache: 'subscriptions' }, this.subscriptions.size)\n metrics.cacheSize.set({ cache: 'mesh' }, this.mesh.size)\n metrics.cacheSize.set({ cache: 'fanout' }, this.fanout.size)\n // Bounded by peer\n metrics.cacheSize.set({ cache: 'peers' }, this.peers.size)\n metrics.cacheSize.set({ cache: 'streamsOutbound' }, this.streamsOutbound.size)\n metrics.cacheSize.set({ cache: 'streamsInbound' }, this.streamsInbound.size)\n metrics.cacheSize.set({ cache: 'acceptFromWhitelist' }, this.acceptFromWhitelist.size)\n metrics.cacheSize.set({ cache: 'gossip' }, this.gossip.size)\n metrics.cacheSize.set({ cache: 'control' }, this.control.size)\n metrics.cacheSize.set({ cache: 'peerhave' }, this.peerhave.size)\n metrics.cacheSize.set({ cache: 'outbound' }, this.outbound.size)\n\n // 2D nested data structure\n let backoffSize = 0\n const now = Date.now()\n metrics.connectedPeersBackoffSec.reset()\n for (const backoff of this.backoff.values()) {\n backoffSize += backoff.size\n for (const [peer, expiredMs] of backoff.entries()) {\n if (this.peers.has(peer)) {\n metrics.connectedPeersBackoffSec.observe(Math.max(0, expiredMs - now) / 1000)\n }\n }\n }\n metrics.cacheSize.set({ cache: 'backoff' }, backoffSize)\n\n // Peer counts\n\n for (const [topicStr, peers] of this.topics) {\n metrics.topicPeersCount.set({ topicStr }, peers.size)\n }\n\n for (const [topicStr, peers] of this.mesh) {\n metrics.meshPeerCounts.set({ topicStr }, peers.size)\n }\n\n // Peer scores\n\n const scores: number[] = []\n const scoreByPeer = new Map()\n metrics.behaviourPenalty.reset()\n\n for (const peerIdStr of this.peers.keys()) {\n const score = this.score.score(peerIdStr)\n scores.push(score)\n scoreByPeer.set(peerIdStr, score)\n metrics.behaviourPenalty.observe(this.score.peerStats.get(peerIdStr)?.behaviourPenalty ?? 0)\n }\n\n metrics.registerScores(scores, this.opts.scoreThresholds)\n\n // Breakdown score per mesh topicLabel\n\n metrics.registerScorePerMesh(this.mesh, scoreByPeer)\n\n // Breakdown on each score weight\n\n const sw = computeAllPeersScoreWeights(\n this.peers.keys(),\n this.score.peerStats,\n this.score.params,\n this.score.peerIPs,\n metrics.topicStrToLabel\n )\n\n metrics.registerScoreWeights(sw)\n }\n}\n\nexport function gossipsub (\n init: Partial = {}\n): (components: GossipSubComponents) => PubSub {\n return (components: GossipSubComponents) => new GossipSub(components, init)\n}\n","import { unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport { StrictSign, StrictNoSign } from '@libp2p/interface'\nimport { type PublishConfig, PublishConfigType } from '../types.js'\nimport type { PeerId } from '@libp2p/interface'\n\n/**\n * Prepare a PublishConfig object from a PeerId.\n */\nexport async function getPublishConfigFromPeerId (\n signaturePolicy: typeof StrictSign | typeof StrictNoSign,\n peerId?: PeerId\n): Promise {\n switch (signaturePolicy) {\n case StrictSign: {\n if (peerId == null) {\n throw Error('Must provide PeerId')\n }\n\n if (peerId.privateKey == null) {\n throw Error('Cannot sign message, no private key present')\n }\n\n if (peerId.publicKey == null) {\n throw Error('Cannot sign message, no public key present')\n }\n\n // Transform privateKey once at initialization time instead of once per message\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n\n return {\n type: PublishConfigType.Signing,\n author: peerId,\n key: peerId.publicKey,\n privateKey\n }\n }\n\n case StrictNoSign:\n return {\n type: PublishConfigType.Anonymous\n }\n\n default:\n throw new Error(`Unknown signature policy \"${signaturePolicy}\"`)\n }\n}\n","export const second = 1000;\nexport const minute = 60 * second;\n\n/**\n * RelayCodec is the libp2p identifier for the waku relay protocol\n */\nexport const RelayCodecs = [\"/vac/waku/relay/2.0.0\"];\n\n/**\n * RelayGossipFactor affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to RelayGossipFactor * (total number of non-mesh peers), or\n * RelayDlazy, whichever is greater.\n */\nexport const RelayGossipFactor = 0.25;\n\n/**\n * GossipsubHeartbeatInitialDelay is the short delay before the heartbeat timer begins\n * after the router is initialized.\n */\nexport const RelayHeartbeatInitialDelay = 100;\n\n/**\n * RelayHeartbeatInterval controls the time between heartbeats.\n */\nexport const RelayHeartbeatInterval = second;\n\n/**\n * RelayPrunePeers controls the number of peers to include in prune Peer eXchange.\n * When we prune a peer that's eligible for PX (has a good score, etc), we will try to\n * send them signed peer records for up to RelayPrunePeers other peers that we\n * know of.\n */\nexport const RelayPrunePeers = 16;\n\n/**\n * RelayPruneBackoff controls the backoff time for pruned peers. This is how long\n * a peer must wait before attempting to graft into our mesh again after being pruned.\n * When pruning a peer, we send them our value of RelayPruneBackoff so they know\n * the minimum time to wait. Peers running older versions may not send a backoff time,\n * so if we receive a prune message without one, we will wait at least RelayPruneBackoff\n * before attempting to re-graft.\n */\nexport const RelayPruneBackoff = minute;\n\n/**\n * RelayFanoutTTL controls how long we keep track of the fanout state. If it's been\n * RelayFanoutTTL since we've published to a topic that we're not subscribed to,\n * we'll delete the fanout map for that topic.\n */\nexport const RelayFanoutTTL = minute;\n\n/**\n * RelayOpportunisticGraftTicks is the number of heartbeat ticks for attempting to improve the mesh\n * with opportunistic grafting. Every RelayOpportunisticGraftTicks we will attempt to select some\n * high-scoring mesh peers to replace lower-scoring ones, if the median score of our mesh peers falls\n * below a threshold\n */\nexport const RelayOpportunisticGraftTicks = 60;\n\n/**\n * RelayOpportunisticGraftPeers is the number of peers to opportunistically graft.\n */\nexport const RelayOpportunisticGraftPeers = 2;\n\n/**\n * RelayMaxIHaveLength is the maximum number of messages to include in an IHAVE message.\n * Also controls the maximum number of IHAVE ids we will accept and request with IWANT from a\n * peer within a heartbeat, to protect from IHAVE floods. You should adjust this value from the\n * default if your system is pushing more than 5000 messages in GossipsubHistoryGossip heartbeats;\n * with the defaults this is 1666 messages/s.\n */\nexport const RelayMaxIHaveLength = 5000;\n","import type { Message, PeerId } from \"@libp2p/interface\";\nimport { TopicValidatorResult } from \"@libp2p/interface\";\nimport { proto_message as proto } from \"@waku/proto\";\nimport { Logger } from \"@waku/utils\";\n\nconst log = new Logger(\"relay\");\n\nexport function messageValidator(\n peer: PeerId,\n message: Message\n): TopicValidatorResult {\n const startTime = performance.now();\n log.info(`validating message from ${peer} received on ${message.topic}`);\n let result = TopicValidatorResult.Accept;\n\n try {\n const protoMessage = proto.WakuMessage.decode(message.data);\n\n if (\n !protoMessage.contentTopic ||\n !protoMessage.contentTopic.length ||\n !protoMessage.payload ||\n !protoMessage.payload.length\n ) {\n result = TopicValidatorResult.Reject;\n }\n } catch (e) {\n result = TopicValidatorResult.Reject;\n }\n\n const endTime = performance.now();\n\n const timeTakenMs = endTime - startTime;\n\n if (timeTakenMs > 100) {\n log.warn(\n `message validation took ${timeTakenMs}ms for peer ${peer} on topic ${message.topic}. This should be less than 100ms.`\n );\n } else {\n log.info(\n `message validation took ${timeTakenMs}ms for peer ${peer} on topic ${message.topic}`\n );\n }\n\n return result;\n}\n","import {\n GossipSub,\n GossipSubComponents,\n GossipsubMessage,\n GossipsubOpts\n} from \"@chainsafe/libp2p-gossipsub\";\nimport type { PeerIdStr, TopicStr } from \"@chainsafe/libp2p-gossipsub/types\";\nimport { SignaturePolicy } from \"@chainsafe/libp2p-gossipsub/types\";\nimport type { PubSub as Libp2pPubsub, PeerId } from \"@libp2p/interface\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport {\n ActiveSubscriptions,\n Callback,\n DefaultPubsubTopic,\n IAsyncIterator,\n IDecodedMessage,\n IDecoder,\n IEncoder,\n IMessage,\n IRelay,\n Libp2p,\n ProtocolCreateOptions,\n ProtocolError,\n PubsubTopic,\n SendResult\n} from \"@waku/interfaces\";\nimport { isWireSizeUnderCap, toAsyncIterator } from \"@waku/utils\";\nimport { pushOrInitMapSet } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\n\nimport { RelayCodecs } from \"./constants.js\";\nimport { messageValidator } from \"./message_validator.js\";\nimport { TopicOnlyDecoder } from \"./topic_only_message.js\";\n\nconst log = new Logger(\"relay\");\n\nexport type Observer = {\n decoder: IDecoder;\n callback: Callback;\n};\n\nexport type RelayCreateOptions = ProtocolCreateOptions & GossipsubOpts;\nexport type ContentTopic = string;\n\n/**\n * Implements the [Waku v2 Relay protocol](https://rfc.vac.dev/spec/11/).\n * Throws if libp2p.pubsub does not support Waku Relay\n */\nclass Relay implements IRelay {\n public readonly pubsubTopics: Set;\n private defaultDecoder: IDecoder;\n\n public static multicodec: string = RelayCodecs[0];\n public readonly gossipSub: GossipSub;\n\n /**\n * observers called when receiving new message.\n * Observers under key `\"\"` are always called.\n */\n private observers: Map>>;\n\n constructor(libp2p: Libp2p, pubsubTopics: PubsubTopic[]) {\n if (!this.isRelayPubsub(libp2p.services.pubsub)) {\n throw Error(\n `Failed to initialize Relay. libp2p.pubsub does not support ${Relay.multicodec}`\n );\n }\n\n this.gossipSub = libp2p.services.pubsub as GossipSub;\n this.pubsubTopics = new Set(pubsubTopics);\n\n if (this.gossipSub.isStarted()) {\n this.subscribeToAllTopics();\n }\n\n this.observers = new Map();\n\n // Default PubsubTopic decoder\n // TODO: User might want to decide what decoder should be used (e.g. for RLN)\n this.defaultDecoder = new TopicOnlyDecoder();\n }\n\n /**\n * Mounts the gossipsub protocol onto the libp2p node\n * and subscribes to all the topics.\n *\n * @override\n * @returns {void}\n */\n public async start(): Promise {\n if (this.gossipSub.isStarted()) {\n throw Error(\"GossipSub already started.\");\n }\n\n await this.gossipSub.start();\n this.subscribeToAllTopics();\n }\n\n /**\n * Send Waku message.\n */\n public async send(encoder: IEncoder, message: IMessage): Promise {\n const successes: PeerId[] = [];\n\n const { pubsubTopic } = encoder;\n if (!this.pubsubTopics.has(pubsubTopic)) {\n log.error(\"Failed to send waku relay: topic not configured\");\n return {\n successes,\n failures: [\n {\n error: ProtocolError.TOPIC_NOT_CONFIGURED\n }\n ]\n };\n }\n\n const msg = await encoder.toWire(message);\n if (!msg) {\n log.error(\"Failed to encode message, aborting publish\");\n return {\n successes,\n failures: [\n {\n error: ProtocolError.ENCODE_FAILED\n }\n ]\n };\n }\n\n if (!isWireSizeUnderCap(msg)) {\n log.error(\"Failed to send waku relay: message is bigger that 1MB\");\n return {\n successes,\n failures: [\n {\n error: ProtocolError.SIZE_TOO_BIG\n }\n ]\n };\n }\n\n const { recipients } = await this.gossipSub.publish(pubsubTopic, msg);\n return {\n successes: recipients\n };\n }\n\n public subscribe(\n decoders: IDecoder | IDecoder[],\n callback: Callback\n ): () => void {\n const observers: Array<[PubsubTopic, Observer]> = [];\n\n for (const decoder of Array.isArray(decoders) ? decoders : [decoders]) {\n const { pubsubTopic } = decoder;\n const ctObs: Map>> = this.observers.get(\n pubsubTopic\n ) ?? new Map();\n const observer = { pubsubTopic, decoder, callback };\n pushOrInitMapSet(ctObs, decoder.contentTopic, observer);\n\n this.observers.set(pubsubTopic, ctObs);\n observers.push([pubsubTopic, observer]);\n }\n\n return () => {\n this.removeObservers(observers);\n };\n }\n\n private removeObservers(\n observers: Array<[PubsubTopic, Observer]>\n ): void {\n for (const [pubsubTopic, observer] of observers) {\n const ctObs = this.observers.get(pubsubTopic);\n if (!ctObs) continue;\n\n const contentTopic = observer.decoder.contentTopic;\n const _obs = ctObs.get(contentTopic);\n if (!_obs) continue;\n\n _obs.delete(observer);\n ctObs.set(contentTopic, _obs);\n this.observers.set(pubsubTopic, ctObs);\n }\n }\n\n public toSubscriptionIterator(\n decoders: IDecoder | IDecoder[]\n ): Promise> {\n return toAsyncIterator(this, decoders);\n }\n\n public getActiveSubscriptions(): ActiveSubscriptions {\n const map = new Map();\n for (const pubsubTopic of this.pubsubTopics) {\n map.set(pubsubTopic, Array.from(this.observers.keys()));\n }\n return map;\n }\n\n public getMeshPeers(topic: TopicStr = DefaultPubsubTopic): PeerIdStr[] {\n return this.gossipSub.getMeshPeers(topic);\n }\n\n private subscribeToAllTopics(): void {\n for (const pubsubTopic of this.pubsubTopics) {\n this.gossipSubSubscribe(pubsubTopic);\n }\n }\n\n private async processIncomingMessage(\n pubsubTopic: string,\n bytes: Uint8Array\n ): Promise {\n const topicOnlyMsg = await this.defaultDecoder.fromWireToProtoObj(bytes);\n if (!topicOnlyMsg || !topicOnlyMsg.contentTopic) {\n log.warn(\"Message does not have a content topic, skipping\");\n return;\n }\n\n // Retrieve the map of content topics for the given pubsubTopic\n const contentTopicMap = this.observers.get(pubsubTopic);\n if (!contentTopicMap) {\n return;\n }\n\n // Retrieve the set of observers for the given contentTopic\n const observers = contentTopicMap.get(topicOnlyMsg.contentTopic) as Set<\n Observer\n >;\n if (!observers) {\n return;\n }\n\n await Promise.all(\n Array.from(observers).map(({ decoder, callback }) => {\n return (async () => {\n try {\n const protoMsg = await decoder.fromWireToProtoObj(bytes);\n if (!protoMsg) {\n log.error(\n \"Internal error: message previously decoded failed on 2nd pass.\"\n );\n return;\n }\n const msg = await decoder.fromProtoObj(pubsubTopic, protoMsg);\n if (msg) {\n await callback(msg);\n } else {\n log.error(\n \"Failed to decode messages on\",\n topicOnlyMsg.contentTopic\n );\n }\n } catch (error) {\n log.error(\"Error while decoding message:\", error);\n }\n })();\n })\n );\n }\n\n /**\n * Subscribe to a pubsub topic and start emitting Waku messages to observers.\n *\n * @override\n */\n private gossipSubSubscribe(pubsubTopic: string): void {\n this.gossipSub.addEventListener(\n \"gossipsub:message\",\n (event: CustomEvent) => {\n if (event.detail.msg.topic !== pubsubTopic) return;\n\n this.processIncomingMessage(\n event.detail.msg.topic,\n event.detail.msg.data\n ).catch((e) => log.error(\"Failed to process incoming message\", e));\n }\n );\n\n this.gossipSub.topicValidators.set(pubsubTopic, messageValidator);\n this.gossipSub.subscribe(pubsubTopic);\n }\n\n private isRelayPubsub(pubsub: Libp2pPubsub | undefined): boolean {\n return pubsub?.multicodecs?.includes(Relay.multicodec) ?? false;\n }\n}\n\nexport function wakuRelay(\n pubsubTopics: PubsubTopic[]\n): (libp2p: Libp2p) => IRelay {\n return (libp2p: Libp2p) => new Relay(libp2p, pubsubTopics);\n}\n\nexport function wakuGossipSub(\n init: Partial = {}\n): (components: GossipSubComponents) => GossipSub {\n return (components: GossipSubComponents) => {\n init = {\n ...init,\n msgIdFn: ({ data }) => sha256(data),\n // Ensure that no signature is included nor expected in the messages.\n globalSignaturePolicy: SignaturePolicy.StrictNoSign,\n fallbackToFloodsub: false\n };\n const pubsub = new GossipSub(components, init);\n pubsub.multicodecs = RelayCodecs;\n return pubsub;\n };\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n\nexport function isPromise (thing: any): thing is Promise {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n","import { ed25519 as ed } from '@noble/curves/ed25519'\nimport type { Uint8ArrayKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32\nconst PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed (seed: Uint8Array): Uint8ArrayKeyPair {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw)\n}\n\nexport function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH)\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i]\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i]\n }\n return privateKey\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","/* eslint-env browser */\n\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get (win = globalThis) {\n const nativeCrypto = win.crypto\n\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n 'Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n","import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\n\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' }\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions): AESCipher {\n const algorithm = opts?.algorithm ?? 'AES-GCM'\n let keyLength = opts?.keyLength ?? 16\n const nonceLength = opts?.nonceLength ?? 12\n const digest = opts?.digest ?? 'SHA-256'\n const saltLength = opts?.saltLength ?? 16\n const iterations = opts?.iterations ?? 32767\n\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n }\n } else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt'])\n }\n\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data)\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)])\n }\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = data.subarray(0, saltLength)\n const nonce = data.subarray(saltLength, saltLength + nonceLength)\n const ciphertext = data.subarray(saltLength + nonceLength)\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt'])\n }\n } else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt'])\n }\n\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext)\n return new Uint8Array(plaintext)\n }\n\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n","import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\nimport type { Multibase } from 'multiformats'\n\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter (privateKey: Uint8Array, password: string): Promise> {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\n","const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n","import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = (): Codec => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n","import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n\n this.code = code\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { isPromise } from '../util.js'\nimport * as crypto from './ed25519.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Ed25519PublicKey {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id (): Promise {\n const encoding = identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n }\n\n bytes = ensureKey(bytes, crypto.privateKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const { privateKey, publicKey } = crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array): Promise {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE')\n }\n return key\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport * as utils from './rsa-utils.js'\nimport type { JWKKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport { utils }\n\nexport async function generateKey (bits: number): Promise {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey): Promise {\n return webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\nexport function keySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE')\n } else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n","import { CodeError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH')\n }\n return randB(length)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2'\nimport { sha512 } from '@noble/hashes/sha512'\nimport * as asn1js from 'asn1js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport { type RsaPrivateKey, unmarshalRsaPrivateKey } from './rsa-class.js'\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value\n\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n }\n\n return key\n}\n\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value\n\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n }\n}\n\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\nfunction bnToBuf (bn: bigint): Uint8Array {\n let hex = bn.toString(16)\n\n if (hex.length % 2 > 0) {\n hex = `0${hex}`\n }\n\n const len = hex.length / 2\n const u8 = new Uint8Array(len)\n\n let i = 0\n let j = 0\n\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16)\n i += 1\n j += 2\n }\n\n return u8\n}\n\nfunction bufToBn (u8: Uint8Array): bigint {\n const hex: string[] = []\n\n u8.forEach(function (i) {\n let h = i.toString(16)\n\n if (h.length % 2 > 0) {\n h = `0${h}`\n }\n\n hex.push(h)\n })\n\n return BigInt('0x' + hex.join(''))\n}\n\nconst SALT_LENGTH = 16\nconst KEY_SIZE = 32\nconst ITERATIONS = 10000\n\nexport async function exportToPem (privateKey: RsaPrivateKey, password: string): Promise {\n const crypto = webcrypto.get()\n\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n })\n\n const keyBuf = keyWrapper.toBER()\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength)\n const salt = randomBytes(SALT_LENGTH)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n }\n )\n\n const iv = randomBytes(16)\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt'])\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr)\n\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n })\n\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n })\n\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n })\n\n const finalWrapperBuf = finalWrapper.toBER()\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength)\n\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n')\n}\n\nexport async function importFromPem (pem: string, password: string): Promise {\n const crypto = webcrypto.get()\n let plaintext: Uint8Array\n\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n const {\n iv,\n salt,\n iterations,\n keySize,\n cipherText\n } = findEncryptedPEMData(result)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: iterations,\n dkLen: keySize\n }\n )\n\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt'])\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText))\n\n const { result: decryptedResult } = asn1js.fromBER(decrypted)\n plaintext = findPEMData(decryptedResult)\n } else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n plaintext = findPEMData(result)\n } else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS')\n }\n\n return unmarshalRsaPrivateKey(plaintext)\n}\n\nfunction findEncryptedPEMData (root: any): { cipherText: Uint8Array, iv: Uint8Array, salt: Uint8Array, iterations: number, keySize: number } {\n const encryptionAlgorithm = root.valueBlock.value[0]\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString()\n\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS')\n }\n\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0]\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString()\n\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS')\n }\n\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1]\n\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue())\n\n let iterations = ITERATIONS\n let keySize = KEY_SIZE\n\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number((pbkdf2Params.valueBlock.value[1] as asn1js.Integer).toBigInt())\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt())\n } else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS')\n }\n\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1]\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString()\n\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n } else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS')\n }\n\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue())\n\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n }\n}\n\nfunction findPEMData (seq: any): Uint8Array {\n return toUint8Array(seq.valueBlock.value[2].getValue())\n}\n\nfunction toUint8Array (buf: ArrayBuffer): Uint8Array {\n return new Uint8Array(buf, 0, buf.byteLength)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport * as crypto from './rsa.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const MAX_RSA_KEY_SIZE = 8192\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean | boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret (): Uint8Array {\n return crypto.getRandomValues(16)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): RsaPublicKey {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export (password: string, format = 'pkcs-8'): Promise> {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password)\n } else if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array): Promise {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array): RsaPublicKey {\n const jwk = crypto.utils.pkixToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey): Promise {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number): Promise {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.generateKey(bits)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { isPromise } from '../util.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign (key: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.sign(p.digest, key).toDERRawBytes()\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.verify(sig, p.digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array): void {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array): void {\n try {\n secp.ProjectivePoint.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\nimport * as crypto from './secp256k1.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Secp256k1PublicKey {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const privateKeyBytes = crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport * as Ed25519 from './ed25519-class.js'\nimport generateEphemeralKeyPair from './ephemeral-keys.js'\nimport { importer } from './importer.js'\nimport { keyStretcher } from './key-stretcher.js'\nimport * as keysPBM from './keys.js'\nimport * as RSA from './rsa-class.js'\nimport { importFromPem } from './rsa-utils.js'\nimport * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js'\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js'\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js'\nexport type { JWKKeyPair } from './interface.js'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string): CodeError> {\n const supported = Object.keys(supportedKeys).join(' / ')\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE')\n}\n\nfunction typeToKey (type: string): typeof RSA | typeof Ed25519 | typeof Secp256k1 {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise {\n return typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE')\n }\n\n return Ed25519.generateKeyPairFromSeed(seed)\n}\n\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown')\n }\n}\n\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise {\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA')\n }\n}\n\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey (encryptedKey: string, password: string): Promise {\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT')\n }\n\n return importFromPem(encryptedKey, password)\n}\n","import type { RoutingOptions } from '../index.js'\nimport type { PeerInfo } from '../peer-info/index.js'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Any object that implements this Symbol as a property should return a\n * ContentRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { contentRoutingSymbol, ContentRouting } from '@libp2p/content-routing'\n *\n * class MyContentRouter implements ContentRouting {\n * get [contentRoutingSymbol] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const contentRoutingSymbol = Symbol.for('@libp2p/content-routing')\n\n/**\n * Implementers of this interface can provide a ContentRouting implementation to\n * interested callers.\n */\nexport interface ContentRoutingProvider {\n [contentRoutingSymbol]: ContentRouting\n}\n\nexport interface ContentRouting {\n /**\n * The implementation of this method should ensure that network peers know the\n * caller can provide content that corresponds to the passed CID.\n *\n * @example\n *\n * ```TypeScript\n * // ...\n * await contentRouting.provide(cid)\n * ```\n */\n provide(cid: CID, options?: RoutingOptions): Promise\n\n /**\n * Find the providers of the passed CID.\n *\n * @example\n *\n * ```TypeScript\n * // Iterate over the providers found for the given cid\n * for await (const provider of contentRouting.findProviders(cid)) {\n * console.log(provider.id, provider.multiaddrs)\n * }\n * ```\n */\n findProviders(cid: CID, options?: RoutingOptions): AsyncIterable\n\n /**\n * Puts a value corresponding to the passed key in a way that can later be\n * retrieved by another network peer using the get method.\n *\n * @example\n *\n * ```TypeScript\n * // ...\n * const key = '/key'\n * const value = uint8ArrayFromString('oh hello there')\n *\n * await contentRouting.put(key, value)\n * ```\n */\n put(key: Uint8Array, value: Uint8Array, options?: RoutingOptions): Promise\n\n /**\n * Retrieves a value from the network corresponding to the passed key.\n *\n * @example\n *\n * ```TypeScript\n * // ...\n *\n * const key = '/key'\n * const value = await contentRouting.get(key)\n * ```\n */\n get(key: Uint8Array, options?: RoutingOptions): Promise\n}\n","import type { RoutingOptions } from '../index.js'\nimport type { PeerId } from '../peer-id/index.js'\nimport type { PeerInfo } from '../peer-info/index.js'\n\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerRouting, PeerRouting } from '@libp2p/peer-routing'\n *\n * class MyPeerRouter implements PeerRouting {\n * get [peerRouting] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerRoutingSymbol = Symbol.for('@libp2p/peer-routing')\n\n/**\n * Implementers of this interface can provide a PeerRouting implementation to\n * interested callers.\n */\nexport interface PeerRoutingProvider {\n [peerRoutingSymbol]: PeerRouting\n}\n\nexport interface PeerRouting {\n /**\n * Searches the network for peer info corresponding to the passed peer id.\n *\n * @example\n *\n * ```TypeScript\n * // ...\n * const peer = await peerRouting.findPeer(peerId, options)\n * ```\n */\n findPeer(peerId: PeerId, options?: RoutingOptions): Promise\n\n /**\n * Search the network for peers that are closer to the passed key. Peer\n * info should be yielded in ever-increasing closeness to the key.\n *\n * @example\n *\n * ```TypeScript\n * // Iterate over the closest peers found for the given key\n * for await (const peer of peerRouting.getClosestPeers(key)) {\n * console.log(peer.id, peer.multiaddrs)\n * }\n * ```\n */\n getClosestPeers(key: Uint8Array, options?: RoutingOptions): AsyncIterable\n}\n","/**\n * @packageDocumentation\n *\n * A logger for libp2p based on the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: \n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\nimport debug from 'debug'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport { truncatePeerId } from './utils.js'\nimport type { PeerId } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error(formatter: any, ...args: any[]): void\n trace(formatter: any, ...args: any[]): void\n enabled: boolean\n}\n\nexport interface ComponentLogger {\n forComponent(name: string): Logger\n}\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport interface PeerLoggerOptions {\n prefixLength: number\n suffixLength: number\n}\n\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12…oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: Partial = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options))\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map(r => r.toString()).find(n => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`)\n }\n\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nexport function mapIterable (iter: IterableIterator, map: (val: T) => R): IterableIterator {\n const iterator: IterableIterator = {\n [Symbol.iterator]: () => {\n return iterator\n },\n next: () => {\n const next = iter.next()\n const val = next.value\n\n if (next.done === true || val == null) {\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n return {\n done: false,\n value: map(val)\n }\n }\n }\n\n return iterator\n}\n","import { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\nimport type { PeerId } from '@libp2p/interface'\n\n/**\n * We can't use PeerIds as set entries because set entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n private readonly set: Set\n\n constructor (set?: PeerSet | Iterable) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size (): number {\n return this.set.size\n }\n\n [Symbol.iterator] (): IterableIterator {\n return this.values()\n }\n\n add (peer: PeerId): void {\n this.set.add(peer.toString())\n }\n\n clear (): void {\n this.set.clear()\n }\n\n delete (peer: PeerId): void {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const id = peerIdFromString(str)\n\n predicate(id, id, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values (): IterableIterator {\n return mapIterable(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n intersection (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n difference (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n union (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n output.add(peerId)\n }\n\n for (const peerId of this) {\n output.add(peerId)\n }\n\n return output\n }\n}\n\nexport function peerSet (): PeerSet {\n return new PeerSet()\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n\nexport function isPromise (thing: any): thing is Promise {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n","import { ed25519 as ed } from '@noble/curves/ed25519'\nimport type { Uint8ArrayKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32\nconst PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed (seed: Uint8Array): Uint8ArrayKeyPair {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw)\n}\n\nexport function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH)\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i]\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i]\n }\n return privateKey\n}\n","/* eslint-env browser */\n\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get (win = globalThis) {\n const nativeCrypto = win.crypto\n\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n 'Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n","import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\n\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' }\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions): AESCipher {\n const algorithm = opts?.algorithm ?? 'AES-GCM'\n let keyLength = opts?.keyLength ?? 16\n const nonceLength = opts?.nonceLength ?? 12\n const digest = opts?.digest ?? 'SHA-256'\n const saltLength = opts?.saltLength ?? 16\n const iterations = opts?.iterations ?? 32767\n\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n }\n } else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt'])\n }\n\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data)\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)])\n }\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = data.subarray(0, saltLength)\n const nonce = data.subarray(saltLength, saltLength + nonceLength)\n const ciphertext = data.subarray(saltLength + nonceLength)\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt'])\n }\n } else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt'])\n }\n\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext)\n return new Uint8Array(plaintext)\n }\n\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\nimport type { Multibase } from 'multiformats'\n\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter (privateKey: Uint8Array, password: string): Promise> {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\n","const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n","import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = (): Codec => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n","import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n\n this.code = code\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { isPromise } from '../util.js'\nimport * as crypto from './ed25519.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Ed25519PublicKey {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id (): Promise {\n const encoding = identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n }\n\n bytes = ensureKey(bytes, crypto.privateKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const { privateKey, publicKey } = crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array): Promise {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE')\n }\n return key\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport * as utils from './rsa-utils.js'\nimport type { JWKKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport { utils }\n\nexport async function generateKey (bits: number): Promise {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey): Promise {\n return webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\nexport function keySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE')\n } else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n","import { CodeError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH')\n }\n return randB(length)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2'\nimport { sha512 } from '@noble/hashes/sha512'\nimport * as asn1js from 'asn1js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport { type RsaPrivateKey, unmarshalRsaPrivateKey } from './rsa-class.js'\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value\n\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n }\n\n return key\n}\n\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value\n\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n }\n}\n\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\nfunction bnToBuf (bn: bigint): Uint8Array {\n let hex = bn.toString(16)\n\n if (hex.length % 2 > 0) {\n hex = `0${hex}`\n }\n\n const len = hex.length / 2\n const u8 = new Uint8Array(len)\n\n let i = 0\n let j = 0\n\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16)\n i += 1\n j += 2\n }\n\n return u8\n}\n\nfunction bufToBn (u8: Uint8Array): bigint {\n const hex: string[] = []\n\n u8.forEach(function (i) {\n let h = i.toString(16)\n\n if (h.length % 2 > 0) {\n h = `0${h}`\n }\n\n hex.push(h)\n })\n\n return BigInt('0x' + hex.join(''))\n}\n\nconst SALT_LENGTH = 16\nconst KEY_SIZE = 32\nconst ITERATIONS = 10000\n\nexport async function exportToPem (privateKey: RsaPrivateKey, password: string): Promise {\n const crypto = webcrypto.get()\n\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n })\n\n const keyBuf = keyWrapper.toBER()\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength)\n const salt = randomBytes(SALT_LENGTH)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n }\n )\n\n const iv = randomBytes(16)\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt'])\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr)\n\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n })\n\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n })\n\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n })\n\n const finalWrapperBuf = finalWrapper.toBER()\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength)\n\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n')\n}\n\nexport async function importFromPem (pem: string, password: string): Promise {\n const crypto = webcrypto.get()\n let plaintext: Uint8Array\n\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n const {\n iv,\n salt,\n iterations,\n keySize,\n cipherText\n } = findEncryptedPEMData(result)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: iterations,\n dkLen: keySize\n }\n )\n\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt'])\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText))\n\n const { result: decryptedResult } = asn1js.fromBER(decrypted)\n plaintext = findPEMData(decryptedResult)\n } else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n plaintext = findPEMData(result)\n } else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS')\n }\n\n return unmarshalRsaPrivateKey(plaintext)\n}\n\nfunction findEncryptedPEMData (root: any): { cipherText: Uint8Array, iv: Uint8Array, salt: Uint8Array, iterations: number, keySize: number } {\n const encryptionAlgorithm = root.valueBlock.value[0]\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString()\n\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS')\n }\n\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0]\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString()\n\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS')\n }\n\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1]\n\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue())\n\n let iterations = ITERATIONS\n let keySize = KEY_SIZE\n\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number((pbkdf2Params.valueBlock.value[1] as asn1js.Integer).toBigInt())\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt())\n } else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS')\n }\n\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1]\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString()\n\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n } else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS')\n }\n\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue())\n\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n }\n}\n\nfunction findPEMData (seq: any): Uint8Array {\n return toUint8Array(seq.valueBlock.value[2].getValue())\n}\n\nfunction toUint8Array (buf: ArrayBuffer): Uint8Array {\n return new Uint8Array(buf, 0, buf.byteLength)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport * as crypto from './rsa.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const MAX_RSA_KEY_SIZE = 8192\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean | boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret (): Uint8Array {\n return crypto.getRandomValues(16)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): RsaPublicKey {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export (password: string, format = 'pkcs-8'): Promise> {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password)\n } else if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array): Promise {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array): RsaPublicKey {\n const jwk = crypto.utils.pkixToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey): Promise {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number): Promise {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.generateKey(bits)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { isPromise } from '../util.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign (key: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.sign(p.digest, key).toDERRawBytes()\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.verify(sig, p.digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array): void {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array): void {\n try {\n secp.ProjectivePoint.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\nimport * as crypto from './secp256k1.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Secp256k1PublicKey {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const privateKeyBytes = crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport * as Ed25519 from './ed25519-class.js'\nimport generateEphemeralKeyPair from './ephemeral-keys.js'\nimport { importer } from './importer.js'\nimport { keyStretcher } from './key-stretcher.js'\nimport * as keysPBM from './keys.js'\nimport * as RSA from './rsa-class.js'\nimport { importFromPem } from './rsa-utils.js'\nimport * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js'\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js'\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js'\nexport type { JWKKeyPair } from './interface.js'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string): CodeError> {\n const supported = Object.keys(supportedKeys).join(' / ')\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE')\n}\n\nfunction typeToKey (type: string): typeof RSA | typeof Ed25519 | typeof Secp256k1 {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise {\n return typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE')\n }\n\n return Ed25519.generateKeyPairFromSeed(seed)\n}\n\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown')\n }\n}\n\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise {\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA')\n }\n}\n\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey (encryptedKey: string, password: string): Promise {\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT')\n }\n\n return importFromPem(encryptedKey, password)\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","/**\n * @packageDocumentation\n *\n * Generate, import, and export PeerIDs.\n *\n * A Peer ID is the SHA-256 [multihash](https://github.com/multiformats/multihash) of a public key.\n *\n * The public key is a base64 encoded string of a protobuf containing an RSA DER buffer. This uses a node buffer to pass the base64 encoded public key protobuf to the multihash for ID generation.\n *\n * @example\n *\n * ```TypeScript\n * import { createEd25519PeerId } from '@libp2p/peer-id-factory'\n *\n * const peerId = await createEd25519PeerId()\n * console.log(peerId.toString())\n * ```\n *\n * ```bash\n * 12D3KooWRm8J3iL796zPFi2EtGGtUJn58AG67gcqzMFHZnnsTzqD\n * ```\n */\n\nimport { generateKeyPair, marshalPrivateKey, unmarshalPrivateKey, marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { peerIdFromKeys, peerIdFromBytes } from '@libp2p/peer-id'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { PeerIdProto } from './proto.js'\nimport type { PublicKey, PrivateKey, RSAPeerId, Ed25519PeerId, Secp256k1PeerId, PeerId } from '@libp2p/interface'\n\nexport const createEd25519PeerId = async (): Promise => {\n const key = await generateKeyPair('Ed25519')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'Ed25519') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createSecp256k1PeerId = async (): Promise => {\n const key = await generateKeyPair('secp256k1')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'secp256k1') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createRSAPeerId = async (opts?: { bits: number }): Promise => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048)\n const id = await createFromPrivKey(key)\n\n if (id.type === 'RSA') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport async function createFromPubKey (publicKey: PublicKey): Promise {\n return peerIdFromKeys(marshalPublicKey(publicKey))\n}\n\nexport async function createFromPrivKey (privateKey: PrivateKey): Promise {\n return peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey))\n}\n\nexport function exportToProtobuf (peerId: RSAPeerId | Ed25519PeerId | Secp256k1PeerId, excludePrivateKey?: boolean): Uint8Array {\n return PeerIdProto.encode({\n id: peerId.multihash.bytes,\n pubKey: peerId.publicKey,\n privKey: excludePrivateKey === true || peerId.privateKey == null ? undefined : peerId.privateKey\n })\n}\n\nexport async function createFromProtobuf (buf: Uint8Array): Promise {\n const {\n id,\n privKey,\n pubKey\n } = PeerIdProto.decode(buf)\n\n return createFromParts(\n id ?? new Uint8Array(0),\n privKey,\n pubKey\n )\n}\n\nexport async function createFromJSON (obj: { id: string, privKey?: string, pubKey?: string }): Promise {\n return createFromParts(\n uint8ArrayFromString(obj.id, 'base58btc'),\n obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined,\n obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined\n )\n}\n\nasync function createFromParts (multihash: Uint8Array, privKey?: Uint8Array, pubKey?: Uint8Array): Promise {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey)\n\n return createFromPrivKey(key)\n } else if (pubKey != null) {\n const key = unmarshalPublicKey(pubKey)\n\n return createFromPubKey(key)\n }\n\n return peerIdFromBytes(multihash)\n}\n","import { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\nimport type { PeerId } from '@libp2p/interface'\n\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nexport class PeerMap {\n private readonly map: Map\n\n constructor (map?: PeerMap) {\n this.map = new Map()\n\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value)\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator<[PeerId, T]> {\n return this.entries()\n }\n\n clear (): void {\n this.map.clear()\n }\n\n delete (peer: PeerId): boolean {\n return this.map.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, T]> {\n return mapIterable<[string, T], [PeerId, T]>(\n this.map.entries(),\n (val) => {\n return [peerIdFromString(val[0]), val[1]]\n }\n )\n }\n\n forEach (fn: (value: T, key: PeerId, map: PeerMap) => void): void {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this)\n })\n }\n\n get (peer: PeerId): T | undefined {\n return this.map.get(peer.toString())\n }\n\n has (peer: PeerId): boolean {\n return this.map.has(peer.toString())\n }\n\n set (peer: PeerId, value: T): void {\n this.map.set(peer.toString(), value)\n }\n\n keys (): IterableIterator {\n return mapIterable(\n this.map.keys(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n values (): IterableIterator {\n return this.map.values()\n }\n\n get size (): number {\n return this.map.size\n }\n}\n\nexport function peerMap (): PeerMap {\n return new PeerMap()\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n run,\n };\n if (this.size && this.#queue[this.size - 1].priority >= options.priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n","// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n","import { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n async add(function_, options = {}) {\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n","export interface WebworkerEventListener {\n (worker: Worker, event: MessageEvent): void\n}\n\nconst events: Record = {}\n\nconst observable = (worker: Worker & { port?: any }) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event)\n })\n\n if (worker.port != null) {\n worker.port.addEventListener('message', (event: any) => {\n observable.dispatchEvent('message', worker, event)\n })\n }\n}\n\nobservable.addEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n events[type] = []\n }\n\n events[type].push(fn)\n}\n\nobservable.removeEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n return\n }\n\n events[type] = events[type]\n .filter(listener => listener === fn)\n}\n\nobservable.dispatchEvent = function (type: string, worker: Worker, event: MessageEvent) {\n if (events[type] == null) {\n return\n }\n\n events[type].forEach(fn => fn(worker, event))\n}\n\nexport default observable\n","export const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read'\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read'\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read'\n\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write'\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write'\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write'\n","import observer from 'observable-webworkers'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n} from './constants.js'\nimport { nanoid } from './utils.js'\nimport type { MorticeImplementation, MorticeOptions, Release } from './index.js'\n\nconst handleWorkerLockRequest = (emitter: EventTarget, masterEvent: string, requestType: string, releaseType: string, grantType: string) => {\n return (worker: Worker, event: MessageEvent) => {\n if (event.data.type !== requestType) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async (): Promise => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n await new Promise((resolve) => {\n const releaseEventListener = (event: MessageEvent): void => {\n if (event == null || event.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n worker.addEventListener('message', releaseEventListener)\n })\n }\n }\n }))\n }\n}\n\nconst makeWorkerLockRequest = (name: string, requestType: string, grantType: string, releaseType: string) => {\n return async () => {\n const id = nanoid()\n\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n })\n\n return new Promise((resolve) => {\n const listener = (event: MessageEvent): void => {\n if (event == null || event.data == null) {\n return\n }\n\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n }\n\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener)\n\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n })\n })\n }\n }\n\n globalThis.addEventListener('message', listener)\n })\n }\n}\n\nconst defaultOptions = {\n singleProcess: false\n}\n\nexport default (options: Required): MorticeImplementation | EventTarget => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const emitter = new EventTarget()\n\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK))\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK))\n\n return emitter\n }\n\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK)\n }\n}\n","export const nanoid = (size: number = 21): string => {\n return Math.random().toString().substring(2)\n}\n","/**\n * @packageDocumentation\n *\n * - Reads occur concurrently\n * - Writes occur one at a time\n * - No reads occur while a write operation is in progress\n * - Locks can be created with different names\n * - Reads/writes can time out\n *\n * ## Usage\n *\n * ```javascript\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * // the lock name & options objects are both optional\n * const mutex = mortice('my-lock', {\n *\n * // how long before write locks time out (default: 24 hours)\n * timeout: 30000,\n *\n * // control how many read operations are executed concurrently (default: Infinity)\n * concurrency: 5,\n *\n * // by default the the lock will be held on the main thread, set this to true if the\n * // a lock should reside on each worker (default: false)\n * singleProcess: false\n * })\n *\n * Promise.all([\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 2')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.writeLock()\n *\n * try {\n * await delay(1000)\n *\n * console.info('write 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 3')\n * } finally {\n * release()\n * }\n * })()\n * ])\n * ```\n *\n * read 1\n * read 2\n * \n * write 1\n * read 3\n *\n * ## Browser\n *\n * Because there's no global way to evesdrop on messages sent by Web Workers, please pass all created Web Workers to the [`observable-webworkers`](https://npmjs.org/package/observable-webworkers) module:\n *\n * ```javascript\n * // main.js\n * import mortice from 'mortice'\n * import observe from 'observable-webworkers'\n *\n * // create our lock on the main thread, it will be held here\n * const mutex = mortice()\n *\n * const worker = new Worker('worker.js')\n *\n * observe(worker)\n * ```\n *\n * ```javascript\n * // worker.js\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * const mutex = mortice()\n *\n * let release = await mutex.readLock()\n * // read something\n * release()\n *\n * release = await mutex.writeLock()\n * // write something\n * release()\n * ```\n */\n\nimport PQueue from 'p-queue'\nimport pTimeout from 'p-timeout'\nimport impl from './node.js'\n\nexport interface MorticeOptions {\n name?: string\n timeout?: number\n concurrency?: number\n singleProcess?: boolean\n}\n\nexport interface Mortice {\n readLock(): Promise\n writeLock(): Promise\n}\n\nexport interface Release {\n (): void\n}\n\nexport interface MorticeImplementation {\n isWorker: boolean\n readLock(name: string, options: MorticeOptions): Mortice['readLock']\n writeLock(name: string, options: MorticeOptions): Mortice['writeLock']\n}\n\nconst mutexes: Record = {}\nlet implementation: any\n\nasync function createReleaseable (queue: PQueue, options: Required): Promise {\n let res: (release: Release) => void\n\n const p = new Promise((resolve) => {\n res = resolve\n })\n\n void queue.add(async () => pTimeout((async () => {\n await new Promise((resolve) => {\n res(() => {\n resolve()\n })\n })\n })(), {\n milliseconds: options.timeout\n }))\n\n return p\n}\n\nconst createMutex = (name: string, options: Required): Mortice => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n }\n }\n\n const masterQueue = new PQueue({ concurrency: 1 })\n let readQueue: PQueue | null\n\n return {\n async readLock () {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return createReleaseable(readQueue, options)\n }\n\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options)\n\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start()\n\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null\n }\n })\n })\n\n return readPromise\n },\n async writeLock () {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null\n\n return createReleaseable(masterQueue, options)\n }\n }\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n}\n\ninterface EventData {\n name: string\n handler(): Promise\n}\n\nexport default function createMortice (options?: MorticeOptions): Mortice {\n const opts: Required = Object.assign({}, defaultOptions, options)\n\n if (implementation == null) {\n implementation = impl(opts)\n\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].readLock()\n .then(async release => event.data.handler().finally(() => { release() }))\n })\n\n implementation.addEventListener('requestWriteLock', async (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].writeLock()\n .then(async release => event.data.handler().finally(() => { release() }))\n })\n }\n }\n\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts)\n }\n\n return mutexes[opts.name]\n}\n","export const codes = {\n ERR_INVALID_PARAMETERS: 'ERR_INVALID_PARAMETERS'\n}\n","const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n","import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Peer {\n addresses: Address[]\n protocols: string[]\n publicKey?: Uint8Array\n peerRecordEnvelope?: Uint8Array\n metadata: Map\n tags: Map\n}\n\nexport namespace Peer {\n export interface Peer$metadataEntry {\n key: string\n value: Uint8Array\n }\n\n export namespace Peer$metadataEntry {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10)\n w.string(obj.key)\n }\n\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n key: '',\n value: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.string()\n break\n case 2:\n obj.value = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Peer$metadataEntry.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer$metadataEntry => {\n return decodeMessage(buf, Peer$metadataEntry.codec())\n }\n }\n\n export interface Peer$tagsEntry {\n key: string\n value?: Tag\n }\n\n export namespace Peer$tagsEntry {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10)\n w.string(obj.key)\n }\n\n if (obj.value != null) {\n w.uint32(18)\n Tag.codec().encode(obj.value, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n key: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.string()\n break\n case 2:\n obj.value = Tag.codec().decode(reader, reader.uint32())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Peer$tagsEntry.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer$tagsEntry => {\n return decodeMessage(buf, Peer$tagsEntry.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(10)\n Address.codec().encode(value, w)\n }\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(18)\n w.string(value)\n }\n }\n\n if (obj.publicKey != null) {\n w.uint32(34)\n w.bytes(obj.publicKey)\n }\n\n if (obj.peerRecordEnvelope != null) {\n w.uint32(42)\n w.bytes(obj.peerRecordEnvelope)\n }\n\n if (obj.metadata != null && obj.metadata.size !== 0) {\n for (const [key, value] of obj.metadata.entries()) {\n w.uint32(50)\n Peer.Peer$metadataEntry.codec().encode({ key, value }, w)\n }\n }\n\n if (obj.tags != null && obj.tags.size !== 0) {\n for (const [key, value] of obj.tags.entries()) {\n w.uint32(58)\n Peer.Peer$tagsEntry.codec().encode({ key, value }, w)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n addresses: [],\n protocols: [],\n metadata: new Map(),\n tags: new Map()\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.addresses.push(Address.codec().decode(reader, reader.uint32()))\n break\n case 2:\n obj.protocols.push(reader.string())\n break\n case 4:\n obj.publicKey = reader.bytes()\n break\n case 5:\n obj.peerRecordEnvelope = reader.bytes()\n break\n case 6: {\n const entry = Peer.Peer$metadataEntry.codec().decode(reader, reader.uint32())\n obj.metadata.set(entry.key, entry.value)\n break\n }\n case 7: {\n const entry = Peer.Peer$tagsEntry.codec().decode(reader, reader.uint32())\n obj.tags.set(entry.key, entry.value)\n break\n }\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n}\n\nexport interface Address {\n multiaddr: Uint8Array\n isCertified?: boolean\n}\n\nexport namespace Address {\n let _codec: Codec
\n\n export const codec = (): Codec
=> {\n if (_codec == null) {\n _codec = message
((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (obj.isCertified != null) {\n w.uint32(16)\n w.bool(obj.isCertified)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes()\n break\n case 2:\n obj.isCertified = reader.bool()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial
): Uint8Array => {\n return encodeMessage(obj, Address.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Address => {\n return decodeMessage(buf, Address.codec())\n }\n}\n\nexport interface Tag {\n value: number\n expiry?: bigint\n}\n\nexport namespace Tag {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.value != null && obj.value !== 0)) {\n w.uint32(8)\n w.uint32(obj.value)\n }\n\n if (obj.expiry != null) {\n w.uint32(16)\n w.uint64(obj.expiry)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n value: 0\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.value = reader.uint32()\n break\n case 2:\n obj.expiry = reader.uint64()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Tag.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tag => {\n return decodeMessage(buf, Tag.codec())\n }\n}\n","import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n\n this.code = code\n }\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16)\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n","import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [777, V, 'memory']\n]\n\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\n}\n\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol (proto: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n","/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport { IpNet } from '@chainsafe/netmask'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf)\n case 42: // ipv6zone\n return bytes2str(buf)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf)\n\n case 421: // ipfs\n return bytes2mh(buf)\n case 444: // onion\n return bytes2onion(buf)\n case 445: // onion3\n return bytes2onion(buf)\n case 466: // certhash\n return bytes2mb(buf)\n default:\n return uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str)\n case 41: // ipv6\n return ip2bytes(str)\n case 42: // ipv6zone\n return str2bytes(str)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str)\n\n case 421: // ipfs\n return mh2bytes(str)\n case 444: // onion\n return onion2bytes(str)\n case 445: // onion3\n return onion32bytes(str)\n case 466: // certhash\n return mb2bytes(str)\n default:\n return uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value\n }\n if (code === ipcidrProtocol.code) {\n mask = value\n }\n })\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr')\n }\n return new IpNet(addr, mask)\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length)\n if (ipString == null) {\n throw new Error('ipBuff is required')\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ipString\n}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.encodingLength(size))\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\n\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length))\n return uint8ArrayConcat([size, mh], size.length + mh.length)\n}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\n const mb = anybaseDecoder.decode(mbstr)\n const size = Uint8Array.from(varint.encode(mb.length))\n return uint8ArrayConcat([size, mb], size.length + mb.length)\n}\nfunction bytes2mb (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.encodingLength(size))\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.encodingLength(size))\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.slice(0, buf.length - 2)\n const portBytes = buf.slice(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n","import * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\nexport interface MultiaddrParts {\n bytes: Uint8Array\n string: string\n tuples: Tuple[]\n stringTuples: StringTuple[]\n path: string | null\n}\n\nexport function stringToMultiaddrParts (str: string): MultiaddrParts {\n str = cleanPath(str)\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n const parts = str.split('/').slice(1)\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n }\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([proto.code])\n stringTuples.push([proto.code])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'))\n tuples.push([proto.code, convertToBytes(proto.code, path)])\n stringTuples.push([proto.code, path])\n break\n }\n\n const bytes = convertToBytes(proto.code, parts[p])\n tuples.push([proto.code, bytes])\n stringTuples.push([proto.code, convertToString(proto.code, bytes)])\n }\n\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n }\n}\n\nexport function bytesToMultiaddrParts (bytes: Uint8Array): MultiaddrParts {\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, bytes.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n stringTuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = bytes.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n const stringAddr = convertToString(code, addr)\n stringTuples.push([code, stringAddr])\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr\n break\n }\n }\n\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n }\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n }))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr))\n return size + varint.encodingLength(size)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a Multiaddr in JavaScript\n *\n * @example\n *\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, type MultiaddrParts, tuplesToBytes } from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport { isMultiaddr, multiaddr, resolvers } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, MultiaddrObject, Protocol, StringTuple, Tuple, NodeAddress, ResolveOptions } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n public bytes: Uint8Array\n #string: string\n #tuples: Tuple[]\n #stringTuples: StringTuple[]\n #path: string | null\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n let parts: MultiaddrParts\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr)\n } else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`)\n }\n parts = stringToMultiaddrParts(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes)\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n\n this.bytes = parts.bytes\n this.#string = parts.string\n this.#tuples = parts.tuples\n this.#stringTuples = parts.stringTuples\n this.#path = parts.path\n }\n\n toString (): string {\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\n const tcp = getProtocol('tcp')\n const udp = getProtocol('udp')\n const ip4 = getProtocol('ip4')\n const ip6 = getProtocol('ip6')\n const dns6 = getProtocol('dns6')\n const ip6zone = getProtocol('ip6zone')\n\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\n\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name\n port = 443\n host = `${value ?? ''}${zone}`\n family = code === dns6.code ? 6 : 4\n }\n\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\n\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name\n host = `${value ?? ''}${zone}`\n family = code === ip6.code ? 6 : 4\n }\n }\n\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".')\n }\n\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n return this.#tuples.map(([code]) => code)\n }\n\n protoNames (): string[] {\n return this.#tuples.map(([code]) => getProtocol(code).name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new Multiaddr(addr)\n return new Multiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`)\n }\n return new Multiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr(tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n let tuples: Array<[number, string | undefined]> = []\n\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name])\n }\n\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = []\n }\n })\n\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc')\n }\n\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n return this.#path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: ResolveOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const result = await resolver(this, options)\n\n return result.map(str => multiaddr(str))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`)\n }\n\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\n\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false\n }\n return true\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.#string})`\n }\n}\n","/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddr } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddr)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(await ma.resolve(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\n\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Resolver } from './resolvers/index.js'\nimport type { DNS } from '@multiformats/dns'\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\n\nexport type { Resolver }\n\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js'\n\nexport interface ResolveOptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions(): MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos(): Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes(): number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames(): string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples(): Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples(): StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId(): string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath(): string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve(options?: ResolveOptions): Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress(): NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress(addr?: Multiaddr): boolean\n}\n\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\n if (addr == null) {\n throw new Error('requires node address object')\n }\n if (transport == null) {\n throw new Error('requires transport protocol')\n }\n let ip: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\n\n host = parts[0]\n const zone = parts[1]\n ip = `/ip6zone/${zone}/ip6`\n }\n break\n default:\n throw Error('Invalid addr family, should be 4 or 6.')\n }\n return new MultiaddrClass('/' + [ip, host, transport, addr.port].join('/'))\n}\n\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName (addr: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\nexport { getProtocol as protocols }\n","import { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { Peer as PeerPB } from '../pb/peer.js'\nimport type { PeerId, Peer, Tag } from '@libp2p/interface'\n\nexport function bytesToPeer (peerId: PeerId, buf: Uint8Array): Peer {\n const peer = PeerPB.decode(buf)\n\n if (peer.publicKey != null && peerId.publicKey == null) {\n peerId = peerIdFromPeerId({\n ...peerId,\n publicKey: peerId.publicKey\n })\n }\n\n const tags = new Map()\n\n // remove any expired tags\n const now = BigInt(Date.now())\n\n for (const [key, tag] of peer.tags.entries()) {\n if (tag.expiry != null && tag.expiry < now) {\n continue\n }\n\n tags.set(key, tag)\n }\n\n return {\n ...peer,\n id: peerId,\n addresses: peer.addresses.map(({ multiaddr: ma, isCertified }) => {\n return {\n multiaddr: multiaddr(ma),\n isCertified: isCertified ?? false\n }\n }),\n metadata: peer.metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined,\n tags\n }\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { type SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\n }\n\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString (encoding: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\n\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces (list: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/344502982398')\n * ```\n */\n static random (): Key {\n return new Key(Math.random().toString().substring(2))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\n\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array())\n }\n\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\n\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1)\n bytes.fill(pathSep, 0, 1)\n bytes.set(this._buf, 1)\n this._buf = bytes\n }\n\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1)\n }\n }\n\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less (key: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\n\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array}\n */\n namespaces (): string[] {\n return this.list()\n }\n\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\n\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\n\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type (): string {\n return namespaceType(this.baseNamespace())\n }\n\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name (): string {\n return namespaceValue(this.baseNamespace())\n }\n\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance (s: string): Key {\n return new Key(this.toString() + ':' + s)\n }\n\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path (): Key {\n let p = this.parent().toString()\n if (!p.endsWith(pathSepS)) {\n p += pathSepS\n }\n p += this.type()\n return new Key(p)\n }\n\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\n\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child (key: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\n\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\n\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\n\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat (...keys: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\n}\n\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType (ns: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\n\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue (ns: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\n\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array} arr\n * @returns {T[]}\n */\nfunction flatten (arr: any[]): string[] {\n return ([]).concat(...arr)\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { isPeerId, type PeerId } from '@libp2p/interface'\nimport { Key } from 'interface-datastore/key'\nimport { codes } from '../errors.js'\n\nexport const NAMESPACE_COMMON = '/peers/'\n\nexport function peerIdToDatastoreKey (peerId: PeerId): Key {\n if (!isPeerId(peerId) || peerId.type == null) {\n throw new CodeError('Invalid PeerId', codes.ERR_INVALID_PARAMETERS)\n }\n\n const b32key = peerId.toCID().toString()\n return new Key(`${NAMESPACE_COMMON}${b32key}`)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\nimport { codes } from '../errors.js'\nimport type { AddressFilter } from '../index.js'\nimport type { Address as AddressPB } from '../pb/peer.js'\nimport type { PeerId, Address } from '@libp2p/interface'\n\nexport async function dedupeFilterAndSortAddresses (peerId: PeerId, filter: AddressFilter, addresses: Array
): Promise {\n const addressMap = new Map()\n\n for (const addr of addresses) {\n if (addr == null) {\n continue\n }\n\n if (addr.multiaddr instanceof Uint8Array) {\n addr.multiaddr = multiaddr(addr.multiaddr)\n }\n\n if (!isMultiaddr(addr.multiaddr)) {\n throw new CodeError('Multiaddr was invalid', codes.ERR_INVALID_PARAMETERS)\n }\n\n if (!(await filter(peerId, addr.multiaddr))) {\n continue\n }\n\n const isCertified = addr.isCertified ?? false\n const maStr = addr.multiaddr.toString()\n const existingAddr = addressMap.get(maStr)\n\n if (existingAddr != null) {\n addr.isCertified = existingAddr.isCertified || isCertified\n } else {\n addressMap.set(maStr, {\n multiaddr: addr.multiaddr,\n isCertified\n })\n }\n }\n\n return [...addressMap.values()]\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString())\n })\n .map(({ isCertified, multiaddr }) => ({\n isCertified,\n multiaddr: multiaddr.bytes\n }))\n}\n","import { CodeError } from '@libp2p/interface'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport { codes } from '../errors.js'\nimport { dedupeFilterAndSortAddresses } from './dedupe-addresses.js'\nimport type { AddressFilter } from '../index.js'\nimport type { Tag, Peer as PeerPB } from '../pb/peer.js'\nimport type { PeerId, Address, Peer, PeerData, TagOptions } from '@libp2p/interface'\n\nexport interface ToPBPeerOptions {\n addressFilter?: AddressFilter\n existingPeer?: Peer\n}\n\nexport async function toPeerPB (peerId: PeerId, data: Partial, strategy: 'merge' | 'patch', options: ToPBPeerOptions): Promise {\n if (data == null) {\n throw new CodeError('Invalid PeerData', codes.ERR_INVALID_PARAMETERS)\n }\n\n if (data.publicKey != null && peerId.publicKey != null && !uint8arrayEquals(data.publicKey, peerId.publicKey)) {\n throw new CodeError('publicKey bytes do not match peer id publicKey bytes', codes.ERR_INVALID_PARAMETERS)\n }\n\n const existingPeer = options.existingPeer\n\n if (existingPeer != null && !peerId.equals(existingPeer.id)) {\n throw new CodeError('peer id did not match existing peer id', codes.ERR_INVALID_PARAMETERS)\n }\n\n let addresses: Address[] = existingPeer?.addresses ?? []\n let protocols = new Set(existingPeer?.protocols ?? [])\n let metadata: Map = existingPeer?.metadata ?? new Map()\n let tags: Map = existingPeer?.tags ?? new Map()\n let peerRecordEnvelope: Uint8Array | undefined = existingPeer?.peerRecordEnvelope\n\n // when patching, we replace the original fields with passed values\n if (strategy === 'patch') {\n if (data.multiaddrs != null || data.addresses != null) {\n addresses = []\n\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })))\n }\n\n if (data.addresses != null) {\n addresses.push(...data.addresses)\n }\n }\n\n if (data.protocols != null) {\n protocols = new Set(data.protocols)\n }\n\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata)\n\n metadata = createSortedMap(metadataEntries, {\n validate: validateMetadata\n })\n }\n\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags)\n\n tags = createSortedMap(tagsEntries, {\n validate: validateTag,\n map: mapTag\n })\n }\n\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope\n }\n }\n\n // when merging, we join the original fields with passed values\n if (strategy === 'merge') {\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })))\n }\n\n if (data.addresses != null) {\n addresses.push(...data.addresses)\n }\n\n if (data.protocols != null) {\n protocols = new Set([...protocols, ...data.protocols])\n }\n\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata)\n\n for (const [key, value] of metadataEntries) {\n if (value == null) {\n metadata.delete(key)\n } else {\n metadata.set(key, value)\n }\n }\n\n metadata = createSortedMap([...metadata.entries()], {\n validate: validateMetadata\n })\n }\n\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags)\n const mergedTags = new Map(tags)\n\n for (const [key, value] of tagsEntries) {\n if (value == null) {\n mergedTags.delete(key)\n } else {\n mergedTags.set(key, value)\n }\n }\n\n tags = createSortedMap([...mergedTags.entries()], {\n validate: validateTag,\n map: mapTag\n })\n }\n\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope\n }\n }\n\n const output: PeerPB = {\n addresses: await dedupeFilterAndSortAddresses(peerId, options.addressFilter ?? (async () => true), addresses),\n protocols: [...protocols.values()].sort((a, b) => {\n return a.localeCompare(b)\n }),\n metadata,\n tags,\n\n publicKey: existingPeer?.id.publicKey ?? data.publicKey ?? peerId.publicKey,\n peerRecordEnvelope\n }\n\n // Ed25519 and secp256k1 have their public key embedded in them so no need to duplicate it\n if (peerId.type !== 'RSA') {\n delete output.publicKey\n }\n\n return output\n}\n\ninterface CreateSortedMapOptions {\n validate(key: string, value: V): void\n map?(key: string, value: V): R\n}\n\n/**\n * In JS maps are ordered by insertion order so create a new map with the\n * keys inserted in alphabetical order.\n */\nfunction createSortedMap (entries: Array<[string, V | undefined]>, options: CreateSortedMapOptions): Map {\n const output = new Map()\n\n for (const [key, value] of entries) {\n if (value == null) {\n continue\n }\n\n options.validate(key, value)\n }\n\n for (const [key, value] of entries.sort(([a], [b]) => {\n return a.localeCompare(b)\n })) {\n if (value != null) {\n output.set(key, options.map?.(key, value) ?? value)\n }\n }\n\n return output\n}\n\nfunction validateMetadata (key: string, value: Uint8Array): void {\n if (typeof key !== 'string') {\n throw new CodeError('Metadata key must be a string', codes.ERR_INVALID_PARAMETERS)\n }\n\n if (!(value instanceof Uint8Array)) {\n throw new CodeError('Metadata value must be a Uint8Array', codes.ERR_INVALID_PARAMETERS)\n }\n}\n\nfunction validateTag (key: string, tag: TagOptions): void {\n if (typeof key !== 'string') {\n throw new CodeError('Tag name must be a string', codes.ERR_INVALID_PARAMETERS)\n }\n\n if (tag.value != null) {\n if (parseInt(`${tag.value}`, 10) !== tag.value) {\n throw new CodeError('Tag value must be an integer', codes.ERR_INVALID_PARAMETERS)\n }\n\n if (tag.value < 0 || tag.value > 100) {\n throw new CodeError('Tag value must be between 0-100', codes.ERR_INVALID_PARAMETERS)\n }\n }\n\n if (tag.ttl != null) {\n if (parseInt(`${tag.ttl}`, 10) !== tag.ttl) {\n throw new CodeError('Tag ttl must be an integer', codes.ERR_INVALID_PARAMETERS)\n }\n\n if (tag.ttl < 0) {\n throw new CodeError('Tag ttl must be between greater than 0', codes.ERR_INVALID_PARAMETERS)\n }\n }\n}\n\nfunction mapTag (key: string, tag: any): Tag {\n let expiry: bigint | undefined\n\n if (tag.expiry != null) {\n expiry = tag.expiry\n }\n\n if (tag.ttl != null) {\n expiry = BigInt(Date.now() + Number(tag.ttl))\n }\n\n return {\n value: tag.value ?? 0,\n expiry\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport mortice, { type Mortice } from 'mortice'\nimport { base32 } from 'multiformats/bases/base32'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { codes } from './errors.js'\nimport { Peer as PeerPB } from './pb/peer.js'\nimport { bytesToPeer } from './utils/bytes-to-peer.js'\nimport { NAMESPACE_COMMON, peerIdToDatastoreKey } from './utils/peer-id-to-datastore-key.js'\nimport { toPeerPB } from './utils/to-peer-pb.js'\nimport type { AddressFilter, PersistentPeerStoreComponents, PersistentPeerStoreInit } from './index.js'\nimport type { PeerUpdate as PeerUpdateExternal, PeerId, Peer, PeerData, PeerQuery } from '@libp2p/interface'\nimport type { Datastore, Key, Query } from 'interface-datastore'\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate extends PeerUpdateExternal {\n updated: boolean\n}\n\nfunction decodePeer (key: Key, value: Uint8Array, cache: PeerMap): Peer {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2]\n const buf = base32.decode(base32Str)\n const peerId = peerIdFromBytes(buf)\n\n const cached = cache.get(peerId)\n\n if (cached != null) {\n return cached\n }\n\n const peer = bytesToPeer(peerId, value)\n\n cache.set(peerId, peer)\n\n return peer\n}\n\nfunction mapQuery (query: PeerQuery, cache: PeerMap): Query {\n if (query == null) {\n return {}\n }\n\n return {\n prefix: NAMESPACE_COMMON,\n filters: (query.filters ?? []).map(fn => ({ key, value }) => {\n return fn(decodePeer(key, value, cache))\n }),\n orders: (query.orders ?? []).map(fn => (a, b) => {\n return fn(decodePeer(a.key, a.value, cache), decodePeer(b.key, b.value, cache))\n })\n }\n}\n\nexport class PersistentStore {\n private readonly peerId: PeerId\n private readonly datastore: Datastore\n public readonly lock: Mortice\n private readonly addressFilter?: AddressFilter\n\n constructor (components: PersistentPeerStoreComponents, init: PersistentPeerStoreInit = {}) {\n this.peerId = components.peerId\n this.datastore = components.datastore\n this.addressFilter = init.addressFilter\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n })\n }\n\n async has (peerId: PeerId): Promise {\n return this.datastore.has(peerIdToDatastoreKey(peerId))\n }\n\n async delete (peerId: PeerId): Promise {\n if (this.peerId.equals(peerId)) {\n throw new CodeError('Cannot delete self peer', codes.ERR_INVALID_PARAMETERS)\n }\n\n await this.datastore.delete(peerIdToDatastoreKey(peerId))\n }\n\n async load (peerId: PeerId): Promise {\n const buf = await this.datastore.get(peerIdToDatastoreKey(peerId))\n\n return bytesToPeer(peerId, buf)\n }\n\n async save (peerId: PeerId, data: PeerData): Promise {\n const {\n existingBuf,\n existingPeer\n } = await this.#findExistingPeer(peerId)\n\n const peerPb: PeerPB = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter\n })\n\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer)\n }\n\n async patch (peerId: PeerId, data: Partial): Promise {\n const {\n existingBuf,\n existingPeer\n } = await this.#findExistingPeer(peerId)\n\n const peerPb: PeerPB = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter,\n existingPeer\n })\n\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer)\n }\n\n async merge (peerId: PeerId, data: PeerData): Promise {\n const {\n existingBuf,\n existingPeer\n } = await this.#findExistingPeer(peerId)\n\n const peerPb: PeerPB = await toPeerPB(peerId, data, 'merge', {\n addressFilter: this.addressFilter,\n existingPeer\n })\n\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer)\n }\n\n async * all (query?: PeerQuery): AsyncGenerator {\n const peerCache = new PeerMap()\n\n for await (const { key, value } of this.datastore.query(mapQuery(query ?? {}, peerCache))) {\n const peer = decodePeer(key, value, peerCache)\n\n if (peer.id.equals(this.peerId)) {\n // Skip self peer if present\n continue\n }\n\n yield peer\n }\n }\n\n async #findExistingPeer (peerId: PeerId): Promise<{ existingBuf?: Uint8Array, existingPeer?: Peer }> {\n try {\n const existingBuf = await this.datastore.get(peerIdToDatastoreKey(peerId))\n const existingPeer = bytesToPeer(peerId, existingBuf)\n\n return {\n existingBuf,\n existingPeer\n }\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n return {}\n }\n\n async #saveIfDifferent (peerId: PeerId, peer: PeerPB, existingBuf?: Uint8Array, existingPeer?: Peer): Promise {\n const buf = PeerPB.encode(peer)\n\n if (existingBuf != null && uint8ArrayEquals(buf, existingBuf)) {\n return {\n peer: bytesToPeer(peerId, buf),\n previous: existingPeer,\n updated: false\n }\n }\n\n await this.datastore.put(peerIdToDatastoreKey(peerId), buf)\n\n return {\n peer: bytesToPeer(peerId, buf),\n previous: existingPeer,\n updated: true\n }\n }\n}\n","/**\n * @packageDocumentation\n *\n * The peer store is where libp2p stores data about the peers it has encountered on the network.\n */\n\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport all from 'it-all'\nimport { PersistentStore, type PeerUpdate } from './store.js'\nimport type { ComponentLogger, Libp2pEvents, Logger, TypedEventTarget, PeerId, PeerStore, Peer, PeerData, PeerQuery } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface PersistentPeerStoreComponents {\n peerId: PeerId\n datastore: Datastore\n events: TypedEventTarget\n logger: ComponentLogger\n}\n\n/**\n * Return true to allow storing the passed multiaddr for the passed peer\n */\nexport interface AddressFilter {\n (peerId: PeerId, multiaddr: Multiaddr): Promise\n}\n\nexport interface PersistentPeerStoreInit {\n addressFilter?: AddressFilter\n}\n\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nexport class PersistentPeerStore implements PeerStore {\n private readonly store: PersistentStore\n private readonly events: TypedEventTarget\n private readonly peerId: PeerId\n private readonly log: Logger\n\n constructor (components: PersistentPeerStoreComponents, init: PersistentPeerStoreInit = {}) {\n this.log = components.logger.forComponent('libp2p:peer-store')\n this.events = components.events\n this.peerId = components.peerId\n this.store = new PersistentStore(components, init)\n }\n\n async forEach (fn: (peer: Peer,) => void, query?: PeerQuery): Promise {\n this.log.trace('forEach await read lock')\n const release = await this.store.lock.readLock()\n this.log.trace('forEach got read lock')\n\n try {\n for await (const peer of this.store.all(query)) {\n fn(peer)\n }\n } finally {\n this.log.trace('forEach release read lock')\n release()\n }\n }\n\n async all (query?: PeerQuery): Promise {\n this.log.trace('all await read lock')\n const release = await this.store.lock.readLock()\n this.log.trace('all got read lock')\n\n try {\n return await all(this.store.all(query))\n } finally {\n this.log.trace('all release read lock')\n release()\n }\n }\n\n async delete (peerId: PeerId): Promise {\n this.log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n this.log.trace('delete got write lock')\n\n try {\n await this.store.delete(peerId)\n } finally {\n this.log.trace('delete release write lock')\n release()\n }\n }\n\n async has (peerId: PeerId): Promise {\n this.log.trace('has await read lock')\n const release = await this.store.lock.readLock()\n this.log.trace('has got read lock')\n\n try {\n return await this.store.has(peerId)\n } finally {\n this.log.trace('has release read lock')\n release()\n }\n }\n\n async get (peerId: PeerId): Promise {\n this.log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n this.log.trace('get got read lock')\n\n try {\n return await this.store.load(peerId)\n } finally {\n this.log.trace('get release read lock')\n release()\n }\n }\n\n async save (id: PeerId, data: PeerData): Promise {\n this.log.trace('save await write lock')\n const release = await this.store.lock.writeLock()\n this.log.trace('save got write lock')\n\n try {\n const result = await this.store.save(id, data)\n\n this.#emitIfUpdated(id, result)\n\n return result.peer\n } finally {\n this.log.trace('save release write lock')\n release()\n }\n }\n\n async patch (id: PeerId, data: PeerData): Promise {\n this.log.trace('patch await write lock')\n const release = await this.store.lock.writeLock()\n this.log.trace('patch got write lock')\n\n try {\n const result = await this.store.patch(id, data)\n\n this.#emitIfUpdated(id, result)\n\n return result.peer\n } finally {\n this.log.trace('patch release write lock')\n release()\n }\n }\n\n async merge (id: PeerId, data: PeerData): Promise {\n this.log.trace('merge await write lock')\n const release = await this.store.lock.writeLock()\n this.log.trace('merge got write lock')\n\n try {\n const result = await this.store.merge(id, data)\n\n this.#emitIfUpdated(id, result)\n\n return result.peer\n } finally {\n this.log.trace('merge release write lock')\n release()\n }\n }\n\n async consumePeerRecord (buf: Uint8Array, expectedPeer?: PeerId): Promise {\n const envelope = await RecordEnvelope.openAndCertify(buf, PeerRecord.DOMAIN)\n\n if (expectedPeer?.equals(envelope.peerId) === false) {\n this.log('envelope peer id was not the expected peer id - expected: %p received: %p', expectedPeer, envelope.peerId)\n return false\n }\n\n const peerRecord = PeerRecord.createFromProtobuf(envelope.payload)\n let peer: Peer | undefined\n\n try {\n peer = await this.get(envelope.peerId)\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n // ensure seq is greater than, or equal to, the last received\n if (peer?.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope)\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload)\n\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber)\n return false\n }\n }\n\n await this.patch(peerRecord.peerId, {\n peerRecordEnvelope: buf,\n addresses: peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }))\n })\n\n return true\n }\n\n #emitIfUpdated (id: PeerId, result: PeerUpdate): void {\n if (!result.updated) {\n return\n }\n\n if (this.peerId.equals(id)) {\n this.events.safeDispatchEvent('self:peer:update', { detail: result })\n } else {\n this.events.safeDispatchEvent('peer:update', { detail: result })\n }\n }\n}\n","import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16)\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n","import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [777, V, 'memory']\n]\n\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\n}\n\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol (proto: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n","/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport { IpNet } from '@chainsafe/netmask'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf)\n case 42: // ipv6zone\n return bytes2str(buf)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf)\n\n case 421: // ipfs\n return bytes2mh(buf)\n case 444: // onion\n return bytes2onion(buf)\n case 445: // onion3\n return bytes2onion(buf)\n case 466: // certhash\n return bytes2mb(buf)\n default:\n return uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str)\n case 41: // ipv6\n return ip2bytes(str)\n case 42: // ipv6zone\n return str2bytes(str)\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str)\n\n case 421: // ipfs\n return mh2bytes(str)\n case 444: // onion\n return onion2bytes(str)\n case 445: // onion3\n return onion32bytes(str)\n case 466: // certhash\n return mb2bytes(str)\n default:\n return uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value\n }\n if (code === ipcidrProtocol.code) {\n mask = value\n }\n })\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr')\n }\n return new IpNet(addr, mask)\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length)\n if (ipString == null) {\n throw new Error('ipBuff is required')\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ipString\n}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.encodingLength(size))\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\n\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length))\n return uint8ArrayConcat([size, mh], size.length + mh.length)\n}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\n const mb = anybaseDecoder.decode(mbstr)\n const size = Uint8Array.from(varint.encode(mb.length))\n return uint8ArrayConcat([size, mb], size.length + mb.length)\n}\nfunction bytes2mb (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.encodingLength(size))\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.encodingLength(size))\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.slice(0, buf.length - 2)\n const portBytes = buf.slice(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n","import * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\nexport interface MultiaddrParts {\n bytes: Uint8Array\n string: string\n tuples: Tuple[]\n stringTuples: StringTuple[]\n path: string | null\n}\n\nexport function stringToMultiaddrParts (str: string): MultiaddrParts {\n str = cleanPath(str)\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n const parts = str.split('/').slice(1)\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n }\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([proto.code])\n stringTuples.push([proto.code])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'))\n tuples.push([proto.code, convertToBytes(proto.code, path)])\n stringTuples.push([proto.code, path])\n break\n }\n\n const bytes = convertToBytes(proto.code, parts[p])\n tuples.push([proto.code, bytes])\n stringTuples.push([proto.code, convertToString(proto.code, bytes)])\n }\n\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n }\n}\n\nexport function bytesToMultiaddrParts (bytes: Uint8Array): MultiaddrParts {\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, bytes.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n stringTuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = bytes.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n const stringAddr = convertToString(code, addr)\n stringTuples.push([code, stringAddr])\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr\n break\n }\n }\n\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n }\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n }))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr))\n return size + varint.encodingLength(size)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a Multiaddr in JavaScript\n *\n * @example\n *\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, type MultiaddrParts, tuplesToBytes } from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport { isMultiaddr, multiaddr, resolvers } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, MultiaddrObject, Protocol, StringTuple, Tuple, NodeAddress, ResolveOptions } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n public bytes: Uint8Array\n #string: string\n #tuples: Tuple[]\n #stringTuples: StringTuple[]\n #path: string | null\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n let parts: MultiaddrParts\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr)\n } else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`)\n }\n parts = stringToMultiaddrParts(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes)\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n\n this.bytes = parts.bytes\n this.#string = parts.string\n this.#tuples = parts.tuples\n this.#stringTuples = parts.stringTuples\n this.#path = parts.path\n }\n\n toString (): string {\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\n const tcp = getProtocol('tcp')\n const udp = getProtocol('udp')\n const ip4 = getProtocol('ip4')\n const ip6 = getProtocol('ip6')\n const dns6 = getProtocol('dns6')\n const ip6zone = getProtocol('ip6zone')\n\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\n\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name\n port = 443\n host = `${value ?? ''}${zone}`\n family = code === dns6.code ? 6 : 4\n }\n\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\n\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name\n host = `${value ?? ''}${zone}`\n family = code === ip6.code ? 6 : 4\n }\n }\n\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".')\n }\n\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n return this.#tuples.map(([code]) => code)\n }\n\n protoNames (): string[] {\n return this.#tuples.map(([code]) => getProtocol(code).name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new Multiaddr(addr)\n return new Multiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`)\n }\n return new Multiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr(tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n let tuples: Array<[number, string | undefined]> = []\n\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name])\n }\n\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = []\n }\n })\n\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc')\n }\n\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n return this.#path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: ResolveOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const result = await resolver(this, options)\n\n return result.map(str => multiaddr(str))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`)\n }\n\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\n\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false\n }\n return true\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.#string})`\n }\n}\n","/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddr } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddr)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(await ma.resolve(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\n\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Resolver } from './resolvers/index.js'\nimport type { DNS } from '@multiformats/dns'\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\n\nexport type { Resolver }\n\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js'\n\nexport interface ResolveOptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions(): MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos(): Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes(): number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames(): string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples(): Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples(): StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId(): string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath(): string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve(options?: ResolveOptions): Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress(): NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress(addr?: Multiaddr): boolean\n}\n\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\n if (addr == null) {\n throw new Error('requires node address object')\n }\n if (transport == null) {\n throw new Error('requires transport protocol')\n }\n let ip: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\n\n host = parts[0]\n const zone = parts[1]\n ip = `/ip6zone/${zone}/ip6`\n }\n break\n default:\n throw Error('Invalid addr family, should be 4 or 6.')\n }\n return new MultiaddrClass('/' + [ip, host, transport, addr.port].join('/'))\n}\n\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName (addr: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\nexport { getProtocol as protocols }\n","/**\n * @packageDocumentation\n *\n * Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values.\n *\n * @example\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * drain(values)\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * const values = async function * {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * await drain(values())\n * ```\n */\n\nfunction isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nfunction drain (source: Iterable): void\nfunction drain (source: Iterable | AsyncIterable): Promise\nfunction drain (source: Iterable | AsyncIterable): Promise | void {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n })()\n } else {\n for (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n }\n}\n\nexport default drain\n","/**\n * @packageDocumentation\n *\n * Lets you look at the contents of an async iterator and decide what to do\n *\n * @example\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const it = peekable(value)\n *\n * const first = it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info([...it])\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const it = peekable(values())\n *\n * const first = await it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info(await all(it))\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n */\n\nexport interface Peek {\n peek(): IteratorResult\n}\n\nexport interface AsyncPeek {\n peek(): Promise>\n}\n\nexport interface Push {\n push(value: T): void\n}\n\nexport type Peekable = Iterable & Peek & Push & Iterator\n\nexport type AsyncPeekable = AsyncIterable & AsyncPeek & Push & AsyncIterator\n\nfunction peekable (iterable: Iterable): Peekable\nfunction peekable (iterable: AsyncIterable): AsyncPeekable\nfunction peekable (iterable: Iterable | AsyncIterable): Peekable | AsyncPeekable {\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n const [iterator, symbol] = iterable[Symbol.asyncIterator] != null\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]\n // @ts-expect-error can't use Symbol.iterator to index iterable since it might be AsyncIterable\n : [iterable[Symbol.iterator](), Symbol.iterator]\n\n const queue: any[] = []\n\n // @ts-expect-error can't use symbol to index peekable\n return {\n peek: () => {\n return iterator.next()\n },\n push: (value: any) => {\n queue.push(value)\n },\n next: () => {\n if (queue.length > 0) {\n return {\n done: false,\n value: queue.shift()\n }\n }\n\n return iterator.next()\n },\n [symbol] () {\n return this\n }\n }\n}\n\nexport default peekable\n","/**\n * @packageDocumentation\n *\n * Filter values out of an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const fn = val => val > 2 // Return boolean to keep item\n *\n * const arr = all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n *\n * Async sources and filter functions must be awaited:\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const fn = async val => val > 2 // Return boolean or promise of boolean to keep item\n *\n * const arr = await all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n */\n\nimport peek from 'it-peekable'\n\nfunction isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Filters the passed (async) iterable by using the filter function\n */\nfunction filter (source: Iterable, fn: (val: T) => Promise): AsyncGenerator\nfunction filter (source: Iterable, fn: (val: T) => boolean): Generator\nfunction filter (source: Iterable | AsyncIterable, fn: (val: T) => boolean | Promise): AsyncGenerator\nfunction filter (source: Iterable | AsyncIterable, fn: (val: T) => boolean | Promise): Generator | AsyncGenerator {\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const entry of source) {\n if (await fn(entry)) {\n yield entry\n }\n }\n })()\n }\n\n // if mapping function returns a promise we have to return an async generator\n const peekable = peek(source)\n const { value, done } = peekable.next()\n\n if (done === true) {\n return (function * () {}())\n }\n\n const res = fn(value)\n\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function * () {\n if (await res) {\n yield value\n }\n\n for await (const entry of peekable) {\n if (await fn(entry)) {\n yield entry\n }\n }\n })()\n }\n\n const func = fn as (val: T) => boolean\n\n return (function * () {\n if (res === true) {\n yield value\n }\n\n for (const entry of peekable) {\n if (func(entry)) {\n yield entry\n }\n }\n })()\n}\n\nexport default filter\n","/**\n * @packageDocumentation\n *\n * Consumes all values from an (async)iterable and returns them sorted by the passed sort function.\n *\n * @example\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * // This can also be an iterator, generator, etc\n * const values = ['foo', 'bar']\n *\n * const arr = all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * const values = async function * () {\n * yield * ['foo', 'bar']\n * }\n *\n * const arr = await all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n */\n\nimport all from 'it-all'\n\nfunction isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n\nexport interface CompareFunction {\n (a: T, b: T): number\n}\n\n/**\n * Collects all values from an async iterator, sorts them\n * using the passed function and yields them\n */\nfunction sort (source: Iterable, sorter: CompareFunction): Generator\nfunction sort (source: Iterable | AsyncIterable, sorter: CompareFunction): AsyncGenerator\nfunction sort (source: Iterable | AsyncIterable, sorter: CompareFunction): AsyncGenerator | Generator {\n if (isAsyncIterable(source)) {\n return (async function * () {\n const arr = await all(source)\n\n yield * arr.sort(sorter)\n })()\n }\n\n return (function * () {\n const arr = all(source)\n\n yield * arr.sort(sorter)\n })()\n}\n\nexport default sort\n","/**\n * @packageDocumentation\n *\n * For when you only want a few values out of an (async)iterable.\n *\n * @example\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const arr = all(take(values, 2))\n *\n * console.info(arr) // 0, 1\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(take(values(), 2))\n *\n * console.info(arr) // 0, 1\n * ```\n */\n\nfunction isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Stop iteration after n items have been received\n */\nfunction take (source: Iterable, limit: number): Generator\nfunction take (source: Iterable | AsyncIterable, limit: number): AsyncGenerator\nfunction take (source: Iterable | AsyncIterable, limit: number): AsyncGenerator | Generator {\n if (isAsyncIterable(source)) {\n return (async function * () {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for await (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n })()\n }\n\n return (function * () {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n })()\n}\n\nexport default take\n","import drain from 'it-drain'\nimport filter from 'it-filter'\nimport sort from 'it-sort'\nimport take from 'it-take'\nimport type { Batch, Datastore, Key, KeyQuery, Pair, Query } from 'interface-datastore'\nimport type { AbortOptions, Await, AwaitIterable } from 'interface-store'\n\nexport class BaseDatastore implements Datastore {\n put (key: Key, val: Uint8Array, options?: AbortOptions): Await {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n get (key: Key, options?: AbortOptions): Await {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n has (key: Key, options?: AbortOptions): Await {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n delete (key: Key, options?: AbortOptions): Await {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n async * putMany (source: AwaitIterable, options: AbortOptions = {}): AwaitIterable {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield key\n }\n }\n\n async * getMany (source: AwaitIterable, options: AbortOptions = {}): AwaitIterable {\n for await (const key of source) {\n yield {\n key,\n value: await this.get(key, options)\n }\n }\n }\n\n async * deleteMany (source: AwaitIterable, options: AbortOptions = {}): AwaitIterable {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n batch (): Batch {\n let puts: Pair[] = []\n let dels: Key[] = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\n\n delete (key) {\n dels.push(key)\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options))\n puts = []\n await drain(this.deleteMany(dels, options))\n dels = []\n }\n }\n }\n\n /**\n * Extending classes should override `query` or implement this method\n */\n // eslint-disable-next-line require-yield\n async * _all (q: Query, options?: AbortOptions): AwaitIterable {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q: KeyQuery, options?: AbortOptions): AwaitIterable {\n throw new Error('._allKeys is not implemented')\n }\n\n query (q: Query, options?: AbortOptions): AwaitIterable {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n const prefix = q.prefix\n it = filter(it, (e) => e.key.toString().startsWith(prefix))\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n const offset = q.offset\n it = filter(it, () => i++ >= offset)\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n queryKeys (q: KeyQuery, options?: AbortOptions): AwaitIterable {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n const prefix = q.prefix\n it = filter(it, (key) =>\n key.toString().startsWith(prefix)\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n if (q.offset != null) {\n const offset = q.offset\n let i = 0\n it = filter(it, () => i++ >= offset)\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n","import { Key } from 'interface-datastore/key'\nimport { BaseDatastore } from './base.js'\nimport * as Errors from './errors.js'\nimport type { Pair } from 'interface-datastore'\nimport type { Await, AwaitIterable } from 'interface-store'\n\nexport class MemoryDatastore extends BaseDatastore {\n private readonly data: Map\n\n constructor () {\n super()\n\n this.data = new Map()\n }\n\n put (key: Key, val: Uint8Array): Await { // eslint-disable-line require-await\n this.data.set(key.toString(), val)\n\n return key\n }\n\n get (key: Key): Await {\n const result = this.data.get(key.toString())\n\n if (result == null) {\n throw Errors.notFoundError()\n }\n\n return result\n }\n\n has (key: Key): Await { // eslint-disable-line require-await\n return this.data.has(key.toString())\n }\n\n delete (key: Key): Await { // eslint-disable-line require-await\n this.data.delete(key.toString())\n }\n\n * _all (): AwaitIterable {\n for (const [key, value] of this.data.entries()) {\n yield { key: new Key(key), value }\n }\n }\n\n * _allKeys (): AwaitIterable {\n for (const key of this.data.keys()) {\n yield new Key(key)\n }\n }\n}\n","import errCode from 'err-code'\n\nexport function dbOpenFailedError (err?: Error): Error {\n err = err ?? new Error('Cannot open database')\n return errCode(err, 'ERR_DB_OPEN_FAILED')\n}\n\nexport function dbDeleteFailedError (err?: Error): Error {\n err = err ?? new Error('Delete failed')\n return errCode(err, 'ERR_DB_DELETE_FAILED')\n}\n\nexport function dbWriteFailedError (err?: Error): Error {\n err = err ?? new Error('Write failed')\n return errCode(err, 'ERR_DB_WRITE_FAILED')\n}\n\nexport function dbReadFailedError (err?: Error): Error {\n err = err ?? new Error('Read failed')\n return errCode(err, 'ERR_DB_READ_FAILED')\n}\n\nexport function notFoundError (err?: Error): Error {\n err = err ?? new Error('Not Found')\n return errCode(err, 'ERR_NOT_FOUND')\n}\n\nexport function abortedError (err?: Error): Error {\n err = err ?? new Error('Aborted')\n return errCode(err, 'ERR_ABORTED')\n}\n","import { peerIdFromString } from '@libp2p/peer-id'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { debounce } from './utils.js'\nimport type { ComponentLogger, Libp2pEvents, Logger, TypedEventTarget, PeerId, PeerStore } from '@libp2p/interface'\nimport type { TransportManager } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface AddressManagerInit {\n /**\n * Pass an function in this field to override the list of addresses\n * that are announced to the network\n */\n announceFilter?: AddressFilter\n\n /**\n * list of multiaddrs string representation to listen\n */\n listen?: string[]\n\n /**\n * list of multiaddrs string representation to announce\n */\n announce?: string[]\n\n /**\n * list of multiaddrs string representation to never announce\n */\n noAnnounce?: string[]\n}\n\nexport interface DefaultAddressManagerComponents {\n peerId: PeerId\n transportManager: TransportManager\n peerStore: PeerStore\n events: TypedEventTarget\n logger: ComponentLogger\n}\n\n/**\n * A function that takes a list of multiaddrs and returns a list\n * to announce\n */\nexport interface AddressFilter {\n (addrs: Multiaddr[]): Multiaddr[]\n}\n\nconst defaultAddressFilter = (addrs: Multiaddr[]): Multiaddr[] => addrs\n\ninterface ObservedAddressMetadata {\n confident: boolean\n}\n\n/**\n * If the passed multiaddr contains the passed peer id, remove it\n */\nfunction stripPeerId (ma: Multiaddr, peerId: PeerId): Multiaddr {\n const observedPeerIdStr = ma.getPeerId()\n\n // strip our peer id if it has been passed\n if (observedPeerIdStr != null) {\n const observedPeerId = peerIdFromString(observedPeerIdStr)\n\n // use same encoding for comparison\n if (observedPeerId.equals(peerId)) {\n ma = ma.decapsulate(multiaddr(`/p2p/${peerId.toString()}`))\n }\n }\n\n return ma\n}\n\nexport class DefaultAddressManager {\n private readonly log: Logger\n private readonly components: DefaultAddressManagerComponents\n // this is an array to allow for duplicates, e.g. multiples of `/ip4/0.0.0.0/tcp/0`\n private readonly listen: string[]\n private readonly announce: Set\n private readonly observed: Map\n private readonly announceFilter: AddressFilter\n\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor (components: DefaultAddressManagerComponents, init: AddressManagerInit = {}) {\n const { listen = [], announce = [] } = init\n\n this.components = components\n this.log = components.logger.forComponent('libp2p:address-manager')\n this.listen = listen.map(ma => ma.toString())\n this.announce = new Set(announce.map(ma => ma.toString()))\n this.observed = new Map()\n this.announceFilter = init.announceFilter ?? defaultAddressFilter\n\n // this method gets called repeatedly on startup when transports start listening so\n // debounce it so we don't cause multiple self:peer:update events to be emitted\n this._updatePeerStoreAddresses = debounce(this._updatePeerStoreAddresses.bind(this), 1000)\n\n // update our stored addresses when new transports listen\n components.events.addEventListener('transport:listening', () => {\n this._updatePeerStoreAddresses()\n })\n // update our stored addresses when existing transports stop listening\n components.events.addEventListener('transport:close', () => {\n this._updatePeerStoreAddresses()\n })\n }\n\n _updatePeerStoreAddresses (): void {\n // if announce addresses have been configured, ensure they make it into our peer\n // record for things like identify\n const addrs = this.getAnnounceAddrs()\n .concat(this.components.transportManager.getAddrs())\n .concat(\n [...this.observed.entries()]\n .filter(([_, metadata]) => metadata.confident)\n .map(([str]) => multiaddr(str))\n ).map(ma => {\n // strip our peer id if it is present\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma.decapsulate(`/p2p/${this.components.peerId.toString()}`)\n }\n\n return ma\n })\n\n this.components.peerStore.patch(this.components.peerId, {\n multiaddrs: addrs\n })\n .catch(err => { this.log.error('error updating addresses', err) })\n }\n\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs (): Multiaddr[] {\n return Array.from(this.listen).map((a) => multiaddr(a))\n }\n\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs (): Multiaddr[] {\n return Array.from(this.announce).map((a) => multiaddr(a))\n }\n\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs (): Multiaddr[] {\n return Array.from(this.observed).map(([a]) => multiaddr(a))\n }\n\n /**\n * Add peer observed addresses\n */\n addObservedAddr (addr: Multiaddr): void {\n addr = stripPeerId(addr, this.components.peerId)\n const addrString = addr.toString()\n\n // do not trigger the change:addresses event if we already know about this address\n if (this.observed.has(addrString)) {\n return\n }\n\n this.observed.set(addrString, {\n confident: false\n })\n }\n\n confirmObservedAddr (addr: Multiaddr): void {\n addr = stripPeerId(addr, this.components.peerId)\n const addrString = addr.toString()\n\n const metadata = this.observed.get(addrString) ?? {\n confident: false\n }\n\n const startingConfidence = metadata.confident\n\n this.observed.set(addrString, {\n confident: true\n })\n\n // only trigger the 'self:peer:update' event if our confidence in an address has changed\n if (!startingConfidence) {\n this._updatePeerStoreAddresses()\n }\n }\n\n removeObservedAddr (addr: Multiaddr): void {\n addr = stripPeerId(addr, this.components.peerId)\n const addrString = addr.toString()\n\n this.observed.delete(addrString)\n }\n\n getAddresses (): Multiaddr[] {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString())\n\n if (addrs.length === 0) {\n // no configured announce addrs, add configured listen addresses\n addrs = this.components.transportManager.getAddrs().map(ma => ma.toString())\n }\n\n // add observed addresses we are confident in\n addrs = addrs.concat(\n Array.from(this.observed)\n .filter(([ma, metadata]) => metadata.confident)\n .map(([ma]) => ma)\n )\n\n // dedupe multiaddrs\n const addrSet = new Set(addrs)\n\n // Create advertising list\n return this.announceFilter(Array.from(addrSet)\n .map(str => multiaddr(str)))\n .map(ma => {\n // do not append our peer id to a path multiaddr as it will become invalid\n if (ma.protos().pop()?.path === true) {\n return ma\n }\n\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${this.components.peerId.toString()}`)\n })\n }\n}\n","export function debounce (func: () => void, wait: number): () => void {\n let timeout: ReturnType | undefined\n\n return function () {\n const later = function (): void {\n timeout = undefined\n func()\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n}\n","/**\n * Implemented by components that have a lifecycle\n */\nexport interface Startable {\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?(): void | Promise\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start(): void | Promise\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?(): void | Promise\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?(): void | Promise\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop(): void | Promise\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?(): void | Promise\n}\n\nexport function isStartable (obj: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\nexport async function start (...objs: any[]): Promise {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\nexport async function stop (...objs: any[]): Promise {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n","import { CodeError } from '@libp2p/interface'\nimport { isStartable, type Startable, type Libp2pEvents, type ComponentLogger, type NodeInfo, type ConnectionProtector, type ConnectionGater, type ContentRouting, type TypedEventTarget, type Metrics, type PeerId, type PeerRouting, type PeerStore, type PrivateKey, type Upgrader } from '@libp2p/interface'\nimport { defaultLogger } from '@libp2p/logger'\nimport type { AddressManager, ConnectionManager, Registrar, TransportManager } from '@libp2p/interface-internal'\nimport type { DNS } from '@multiformats/dns'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface Components extends Record, Startable {\n peerId: PeerId\n privateKey: PrivateKey\n nodeInfo: NodeInfo\n logger: ComponentLogger\n events: TypedEventTarget\n addressManager: AddressManager\n peerStore: PeerStore\n upgrader: Upgrader\n registrar: Registrar\n connectionManager: ConnectionManager\n transportManager: TransportManager\n connectionGater: ConnectionGater\n contentRouting: ContentRouting\n peerRouting: PeerRouting\n datastore: Datastore\n connectionProtector?: ConnectionProtector\n metrics?: Metrics\n dns?: DNS\n}\n\nexport interface ComponentsInit {\n peerId?: PeerId\n privateKey?: PrivateKey\n nodeInfo?: NodeInfo\n logger?: ComponentLogger\n events?: TypedEventTarget\n addressManager?: AddressManager\n peerStore?: PeerStore\n upgrader?: Upgrader\n metrics?: Metrics\n registrar?: Registrar\n connectionManager?: ConnectionManager\n transportManager?: TransportManager\n connectionGater?: ConnectionGater\n contentRouting?: ContentRouting\n peerRouting?: PeerRouting\n datastore?: Datastore\n connectionProtector?: ConnectionProtector\n dns?: DNS\n}\n\nclass DefaultComponents implements Startable {\n public components: Record = {}\n private _started = false\n\n constructor (init: ComponentsInit = {}) {\n this.components = {}\n\n for (const [key, value] of Object.entries(init)) {\n this.components[key] = value\n }\n\n if (this.components.logger == null) {\n this.components.logger = defaultLogger()\n }\n }\n\n isStarted (): boolean {\n return this._started\n }\n\n private async _invokeStartableMethod (methodName: 'beforeStart' | 'start' | 'afterStart' | 'beforeStop' | 'stop' | 'afterStop'): Promise {\n await Promise.all(\n Object.values(this.components)\n .filter(obj => isStartable(obj))\n .map(async (startable: Startable) => {\n await startable[methodName]?.()\n })\n )\n }\n\n async beforeStart (): Promise {\n await this._invokeStartableMethod('beforeStart')\n }\n\n async start (): Promise {\n await this._invokeStartableMethod('start')\n this._started = true\n }\n\n async afterStart (): Promise {\n await this._invokeStartableMethod('afterStart')\n }\n\n async beforeStop (): Promise {\n await this._invokeStartableMethod('beforeStop')\n }\n\n async stop (): Promise {\n await this._invokeStartableMethod('stop')\n this._started = false\n }\n\n async afterStop (): Promise {\n await this._invokeStartableMethod('afterStop')\n }\n}\n\nconst OPTIONAL_SERVICES = [\n 'metrics',\n 'connectionProtector',\n 'dns'\n]\n\nconst NON_SERVICE_PROPERTIES = [\n 'components',\n 'isStarted',\n 'beforeStart',\n 'start',\n 'afterStart',\n 'beforeStop',\n 'stop',\n 'afterStop',\n 'then',\n '_invokeStartableMethod'\n]\n\nexport function defaultComponents (init: ComponentsInit = {}): Components {\n const components = new DefaultComponents(init)\n\n const proxy = new Proxy(components, {\n get (target, prop, receiver) {\n if (typeof prop === 'string' && !NON_SERVICE_PROPERTIES.includes(prop)) {\n const service = components.components[prop]\n\n if (service == null && !OPTIONAL_SERVICES.includes(prop)) {\n throw new CodeError(`${prop} not set`, 'ERR_SERVICE_MISSING')\n }\n\n return service\n }\n\n return Reflect.get(target, prop, receiver)\n },\n\n set (target, prop, value) {\n if (typeof prop === 'string') {\n components.components[prop] = value\n } else {\n Reflect.set(target, prop, value)\n }\n\n return true\n }\n })\n\n // @ts-expect-error component keys are proxied\n return proxy\n}\n","import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { Netmask } from 'netmask'\n\nconst PRIVATE_IP_RANGES = [\n '0.0.0.0/8',\n '10.0.0.0/8',\n '100.64.0.0/10',\n '127.0.0.0/8',\n '169.254.0.0/16',\n '172.16.0.0/12',\n '192.0.0.0/24',\n '192.0.0.0/29',\n '192.0.0.8/32',\n '192.0.0.9/32',\n '192.0.0.10/32',\n '192.0.0.170/32',\n '192.0.0.171/32',\n '192.0.2.0/24',\n '192.31.196.0/24',\n '192.52.193.0/24',\n '192.88.99.0/24',\n '192.168.0.0/16',\n '192.175.48.0/24',\n '198.18.0.0/15',\n '198.51.100.0/24',\n '203.0.113.0/24',\n '240.0.0.0/4',\n '255.255.255.255/32'\n]\n\nconst NETMASK_RANGES = PRIVATE_IP_RANGES.map(ipRange => new Netmask(ipRange))\n\nfunction ipv4Check (ipAddr: string): boolean {\n for (const r of NETMASK_RANGES) {\n if (r.contains(ipAddr)) return true\n }\n\n return false\n}\n\nfunction ipv6Check (ipAddr: string): boolean {\n return /^::$/.test(ipAddr) ||\n /^::1$/.test(ipAddr) ||\n /^::f{4}:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^::f{4}:0.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ipAddr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ipAddr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ipAddr)\n}\n\nexport function isPrivateIp (ip: string): boolean | undefined {\n if (isIPv4(ip)) return ipv4Check(ip)\n else if (isIPv6(ip)) return ipv6Check(ip)\n else return undefined\n}\n","import { isPrivateIp } from '@libp2p/utils/private-ip'\nimport type { ConnectionGater } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Returns a connection gater that disallows dialling private addresses by\n * default. Browsers are severely limited in their resource usage so don't\n * waste time trying to dial undiallable addresses.\n */\nexport function connectionGater (gater: ConnectionGater = {}): ConnectionGater {\n return {\n denyDialPeer: async () => false,\n denyDialMultiaddr: async (multiaddr: Multiaddr) => {\n const tuples = multiaddr.stringTuples()\n\n if (tuples[0][0] === 4 || tuples[0][0] === 41) {\n return Boolean(isPrivateIp(`${tuples[0][1]}`))\n }\n\n return false\n },\n denyInboundConnection: async () => false,\n denyOutboundConnection: async () => false,\n denyInboundEncryptedConnection: async () => false,\n denyOutboundEncryptedConnection: async () => false,\n denyInboundUpgradedConnection: async () => false,\n denyOutboundUpgradedConnection: async () => false,\n filterMultiaddrForPeer: async () => true,\n ...gater\n }\n}\n","import { isPrivateIp } from '../private-ip.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Check if a given multiaddr has a private address.\n */\nexport function isPrivate (ma: Multiaddr): boolean {\n try {\n const { address } = ma.nodeAddress()\n\n return Boolean(isPrivateIp(address))\n } catch {\n return true\n }\n}\n","/**\n * @packageDocumentation\n *\n * Provides strategies to sort a list of multiaddrs.\n *\n * @example\n *\n * ```typescript\n * import { publicAddressesFirst } from '@libp2p/utils/address-sort'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n *\n * const addresses = [\n * multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * multiaddr('/ip4/82.41.53.1/tcp/9000')\n * ].sort(publicAddressesFirst)\n *\n * console.info(addresses)\n * // ['/ip4/82.41.53.1/tcp/9000', '/ip4/127.0.0.1/tcp/9000']\n * ```\n */\n\nimport { Circuit } from '@multiformats/multiaddr-matcher'\nimport { isPrivate } from './multiaddr/is-private.js'\nimport type { Address } from '@libp2p/interface'\n\n/**\n * Compare function for array.sort() that moves public addresses to the start\n * of the array.\n */\nexport function publicAddressesFirst (a: Address, b: Address): -1 | 0 | 1 {\n const isAPrivate = isPrivate(a.multiaddr)\n const isBPrivate = isPrivate(b.multiaddr)\n\n if (isAPrivate && !isBPrivate) {\n return 1\n } else if (!isAPrivate && isBPrivate) {\n return -1\n }\n\n return 0\n}\n\n/**\n * Compare function for array.sort() that moves certified addresses to the start\n * of the array.\n */\nexport function certifiedAddressesFirst (a: Address, b: Address): -1 | 0 | 1 {\n if (a.isCertified && !b.isCertified) {\n return -1\n } else if (!a.isCertified && b.isCertified) {\n return 1\n }\n\n return 0\n}\n\n/**\n * Compare function for array.sort() that moves circuit relay addresses to the\n * start of the array.\n */\nexport function circuitRelayAddressesLast (a: Address, b: Address): -1 | 0 | 1 {\n const isACircuit = Circuit.exactMatch(a.multiaddr)\n const isBCircuit = Circuit.exactMatch(b.multiaddr)\n\n if (isACircuit && !isBCircuit) {\n return 1\n } else if (!isACircuit && isBCircuit) {\n return -1\n }\n\n return 0\n}\n\nexport function defaultAddressSort (a: Address, b: Address): -1 | 0 | 1 {\n const publicResult = publicAddressesFirst(a, b)\n\n if (publicResult !== 0) {\n return publicResult\n }\n\n const relayResult = circuitRelayAddressesLast(a, b)\n\n if (relayResult !== 0) {\n return relayResult\n }\n\n const certifiedResult = certifiedAddressesFirst(a, b)\n\n return certifiedResult\n}\n","\n/**\n * Progress events are emitted during long running operations\n */\nexport interface ProgressEvent {\n /**\n * The event type\n */\n type: T\n\n /**\n * Context-specific event information\n */\n detail: D\n}\n\n/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent extends Event implements ProgressEvent {\n // @ts-expect-error type is a property of Event, we just declare it here for use as a type disambiguator\n public type: T\n public detail: D\n\n constructor (type: T, detail?: any) {\n super(type)\n\n this.detail = detail\n }\n}\n\n/**\n * Define an `onProgress` callback that can be invoked with `ProgressEvent`s\n *\n * @example\n *\n * ```typescript\n * type MyOperationProgressEvents =\n * ProgressEvent<'operation:start'> |\n * ProgressEvent<'operation:success', Result> |\n * ProgressEvent<'operation:error', Error>\n *\n * export interface MyOperationOptions extends ProgressOptions {\n * // define options here\n * }\n * ```\n */\nexport interface ProgressOptions {\n onProgress?: (evt: Event) => void\n}\n","import { RecordType } from '../index.js'\n\nexport function getTypes (types?: RecordType | RecordType[]): RecordType[] {\n const DEFAULT_TYPES = [\n RecordType.A\n ]\n\n if (types == null) {\n return DEFAULT_TYPES\n }\n\n if (Array.isArray(types)) {\n if (types.length === 0) {\n return DEFAULT_TYPES\n }\n\n return types\n }\n\n return [\n types\n ]\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RecordType, type DNSResponse } from '../index.js'\n\n/**\n * This TTL will be used if the remote service does not return one\n */\nexport const DEFAULT_TTL = 60\n\nexport function toDNSResponse (obj: any): DNSResponse {\n return {\n Status: obj.Status ?? 0,\n TC: obj.TC ?? obj.flag_tc ?? false,\n RD: obj.RD ?? obj.flag_rd ?? false,\n RA: obj.RA ?? obj.flag_ra ?? false,\n AD: obj.AD ?? obj.flag_ad ?? false,\n CD: obj.CD ?? obj.flag_cd ?? false,\n Question: (obj.Question ?? obj.questions ?? []).map((question: any) => {\n return {\n name: question.name,\n type: RecordType[question.type]\n }\n }),\n Answer: (obj.Answer ?? obj.answers ?? []).map((answer: any) => {\n return {\n name: answer.name,\n type: RecordType[answer.type],\n TTL: (answer.TTL ?? answer.ttl ?? DEFAULT_TTL),\n data: answer.data instanceof Uint8Array ? uint8ArrayToString(answer.data) : answer.data\n }\n })\n }\n}\n","/* eslint-env browser */\n\nimport PQueue from 'p-queue'\nimport { CustomProgressEvent } from 'progress-events'\nimport { RecordType, type DNSResponse } from '../index.js'\nimport { getTypes } from '../utils/get-types.js'\nimport { toDNSResponse } from '../utils/to-dns-response.js'\nimport type { DNSResolver } from './index.js'\n\n/**\n * Browsers limit concurrent connections per host (~6), we don't want to exhaust\n * the limit so this value controls how many DNS queries can be in flight at\n * once.\n */\nexport const DEFAULT_QUERY_CONCURRENCY = 4\n\nexport interface DNSJSONOverHTTPSOptions {\n queryConcurrency?: number\n}\n\n/**\n * Uses the RFC 8427 'application/dns-json' content-type to resolve DNS queries.\n *\n * Supports and server that uses the same schema as Google's DNS over HTTPS\n * resolver.\n *\n * This resolver needs fewer dependencies than the regular DNS-over-HTTPS\n * resolver so can result in a smaller bundle size and consequently is preferred\n * for browser use.\n *\n * @see https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/\n * @see https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers\n * @see https://dnsprivacy.org/public_resolvers/\n * @see https://datatracker.ietf.org/doc/html/rfc8427\n */\nexport function dnsJsonOverHttps (url: string, init: DNSJSONOverHTTPSOptions = {}): DNSResolver {\n const httpQueue = new PQueue({\n concurrency: init.queryConcurrency ?? DEFAULT_QUERY_CONCURRENCY\n })\n\n return async (fqdn, options = {}) => {\n const searchParams = new URLSearchParams()\n searchParams.set('name', fqdn)\n\n getTypes(options.types).forEach(type => {\n // We pass record type as a string to the server because cloudflare DNS bug. see https://github.com/ipfs/helia/issues/474\n searchParams.append('type', RecordType[type])\n })\n\n options.onProgress?.(new CustomProgressEvent('dns:query', { detail: fqdn }))\n\n // query DNS-JSON over HTTPS server\n const response = await httpQueue.add(async () => {\n const res = await fetch(`${url}?${searchParams}`, {\n headers: {\n accept: 'application/dns-json'\n },\n signal: options?.signal\n })\n\n if (res.status !== 200) {\n throw new Error(`Unexpected HTTP status: ${res.status} - ${res.statusText}`)\n }\n\n const response = toDNSResponse(await res.json())\n\n options.onProgress?.(new CustomProgressEvent('dns:response', { detail: response }))\n\n return response\n }, {\n signal: options.signal\n })\n\n if (response == null) {\n throw new Error('No DNS response received')\n }\n\n return response\n }\n}\n","import hashlru from 'hashlru'\nimport { RecordType } from '../index.js'\nimport { DEFAULT_TTL, toDNSResponse } from './to-dns-response.js'\nimport type { Answer, DNSResponse } from '../index.js'\n\ninterface CachedAnswer {\n expires: number\n value: Answer\n}\n\nexport interface AnswerCache {\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined\n add (domain: string, answer: Answer): void\n remove (domain: string, type: ResponseType): void\n clear (): void\n}\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n */\nclass CachedAnswers {\n private readonly lru: ReturnType\n\n constructor (maxSize: number) {\n this.lru = hashlru(maxSize)\n }\n\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined {\n let foundAllAnswers = true\n const answers: Answer[] = []\n\n for (const type of types) {\n const cached = this.getAnswers(fqdn, type)\n\n if (cached.length === 0) {\n foundAllAnswers = false\n break\n }\n\n answers.push(...cached)\n }\n\n if (foundAllAnswers) {\n return toDNSResponse({ answers })\n }\n }\n\n private getAnswers (domain: string, type: RecordType): Answer[] {\n const key = `${domain.toLowerCase()}-${type}`\n const answers: CachedAnswer[] = this.lru.get(key)\n\n if (answers != null) {\n const cachedAnswers = answers\n .filter((entry) => {\n return entry.expires > Date.now()\n })\n .map(({ expires, value }) => ({\n ...value,\n TTL: Math.round((expires - Date.now()) / 1000),\n type: RecordType[value.type]\n }))\n\n if (cachedAnswers.length === 0) {\n this.lru.remove(key)\n }\n\n // @ts-expect-error hashlru stringifies stored types which turns enums\n // into strings, we convert back into enums above but tsc doesn't know\n return cachedAnswers\n }\n\n return []\n }\n\n add (domain: string, answer: Answer): void {\n const key = `${domain.toLowerCase()}-${answer.type}`\n\n const answers: CachedAnswer[] = this.lru.get(key) ?? []\n answers.push({\n expires: Date.now() + ((answer.TTL ?? DEFAULT_TTL) * 1000),\n value: answer\n })\n\n this.lru.set(key, answers)\n }\n\n remove (domain: string, type: ResponseType): void {\n const key = `${domain.toLowerCase()}-${type}`\n\n this.lru.remove(key)\n }\n\n clear (): void {\n this.lru.clear()\n }\n}\n\n/**\n * Avoid sending multiple queries for the same hostname by caching results\n */\nexport function cache (size: number): AnswerCache {\n return new CachedAnswers(size)\n}\n","import { CustomProgressEvent } from 'progress-events'\nimport { defaultResolver } from './resolvers/default.js'\nimport { cache } from './utils/cache.js'\nimport { getTypes } from './utils/get-types.js'\nimport type { DNS as DNSInterface, DNSInit, DNSResponse, QueryOptions } from './index.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { AnswerCache } from './utils/cache.js'\n\nconst DEFAULT_ANSWER_CACHE_SIZE = 1000\n\nexport class DNS implements DNSInterface {\n private readonly resolvers: Record\n private readonly cache: AnswerCache\n\n constructor (init: DNSInit) {\n this.resolvers = {}\n this.cache = cache(init.cacheSize ?? DEFAULT_ANSWER_CACHE_SIZE)\n\n Object.entries(init.resolvers ?? {}).forEach(([tld, resolver]) => {\n if (!Array.isArray(resolver)) {\n resolver = [resolver]\n }\n\n // convert `com` -> `com.`\n if (!tld.endsWith('.')) {\n tld = `${tld}.`\n }\n\n this.resolvers[tld] = resolver\n })\n\n // configure default resolver if none specified\n if (this.resolvers['.'] == null) {\n this.resolvers['.'] = defaultResolver()\n }\n }\n\n /**\n * Queries DNS resolvers for the passed record types for the passed domain.\n *\n * If cached records exist for all desired types they will be returned\n * instead.\n *\n * Any new responses will be added to the cache for subsequent requests.\n */\n async query (domain: string, options: QueryOptions = {}): Promise {\n const types = getTypes(options.types)\n const cached = options.cached !== false ? this.cache.get(domain, types) : undefined\n\n if (cached != null) {\n options.onProgress?.(new CustomProgressEvent('dns:cache', { detail: cached }))\n\n return cached\n }\n\n const tld = `${domain.split('.').pop()}.`\n const resolvers = (this.resolvers[tld] ?? this.resolvers['.']).sort(() => {\n return (Math.random() > 0.5) ? -1 : 1\n })\n\n const errors: Error[] = []\n\n for (const resolver of resolvers) {\n // skip further resolutions if the user aborted the signal\n if (options.signal?.aborted === true) {\n break\n }\n\n try {\n const result = await resolver(domain, {\n ...options,\n types\n })\n\n for (const answer of result.Answer) {\n this.cache.add(domain, answer)\n }\n\n return result\n } catch (err: any) {\n errors.push(err)\n options.onProgress?.(new CustomProgressEvent('dns:error', { detail: err }))\n }\n }\n\n if (errors.length === 1) {\n throw errors[0]\n }\n\n throw new AggregateError(errors, `DNS lookup of ${domain} ${types} failed`)\n }\n}\n","import { dnsJsonOverHttps } from './dns-json-over-https.js'\nimport type { DNSResolver } from './index.js'\n\nexport function defaultResolver (): DNSResolver[] {\n return [\n dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n dnsJsonOverHttps('https://dns.google/resolve')\n ]\n}\n","/**\n * @packageDocumentation\n *\n * Query DNS records using `node:dns`, DNS over HTTP and/or DNSJSON over HTTP.\n *\n * A list of publicly accessible servers can be found [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers).\n *\n * @example Using the default resolver\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve A records with a 5s timeout\n * const result = await dns.query('google.com', {\n * signal: AbortSignal.timeout(5000)\n * })\n * ```\n *\n * @example Using per-TLD resolvers\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * // will only be used to resolve `.com` addresses\n * 'com.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n *\n * // this can also be an array, resolvers will be shuffled and tried in\n * // series\n * 'net.': [\n * dnsJsonOverHttps('https://dns.google/resolve'),\n * dnsJsonOverHttps('https://dns.pub/dns-query')\n * ],\n *\n * // will only be used to resolve all other addresses\n * '.': dnsJsonOverHttps('https://dnsforge.de/dns-query'),\n * }\n * })\n * ```\n *\n * @example Query for specific record types\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve only TXT records\n * const result = await dns.query('google.com', {\n * types: [\n * RecordType.TXT\n * ]\n * })\n * ```\n *\n * ## Caching\n *\n * Individual Aanswers are cached so. If you make a request, for which all\n * record types are cached, all values will be pulled from the cache.\n *\n * If any of the record types are not cached, a new request will be resolved as\n * if none of the records were cached, and the cache will be updated to include\n * the new results.\n *\n * @example Ignoring the cache\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // do not used cached results, always resolve a new query\n * const result = await dns.query('google.com', {\n * cached: false\n * })\n * ```\n */\n\nimport { DNS as DNSClass } from './dns.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\n/**\n * A subset of DNS Record Types\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\nexport enum RecordType {\n A = 1,\n CNAME = 5,\n TXT = 16,\n AAAA = 28\n}\n\nexport interface Question {\n /**\n * The record name requested.\n */\n name: string\n\n /**\n * The type of DNS record requested.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\n type: RecordType\n}\n\nexport interface Answer {\n /**\n * The record owner.\n */\n name: string\n\n /**\n * The type of DNS record.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4\n */\n type: RecordType\n\n /**\n * The number of seconds the answer can be stored in cache before it is\n * considered stale.\n */\n TTL: number\n\n /**\n * The value of the DNS record for the given name and type. The data will be\n * in text for standardized record types and in hex for unknown types.\n */\n data: string\n}\n\nexport interface DNSResponse {\n /**\n * The Response Code of the DNS Query.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n */\n Status: number\n\n /**\n * If true, it means the truncated bit was set. This happens when the DNS\n * answer is larger than a single UDP or TCP packet.\n */\n TC: boolean\n\n /**\n * If true, it means the Recursive Desired bit was set.\n */\n RD: boolean\n\n /**\n * If true, it means the Recursion Available bit was set.\n */\n RA: boolean\n\n /**\n * If true, it means that every record in the answer was verified with DNSSEC.\n */\n AD: boolean\n\n /**\n * If true, the client asked to disable DNSSEC validation.\n */\n CD: boolean\n\n /**\n * The records that were requested.\n */\n Question: Question[]\n\n /**\n * Values for the records that were requested.\n */\n Answer: Answer[]\n}\n\n/**\n * The default maximum amount of recursion allowed during a query\n */\nexport const MAX_RECURSIVE_DEPTH = 32\n\nexport interface QueryOptions extends ProgressOptions {\n signal?: AbortSignal\n\n /**\n * Do not use cached DNS entries\n *\n * @default false\n */\n cached?: boolean\n\n /**\n * The type or types of DNS records to resolve\n *\n * @default [RecordType.A, RecordType.AAAA]\n */\n types?: RecordType | RecordType[]\n}\n\nexport interface DNS {\n query(fqdn: string, options?: QueryOptions): Promise\n}\n\nexport type ResolveDnsProgressEvents =\n ProgressEvent<'dns:cache', string> |\n ProgressEvent<'dns:query', string> |\n ProgressEvent<'dns:response', DNSResponse> |\n ProgressEvent<'dns:error', Error>\n\nexport type DNSResolvers = Record\n\nexport interface DNSInit {\n /**\n * A set of resolvers used to answer DNS queries\n *\n * String keys control which resolvers are used for which TLDs.\n *\n * @example\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns'\n *\n * const resolver = dns({\n * resolvers: {\n * // only used for .com domains\n * 'com.': dnsOverHttps('https://example-1.com'),\n *\n * // only used for .net domains, can be an array\n * 'net.': [\n * dnsOverHttps('https://example-2.com'),\n * dnsOverHttps('https://example-3.com'),\n * ],\n *\n * // used for everything else (can be an array)\n * '.': dnsOverHttps('https://example-4.com')\n * }\n * })\n * ```\n */\n resolvers?: DNSResolvers\n\n /**\n * To avoid repeating DNS lookups, successful answers are cached according to\n * their TTL. To avoid exhausting memory, this option controls how many\n * answers to cache.\n *\n * @default 1000\n */\n cacheSize?: number\n}\n\nexport function dns (init: DNSInit = {}): DNS {\n return new DNSClass(init)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { dns, RecordType } from '@multiformats/dns'\nimport { multiaddr } from '../index.js'\nimport { getProtocol } from '../protocols-table.js'\nimport type { Resolver } from './index.js'\nimport type { AbortOptions, Multiaddr } from '../index.js'\nimport type { DNS } from '@multiformats/dns'\n\nconst MAX_RECURSIVE_DEPTH = 32\nconst { code: dnsaddrCode } = getProtocol('dnsaddr')\n\nexport interface DNSADDROptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport const dnsaddrResolver: Resolver = async function dnsaddrResolver (ma: Multiaddr, options: DNSADDROptions = {}): Promise {\n const recursionLimit = options.maxRecursiveDepth ?? MAX_RECURSIVE_DEPTH\n\n if (recursionLimit === 0) {\n throw new CodeError('Max recursive depth reached', 'ERR_MAX_RECURSIVE_DEPTH_REACHED')\n }\n\n const [, hostname] = ma.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? []\n\n const resolver = options?.dns ?? dns()\n const result = await resolver.query(`_dnsaddr.${hostname}`, {\n signal: options?.signal,\n types: [\n RecordType.TXT\n ]\n })\n\n const peerId = ma.getPeerId()\n const output: string[] = []\n\n for (const answer of result.Answer) {\n const addr = answer.data.split('=')[1]\n\n if (addr == null) {\n continue\n }\n\n if (peerId != null && !addr.includes(peerId)) {\n continue\n }\n\n const ma = multiaddr(addr)\n\n if (addr.startsWith('/dnsaddr')) {\n const resolved = await ma.resolve({\n ...options,\n maxRecursiveDepth: recursionLimit - 1\n })\n\n output.push(...resolved.map(ma => ma.toString()))\n } else {\n output.push(ma.toString())\n }\n }\n\n return output\n}\n","/**\n * Thin ESM wrapper for CJS named exports.\n *\n * Ref: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1\n */\n\nimport mergeOptions from './index.js';\nexport default mergeOptions;\n","export enum messages {\n NOT_STARTED_YET = 'The libp2p node is not started yet',\n ERR_PROTECTOR_REQUIRED = 'Private network is enforced, but no protector was provided',\n NOT_FOUND = 'Not found'\n}\n\nexport enum codes {\n ERR_PROTECTOR_REQUIRED = 'ERR_PROTECTOR_REQUIRED',\n ERR_PEER_DIAL_INTERCEPTED = 'ERR_PEER_DIAL_INTERCEPTED',\n ERR_CONNECTION_INTERCEPTED = 'ERR_CONNECTION_INTERCEPTED',\n ERR_INVALID_PROTOCOLS_FOR_STREAM = 'ERR_INVALID_PROTOCOLS_FOR_STREAM',\n ERR_CONNECTION_ENDED = 'ERR_CONNECTION_ENDED',\n ERR_CONNECTION_FAILED = 'ERR_CONNECTION_FAILED',\n ERR_NODE_NOT_STARTED = 'ERR_NODE_NOT_STARTED',\n ERR_ALREADY_ABORTED = 'ERR_ALREADY_ABORTED',\n ERR_TOO_MANY_ADDRESSES = 'ERR_TOO_MANY_ADDRESSES',\n ERR_NO_VALID_ADDRESSES = 'ERR_NO_VALID_ADDRESSES',\n ERR_RELAYED_DIAL = 'ERR_RELAYED_DIAL',\n ERR_DIALED_SELF = 'ERR_DIALED_SELF',\n ERR_DISCOVERED_SELF = 'ERR_DISCOVERED_SELF',\n ERR_DUPLICATE_TRANSPORT = 'ERR_DUPLICATE_TRANSPORT',\n ERR_ENCRYPTION_FAILED = 'ERR_ENCRYPTION_FAILED',\n ERR_HOP_REQUEST_FAILED = 'ERR_HOP_REQUEST_FAILED',\n ERR_INVALID_KEY = 'ERR_INVALID_KEY',\n ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE',\n ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS',\n ERR_INVALID_PEER = 'ERR_INVALID_PEER',\n ERR_MUXER_UNAVAILABLE = 'ERR_MUXER_UNAVAILABLE',\n ERR_NOT_FOUND = 'ERR_NOT_FOUND',\n ERR_TRANSPORT_UNAVAILABLE = 'ERR_TRANSPORT_UNAVAILABLE',\n ERR_TRANSPORT_DIAL_FAILED = 'ERR_TRANSPORT_DIAL_FAILED',\n ERR_UNSUPPORTED_PROTOCOL = 'ERR_UNSUPPORTED_PROTOCOL',\n ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED = 'ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED',\n ERR_INVALID_MULTIADDR = 'ERR_INVALID_MULTIADDR',\n ERR_SIGNATURE_NOT_VALID = 'ERR_SIGNATURE_NOT_VALID',\n ERR_FIND_SELF = 'ERR_FIND_SELF',\n ERR_NO_ROUTERS_AVAILABLE = 'ERR_NO_ROUTERS_AVAILABLE',\n ERR_CONNECTION_NOT_MULTIPLEXED = 'ERR_CONNECTION_NOT_MULTIPLEXED',\n ERR_NO_DIAL_TOKENS = 'ERR_NO_DIAL_TOKENS',\n ERR_INVALID_CMS = 'ERR_INVALID_CMS',\n ERR_MISSING_KEYS = 'ERR_MISSING_KEYS',\n ERR_NO_KEY = 'ERR_NO_KEY',\n ERR_INVALID_KEY_NAME = 'ERR_INVALID_KEY_NAME',\n ERR_INVALID_KEY_TYPE = 'ERR_INVALID_KEY_TYPE',\n ERR_KEY_ALREADY_EXISTS = 'ERR_KEY_ALREADY_EXISTS',\n ERR_INVALID_KEY_SIZE = 'ERR_INVALID_KEY_SIZE',\n ERR_KEY_NOT_FOUND = 'ERR_KEY_NOT_FOUND',\n ERR_OLD_KEY_NAME_INVALID = 'ERR_OLD_KEY_NAME_INVALID',\n ERR_NEW_KEY_NAME_INVALID = 'ERR_NEW_KEY_NAME_INVALID',\n ERR_PASSWORD_REQUIRED = 'ERR_PASSWORD_REQUIRED',\n ERR_PEM_REQUIRED = 'ERR_PEM_REQUIRED',\n ERR_CANNOT_READ_KEY = 'ERR_CANNOT_READ_KEY',\n ERR_MISSING_PRIVATE_KEY = 'ERR_MISSING_PRIVATE_KEY',\n ERR_MISSING_PUBLIC_KEY = 'ERR_MISSING_PUBLIC_KEY',\n ERR_INVALID_OLD_PASS_TYPE = 'ERR_INVALID_OLD_PASS_TYPE',\n ERR_INVALID_NEW_PASS_TYPE = 'ERR_INVALID_NEW_PASS_TYPE',\n ERR_INVALID_PASS_LENGTH = 'ERR_INVALID_PASS_LENGTH',\n ERR_NOT_IMPLEMENTED = 'ERR_NOT_IMPLEMENTED',\n ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK',\n ERR_INVALID_RECORD = 'ERR_INVALID_RECORD',\n ERR_ALREADY_SUCCEEDED = 'ERR_ALREADY_SUCCEEDED',\n ERR_NO_HANDLER_FOR_PROTOCOL = 'ERR_NO_HANDLER_FOR_PROTOCOL',\n ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS',\n ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS',\n ERR_CONNECTION_DENIED = 'ERR_CONNECTION_DENIED',\n ERR_TRANSFER_LIMIT_EXCEEDED = 'ERR_TRANSFER_LIMIT_EXCEEDED'\n}\n","import { CodeError, FaultTolerance } from '@libp2p/interface'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { defaultAddressSort } from '@libp2p/utils/address-sort'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport mergeOptions from 'merge-options'\nimport { codes, messages } from './errors.js'\nimport type { Libp2pInit } from './index.js'\nimport type { ServiceMap, RecursivePartial } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst DefaultConfig: Partial = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs: Multiaddr[]) => multiaddrs\n },\n connectionManager: {\n resolvers: {\n dnsaddr: dnsaddrResolver\n },\n addressSorter: defaultAddressSort\n },\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n }\n}\n\nexport async function validateConfig > (opts: RecursivePartial>): Promise> {\n const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts)\n\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw new CodeError(messages.ERR_PROTECTOR_REQUIRED, codes.ERR_PROTECTOR_REQUIRED)\n }\n\n if (!(await peerIdFromKeys(resultingOptions.privateKey.public.bytes, resultingOptions.privateKey.bytes)).equals(resultingOptions.peerId)) {\n throw new CodeError('Private key doesn\\'t match peer id', codes.ERR_INVALID_KEY)\n }\n\n return resultingOptions\n}\n","import { CodeError, isPeerId } from '@libp2p/interface'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { isMultiaddr } from '@multiformats/multiaddr'\nimport { codes } from './errors.js'\nimport type { PeerId } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface PeerAddress {\n peerId?: PeerId\n multiaddrs: Multiaddr[]\n}\n\n/**\n * Extracts a PeerId and/or multiaddr from the passed PeerId or Multiaddr or an array of Multiaddrs\n */\nexport function getPeerAddress (peer: PeerId | Multiaddr | Multiaddr[]): PeerAddress {\n if (isPeerId(peer)) {\n return { peerId: peer, multiaddrs: [] }\n }\n\n if (!Array.isArray(peer)) {\n peer = [peer]\n }\n\n let peerId: PeerId | undefined\n\n if (peer.length > 0) {\n const peerIdStr = peer[0].getPeerId()\n peerId = peerIdStr == null ? undefined : peerIdFromString(peerIdStr)\n\n // ensure PeerId is either not set or is consistent\n peer.forEach(ma => {\n if (!isMultiaddr(ma)) {\n throw new CodeError('Invalid Multiaddr', codes.ERR_INVALID_MULTIADDR)\n }\n\n const maPeerIdStr = ma.getPeerId()\n\n if (maPeerIdStr == null) {\n if (peerId != null) {\n throw new CodeError('Multiaddrs must all have the same peer id or have no peer id', codes.ERR_INVALID_PARAMETERS)\n }\n } else {\n const maPeerId = peerIdFromString(maPeerIdStr)\n\n if (peerId == null || !peerId.equals(maPeerId)) {\n throw new CodeError('Multiaddrs must all have the same peer id or have no peer id', codes.ERR_INVALID_PARAMETERS)\n }\n }\n })\n }\n\n return {\n peerId,\n multiaddrs: peer\n }\n}\n","/**\n * @packageDocumentation\n *\n * Race an event against an AbortSignal, taking care to remove any event\n * listeners that were added.\n *\n * @example Getting started\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * setTimeout(() => {\n * // too late\n * emitter.dispatchEvent(new CustomEvent('event'))\n * }, 1000)\n *\n * // throws an AbortError\n * const resolve = await raceEvent(emitter, 'event', controller.signal)\n * ```\n *\n * @example Customising the thrown AbortError\n *\n * The error message and `.code` property of the thrown `AbortError` can be\n * specified by passing options:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * errorMessage: 'Oh no!',\n * errorCode: 'ERR_OH_NO'\n * })\n * ```\n *\n * @example Only resolving on specific events\n *\n * Where multiple events with the same type are emitted, a `filter` function can\n * be passed to only resolve on one of them:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt: Event) => {\n * return evt.detail.foo === 'bar'\n * }\n * })\n * ```\n *\n * @example Terminating early by throwing from the filter\n *\n * You can cause listening for the event to cease and all event listeners to be\n * removed by throwing from the filter:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws Error: Cannot continue\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt) => {\n * if (...reasons) {\n * throw new Error('Cannot continue')\n * }\n *\n * return true\n * }\n * })\n * ```\n */\n\n/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n public type: string\n public code: string | string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.name = 'AbortError'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface RaceEventOptions {\n /**\n * The message for the error thrown if the signal aborts\n */\n errorMessage?: string\n\n /**\n * The code for the error thrown if the signal aborts\n */\n errorCode?: string\n\n /**\n * When multiple events with the same name may be emitted, pass a filter\n * function here to allow ignoring ones that should not cause the returned\n * promise to resolve.\n */\n filter?(evt: T): boolean\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceEvent (emitter: EventTarget, eventName: string, signal?: AbortSignal, opts?: RaceEventOptions): Promise {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode)\n\n if (signal?.aborted === true) {\n return Promise.reject(error)\n }\n\n return new Promise((resolve, reject) => {\n const eventListener = (evt: any): void => {\n try {\n if (opts?.filter?.(evt) === false) {\n return\n }\n } catch (err: any) {\n emitter.removeEventListener(eventName, eventListener)\n signal?.removeEventListener('abort', abortListener)\n\n reject(err)\n return\n }\n\n emitter.removeEventListener(eventName, eventListener)\n signal?.removeEventListener('abort', abortListener)\n\n resolve(evt)\n }\n const abortListener = (): void => {\n emitter.removeEventListener(eventName, eventListener)\n signal?.removeEventListener('abort', abortListener)\n\n reject(error)\n }\n\n emitter.addEventListener(eventName, eventListener)\n signal?.addEventListener('abort', abortListener)\n })\n}\n","import { AbortError } from '@libp2p/interface'\nimport pDefer from 'p-defer'\nimport type { DeferredPromise } from 'p-defer'\n\nexport class JobRecipient {\n public deferred: DeferredPromise\n public signal?: AbortSignal\n public where?: string\n\n constructor (where?: string, signal?: AbortSignal) {\n this.signal = signal\n this.deferred = pDefer()\n this.where = where\n\n this.onAbort = this.onAbort.bind(this)\n this.signal?.addEventListener('abort', this.onAbort)\n }\n\n onAbort (): void {\n this.deferred.reject(new AbortError())\n }\n\n cleanup (): void {\n this.signal?.removeEventListener('abort', this.onAbort)\n }\n}\n","import { AbortError, setMaxListeners } from '@libp2p/interface'\nimport { raceSignal } from 'race-signal'\nimport { JobRecipient } from './recipient.js'\nimport type { JobStatus } from './index.js'\nimport type { AbortOptions } from '@libp2p/interface'\n\n/**\n * Returns a random string\n */\nfunction randomId (): string {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n}\n\nexport interface JobTimeline {\n created: number\n started?: number\n finished?: number\n}\n\nexport class Job {\n public id: string\n public fn: (options: JobOptions) => Promise\n public options: JobOptions\n public priority: number\n public recipients: Array>\n public status: JobStatus\n public readonly timeline: JobTimeline\n private readonly controller: AbortController\n\n constructor (fn: (options: JobOptions) => Promise, options: any, priority: number = 0) {\n this.id = randomId()\n this.status = 'queued'\n this.fn = fn\n this.priority = priority\n this.options = options\n this.recipients = []\n this.timeline = {\n created: Date.now()\n }\n\n this.controller = new AbortController()\n setMaxListeners(Infinity, this.controller.signal)\n\n this.onAbort = this.onAbort.bind(this)\n }\n\n abort (err: Error): void {\n this.controller.abort(err)\n }\n\n onAbort (): void {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true)\n }, true)\n\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError())\n }\n }\n\n async join (options: AbortOptions = {}): Promise {\n const recipient = new JobRecipient((new Error('where')).stack, options.signal)\n this.recipients.push(recipient)\n\n options.signal?.addEventListener('abort', this.onAbort)\n\n return recipient.deferred.promise\n }\n\n async run (): Promise {\n this.status = 'running'\n this.timeline.started = Date.now()\n\n try {\n this.controller.signal.throwIfAborted()\n\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal)\n\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result)\n })\n\n this.status = 'complete'\n } catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err)\n })\n\n this.status = 'errored'\n } finally {\n this.timeline.finished = Date.now()\n this.cleanup()\n }\n }\n\n cleanup (): void {\n this.recipients.forEach(recipient => {\n recipient.signal?.removeEventListener('abort', this.onAbort)\n })\n }\n}\n","import { AbortError, CodeError, TypedEventEmitter } from '@libp2p/interface'\nimport { pushable } from 'it-pushable'\nimport { raceEvent } from 'race-event'\nimport { Job } from './job.js'\nimport type { AbortOptions, Metrics } from '@libp2p/interface'\n\nexport interface QueueAddOptions extends AbortOptions {\n /**\n * Priority of operation. Operations with greater priority will be scheduled first.\n *\n * @default 0\n */\n priority?: number\n}\n\nexport interface QueueInit {\n /**\n * Concurrency limit.\n *\n * Minimum: `1`.\n *\n * @default Infinity\n */\n concurrency?: number\n\n /**\n * The name of the metric for the queue length\n */\n metricName?: string\n\n /**\n * An implementation of the libp2p Metrics interface\n */\n metrics?: Metrics\n}\n\nexport type JobStatus = 'queued' | 'running' | 'errored' | 'complete'\n\nexport interface RunFunction {\n (opts?: Options): Promise\n}\n\nexport interface JobMatcher {\n (options?: Partial): boolean\n}\n\nexport interface QueueEvents {\n 'active': CustomEvent\n 'idle': CustomEvent\n 'empty': CustomEvent\n 'add': CustomEvent\n 'next': CustomEvent\n 'completed': CustomEvent\n 'error': CustomEvent\n}\n\n// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nfunction lowerBound (array: readonly T[], value: T, comparator: (a: T, b: T) => number): number {\n let first = 0\n let count = array.length\n\n while (count > 0) {\n const step = Math.trunc(count / 2)\n let it = first + step\n\n if (comparator(array[it], value) <= 0) {\n first = ++it\n count -= step + 1\n } else {\n count = step\n }\n }\n\n return first\n}\n\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nexport class Queue extends TypedEventEmitter> {\n public concurrency: number\n public queue: Array>\n private pending: number\n\n constructor (init: QueueInit = {}) {\n super()\n\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY\n this.pending = 0\n\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n }\n }\n })\n }\n\n this.queue = []\n }\n\n private tryToStartAnother (): boolean {\n if (this.size === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"empty\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('empty')\n })\n\n if (this.running === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"idle\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('idle')\n })\n }\n\n return false\n }\n\n if (this.pending < this.concurrency) {\n let job: Job | undefined\n\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j\n break\n }\n }\n\n if (job == null) {\n return false\n }\n\n this.safeDispatchEvent('active')\n\n this.pending++\n\n job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n\n this.pending--\n this.tryToStartAnother()\n this.safeDispatchEvent('next')\n })\n\n return true\n }\n\n return false\n }\n\n private enqueue (job: Job): void {\n if (this.queue[this.size - 1]?.priority >= job.priority) {\n this.queue.push(job)\n return\n }\n\n const index = lowerBound(\n this.queue, job,\n (a: Readonly< Job>, b: Readonly< Job>) => b.priority - a.priority\n )\n this.queue.splice(index, 0, job)\n }\n\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add (fn: RunFunction, options?: JobOptions): Promise {\n options?.signal?.throwIfAborted()\n\n const job = new Job(fn, options, options?.priority)\n\n const p = job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result })\n\n return result\n })\n .catch(err => {\n this.safeDispatchEvent('error', { detail: err })\n\n throw err\n })\n\n this.enqueue(job)\n this.safeDispatchEvent('add')\n this.tryToStartAnother()\n\n return p\n }\n\n /**\n * Clear the queue\n */\n clear (): void {\n this.queue.splice(0, this.queue.length)\n }\n\n /**\n * Abort all jobs in the queue and clear it\n */\n abort (): void {\n this.queue.forEach(job => {\n job.abort(new AbortError())\n })\n\n this.clear()\n }\n\n /**\n * Can be called multiple times. Useful if you for example add additional items at a later time.\n *\n * @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty (options?: AbortOptions): Promise {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return\n }\n\n await raceEvent(this, 'empty', options?.signal)\n }\n\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan (limit: number, options?: AbortOptions): Promise {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return\n }\n\n await raceEvent(this, 'next', options?.signal, {\n filter: () => this.size < limit\n })\n }\n\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * empty, but it could mean that some promises haven't completed yet.\n *\n * @returns A promise that settles when the queue becomes empty, and all\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle (options?: AbortOptions): Promise {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return\n }\n\n await raceEvent(this, 'idle', options?.signal)\n }\n\n /**\n * Size of the queue including running items\n */\n get size (): number {\n return this.queue.length\n }\n\n /**\n * The number of queued items waiting to run.\n */\n get queued (): number {\n return this.queue.length - this.pending\n }\n\n /**\n * The number of items currently running.\n */\n get running (): number {\n return this.pending\n }\n\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async * toGenerator (options?: AbortOptions): AsyncGenerator {\n options?.signal?.throwIfAborted()\n\n const stream = pushable({\n objectMode: true\n })\n\n const cleanup = (err?: Error): void => {\n if (err != null) {\n this.abort()\n } else {\n this.clear()\n }\n\n stream.end(err)\n }\n\n const onQueueJobComplete = (evt: CustomEvent): void => {\n if (evt.detail != null) {\n stream.push(evt.detail)\n }\n }\n\n const onQueueError = (evt: CustomEvent): void => {\n cleanup(evt.detail)\n }\n\n const onQueueIdle = (): void => {\n cleanup()\n }\n\n // clear the queue and throw if the query is aborted\n const onSignalAbort = (): void => {\n cleanup(new CodeError('Queue aborted', 'ERR_QUEUE_ABORTED'))\n }\n\n // add listeners\n this.addEventListener('completed', onQueueJobComplete)\n this.addEventListener('error', onQueueError)\n this.addEventListener('idle', onQueueIdle)\n options?.signal?.addEventListener('abort', onSignalAbort)\n\n try {\n yield * stream\n } finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete)\n this.removeEventListener('error', onQueueError)\n this.removeEventListener('idle', onQueueIdle)\n options?.signal?.removeEventListener('abort', onSignalAbort)\n\n // empty the queue for when the user has broken out of a loop early\n cleanup()\n }\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\n\nimport { Queue, type QueueAddOptions } from './queue/index.js'\nimport type { Job } from './queue/job.js'\nimport type { PeerId } from '@libp2p/interface'\n\nexport interface PeerQueueJobOptions extends QueueAddOptions {\n peerId: PeerId\n}\n\n/**\n * Extends Queue to add support for querying queued jobs by peer id\n */\nexport class PeerQueue extends Queue {\n has (peerId: PeerId): boolean {\n return this.find(peerId) != null\n }\n\n find (peerId: PeerId): Job | undefined {\n return this.queue.find(job => {\n return peerId.equals(job.options.peerId)\n })\n }\n}\n","export * from './constants.defaults.js'\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#minConnections\n */\nexport const MIN_CONNECTIONS = 5\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxConnections\n */\nexport const MAX_CONNECTIONS = 100\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelDials\n */\nexport const MAX_PARALLEL_DIALS = 50\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.unknown.ConnectionManagerInit.html#autoDialPeerRetryThreshold\n */\nexport const AUTO_DIAL_PEER_RETRY_THRESHOLD = 1000 * 60 * 7\n","/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#dialTimeout\n */\nexport const DIAL_TIMEOUT = 5e3\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundUpgradeTimeout\n */\nexport const INBOUND_UPGRADE_TIMEOUT = 2e3\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxPeerAddrsToDial\n */\nexport const MAX_PEER_ADDRS_TO_DIAL = 25\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialInterval\n */\nexport const AUTO_DIAL_INTERVAL = 5000\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialConcurrency\n */\nexport const AUTO_DIAL_CONCURRENCY = 25\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialPriority\n */\nexport const AUTO_DIAL_PRIORITY = 0\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialMaxQueueLength\n */\nexport const AUTO_DIAL_MAX_QUEUE_LENGTH = 100\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.unknown.ConnectionManagerInit.html#autoDialDiscoveredPeersDebounce\n */\nexport const AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE = 10\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundConnectionThreshold\n */\nexport const INBOUND_CONNECTION_THRESHOLD = 5\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxIncomingPendingConnections\n */\nexport const MAX_INCOMING_PENDING_CONNECTIONS = 10\n\n/**\n * Store as part of the peer store metadata for a given peer, the value for this\n * key is a timestamp of the last time a dial attempted failed with the relevant\n * peer stored as a string.\n *\n * Used to insure we do not endlessly try to auto dial peers we have recently\n * failed to dial.\n */\nexport const LAST_DIAL_FAILURE_KEY = 'last-dial-failure'\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxDialQueueLength\n */\nexport const MAX_DIAL_QUEUE_LENGTH = 500\n","import { PeerMap, PeerSet } from '@libp2p/peer-collections'\nimport { PeerQueue } from '@libp2p/utils/peer-queue'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { AUTO_DIAL_CONCURRENCY, AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE, AUTO_DIAL_INTERVAL, AUTO_DIAL_MAX_QUEUE_LENGTH, AUTO_DIAL_PEER_RETRY_THRESHOLD, AUTO_DIAL_PRIORITY, LAST_DIAL_FAILURE_KEY, MIN_CONNECTIONS } from './constants.js'\nimport type { Libp2pEvents, Logger, ComponentLogger, TypedEventTarget, PeerStore, Startable, Metrics } from '@libp2p/interface'\nimport type { ConnectionManager } from '@libp2p/interface-internal'\n\ninterface AutoDialInit {\n minConnections?: number\n maxQueueLength?: number\n autoDialConcurrency?: number\n autoDialPriority?: number\n autoDialInterval?: number\n autoDialPeerRetryThreshold?: number\n autoDialDiscoveredPeersDebounce?: number\n}\n\ninterface AutoDialComponents {\n connectionManager: ConnectionManager\n peerStore: PeerStore\n events: TypedEventTarget\n logger: ComponentLogger\n metrics?: Metrics\n}\n\nconst defaultOptions = {\n minConnections: MIN_CONNECTIONS,\n maxQueueLength: AUTO_DIAL_MAX_QUEUE_LENGTH,\n autoDialConcurrency: AUTO_DIAL_CONCURRENCY,\n autoDialPriority: AUTO_DIAL_PRIORITY,\n autoDialInterval: AUTO_DIAL_INTERVAL,\n autoDialPeerRetryThreshold: AUTO_DIAL_PEER_RETRY_THRESHOLD,\n autoDialDiscoveredPeersDebounce: AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE\n}\n\nexport class AutoDial implements Startable {\n private readonly connectionManager: ConnectionManager\n private readonly peerStore: PeerStore\n private readonly queue: PeerQueue\n private readonly minConnections: number\n private readonly autoDialPriority: number\n private readonly autoDialIntervalMs: number\n private readonly autoDialMaxQueueLength: number\n private readonly autoDialPeerRetryThresholdMs: number\n private readonly autoDialDiscoveredPeersDebounce: number\n private autoDialInterval?: ReturnType\n private started: boolean\n private running: boolean\n private readonly log: Logger\n\n /**\n * Proactively tries to connect to known peers stored in the PeerStore.\n * It will keep the number of connections below the upper limit and sort\n * the peers to connect based on whether we know their keys and protocols.\n */\n constructor (components: AutoDialComponents, init: AutoDialInit) {\n this.connectionManager = components.connectionManager\n this.peerStore = components.peerStore\n this.minConnections = init.minConnections ?? defaultOptions.minConnections\n this.autoDialPriority = init.autoDialPriority ?? defaultOptions.autoDialPriority\n this.autoDialIntervalMs = init.autoDialInterval ?? defaultOptions.autoDialInterval\n this.autoDialMaxQueueLength = init.maxQueueLength ?? defaultOptions.maxQueueLength\n this.autoDialPeerRetryThresholdMs = init.autoDialPeerRetryThreshold ?? defaultOptions.autoDialPeerRetryThreshold\n this.autoDialDiscoveredPeersDebounce = init.autoDialDiscoveredPeersDebounce ?? defaultOptions.autoDialDiscoveredPeersDebounce\n this.log = components.logger.forComponent('libp2p:connection-manager:auto-dial')\n this.started = false\n this.running = false\n this.queue = new PeerQueue({\n concurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n metricName: 'libp2p_autodial_queue',\n metrics: components.metrics\n })\n this.queue.addEventListener('error', (evt) => {\n this.log.error('error during auto-dial', evt.detail)\n })\n\n // check the min connection limit whenever a peer disconnects\n components.events.addEventListener('connection:close', () => {\n this.autoDial()\n .catch(err => {\n this.log.error(err)\n })\n })\n\n // sometimes peers are discovered in quick succession so add a small\n // debounce to ensure all eligible peers are autodialed\n let debounce: ReturnType\n\n // when new peers are discovered, dial them if we don't have\n // enough connections\n components.events.addEventListener('peer:discovery', () => {\n clearTimeout(debounce)\n debounce = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error(err)\n })\n }, this.autoDialDiscoveredPeersDebounce)\n })\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n }\n\n afterStart (): void {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err)\n })\n }\n\n stop (): void {\n // clear the queue\n this.queue.clear()\n clearTimeout(this.autoDialInterval)\n this.started = false\n this.running = false\n }\n\n async autoDial (): Promise {\n if (!this.started || this.running) {\n return\n }\n\n const connections = this.connectionManager.getConnectionsMap()\n const numConnections = connections.size\n\n // already have enough connections\n if (numConnections >= this.minConnections) {\n if (this.minConnections > 0) {\n this.log.trace('have enough connections %d/%d', numConnections, this.minConnections)\n }\n\n // no need to schedule next autodial as it will be run when on\n // connection:close event\n return\n }\n\n if (this.queue.size > this.autoDialMaxQueueLength) {\n this.log('not enough connections %d/%d but auto dial queue is full', numConnections, this.minConnections)\n this.sheduleNextAutodial()\n return\n }\n\n this.running = true\n\n this.log('not enough connections %d/%d - will dial peers to increase the number of connections', numConnections, this.minConnections)\n\n const dialQueue = new PeerSet(\n // @ts-expect-error boolean filter removes falsy peer IDs\n this.connectionManager.getDialQueue()\n .map(queue => queue.peerId)\n .filter(Boolean)\n )\n\n // sort peers on whether we know protocols or public keys for them\n const peers = await this.peerStore.all({\n filters: [\n // remove some peers\n (peer) => {\n // remove peers without addresses\n if (peer.addresses.length === 0) {\n this.log.trace('not autodialing %p because they have no addresses', peer.id)\n return false\n }\n\n // remove peers we are already connected to\n if (connections.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already connected', peer.id)\n return false\n }\n\n // remove peers we are already dialling\n if (dialQueue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being dialed', peer.id)\n return false\n }\n\n // remove peers already in the autodial queue\n if (this.queue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being autodialed', peer.id)\n return false\n }\n\n return true\n }\n ]\n })\n\n // shuffle the peers - this is so peers with the same tag values will be\n // dialled in a different order each time\n const shuffledPeers = peers.sort(() => Math.random() > 0.5 ? 1 : -1)\n\n // sort shuffled peers by tag value\n const peerValues = new PeerMap()\n for (const peer of shuffledPeers) {\n if (peerValues.has(peer.id)) {\n continue\n }\n\n // sum all tag values\n peerValues.set(peer.id, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value\n }, 0))\n }\n\n // sort by value, highest to lowest\n const sortedPeers = shuffledPeers.sort((a, b) => {\n const peerAValue = peerValues.get(a.id) ?? 0\n const peerBValue = peerValues.get(b.id) ?? 0\n\n if (peerAValue > peerBValue) {\n return -1\n }\n\n if (peerAValue < peerBValue) {\n return 1\n }\n\n return 0\n })\n\n const peersThatHaveNotFailed = sortedPeers.filter(peer => {\n const lastDialFailure = peer.metadata.get(LAST_DIAL_FAILURE_KEY)\n\n if (lastDialFailure == null) {\n return true\n }\n\n const lastDialFailureTimestamp = parseInt(uint8ArrayToString(lastDialFailure))\n\n if (isNaN(lastDialFailureTimestamp)) {\n return true\n }\n\n // only dial if the time since the last failure is above the retry threshold\n return Date.now() - lastDialFailureTimestamp > this.autoDialPeerRetryThresholdMs\n })\n\n this.log('selected %d/%d peers to dial', peersThatHaveNotFailed.length, peers.length)\n\n for (const peer of peersThatHaveNotFailed) {\n this.queue.add(async () => {\n const numConnections = this.connectionManager.getConnectionsMap().size\n\n // Check to see if we still need to auto dial\n if (numConnections >= this.minConnections) {\n this.log('got enough connections now %d/%d', numConnections, this.minConnections)\n this.queue.clear()\n return\n }\n\n this.log('connecting to a peerStore stored peer %p', peer.id)\n await this.connectionManager.openConnection(peer.id, {\n priority: this.autoDialPriority\n })\n }, {\n peerId: peer.id\n }).catch(err => {\n this.log.error('could not connect to peerStore stored peer', err)\n })\n }\n\n this.running = false\n this.sheduleNextAutodial()\n }\n\n private sheduleNextAutodial (): void {\n if (!this.started) {\n return\n }\n\n this.autoDialInterval = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err)\n })\n }, this.autoDialIntervalMs)\n }\n}\n","import { PeerMap } from '@libp2p/peer-collections'\nimport { MAX_CONNECTIONS } from './constants.js'\nimport type { Libp2pEvents, Logger, ComponentLogger, TypedEventTarget, PeerStore } from '@libp2p/interface'\nimport type { ConnectionManager } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\ninterface ConnectionPrunerInit {\n maxConnections?: number\n allow?: Multiaddr[]\n}\n\ninterface ConnectionPrunerComponents {\n connectionManager: ConnectionManager\n peerStore: PeerStore\n events: TypedEventTarget\n logger: ComponentLogger\n}\n\nconst defaultOptions = {\n maxConnections: MAX_CONNECTIONS,\n allow: []\n}\n\n/**\n * If we go over the max connections limit, choose some connections to close\n */\nexport class ConnectionPruner {\n private readonly maxConnections: number\n private readonly connectionManager: ConnectionManager\n private readonly peerStore: PeerStore\n private readonly allow: Multiaddr[]\n private readonly events: TypedEventTarget\n private readonly log: Logger\n\n constructor (components: ConnectionPrunerComponents, init: ConnectionPrunerInit = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections\n this.allow = init.allow ?? defaultOptions.allow\n this.connectionManager = components.connectionManager\n this.peerStore = components.peerStore\n this.events = components.events\n this.log = components.logger.forComponent('libp2p:connection-manager:connection-pruner')\n\n // check the max connection limit whenever a peer connects\n components.events.addEventListener('connection:open', () => {\n this.maybePruneConnections()\n .catch(err => {\n this.log.error(err)\n })\n })\n }\n\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n async maybePruneConnections (): Promise {\n const connections = this.connectionManager.getConnections()\n const numConnections = connections.length\n const toPrune = Math.max(numConnections - this.maxConnections, 0)\n\n this.log('checking max connections limit %d/%d', numConnections, this.maxConnections)\n if (numConnections <= this.maxConnections) {\n return\n }\n\n this.log('max connections limit exceeded %d/%d, pruning %d connection(s)', numConnections, this.maxConnections, toPrune)\n const peerValues = new PeerMap()\n\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer\n\n if (peerValues.has(remotePeer)) {\n continue\n }\n\n peerValues.set(remotePeer, 0)\n\n try {\n const peer = await this.peerStore.get(remotePeer)\n\n // sum all tag values\n peerValues.set(remotePeer, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value\n }, 0))\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n this.log.error('error loading peer tags', err)\n }\n }\n }\n\n // sort by value, lowest to highest\n const sortedConnections = connections.sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0\n const peerBValue = peerValues.get(b.remotePeer) ?? 0\n\n if (peerAValue > peerBValue) {\n return 1\n }\n\n if (peerAValue < peerBValue) {\n return -1\n }\n\n // if the peers have an equal tag value then we want to close short-lived connections first\n const connectionALifespan = a.timeline.open\n const connectionBLifespan = b.timeline.open\n\n if (connectionALifespan < connectionBLifespan) {\n return 1\n }\n\n if (connectionALifespan > connectionBLifespan) {\n return -1\n }\n\n return 0\n })\n\n // close some connections\n const toClose = []\n\n for (const connection of sortedConnections) {\n this.log('too many connections open - closing a connection to %p', connection.remotePeer)\n // check allow list\n const connectionInAllowList = this.allow.some((ma) => {\n return connection.remoteAddr.toString().startsWith(ma.toString())\n })\n\n // Connections in the allow list should be excluded from pruning\n if (!connectionInAllowList) {\n toClose.push(connection)\n }\n\n if (toClose.length === toPrune) {\n break\n }\n }\n\n // close connections\n await Promise.all(\n toClose.map(async connection => {\n try {\n await connection.close()\n } catch (err) {\n this.log.error(err)\n }\n })\n )\n\n // despatch prune event\n this.events.safeDispatchEvent('connection:prune', { detail: toClose })\n }\n}\n","/* eslint-disable max-depth */\nimport { CodeError, AggregateCodeError, ERR_TIMEOUT, setMaxListeners } from '@libp2p/interface'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { defaultAddressSort } from '@libp2p/utils/address-sort'\nimport { Queue, type QueueAddOptions } from '@libp2p/utils/queue'\nimport { type Multiaddr, type Resolver, resolvers, multiaddr } from '@multiformats/multiaddr'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport { type ClearableSignal, anySignal } from 'any-signal'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { codes } from '../errors.js'\nimport { getPeerAddress } from '../get-peer.js'\nimport {\n DIAL_TIMEOUT,\n MAX_PARALLEL_DIALS,\n MAX_PEER_ADDRS_TO_DIAL,\n LAST_DIAL_FAILURE_KEY,\n MAX_DIAL_QUEUE_LENGTH\n} from './constants.js'\nimport { resolveMultiaddrs } from './utils.js'\nimport type { AddressSorter, AbortOptions, ComponentLogger, Logger, Connection, ConnectionGater, Metrics, PeerId, Address, PeerStore, PeerRouting } from '@libp2p/interface'\nimport type { TransportManager } from '@libp2p/interface-internal'\nimport type { DNS } from '@multiformats/dns'\n\nexport interface PendingDialTarget {\n resolve(value: any): void\n reject(err: Error): void\n}\n\nexport interface DialOptions extends AbortOptions {\n priority?: number\n force?: boolean\n}\n\ninterface DialQueueJobOptions extends QueueAddOptions {\n peerId?: PeerId\n multiaddrs: Set\n}\n\ninterface DialerInit {\n addressSorter?: AddressSorter\n maxParallelDials?: number\n maxDialQueueLength?: number\n maxPeerAddrsToDial?: number\n dialTimeout?: number\n resolvers?: Record\n connections?: PeerMap\n}\n\nconst defaultOptions = {\n addressSorter: defaultAddressSort,\n maxParallelDials: MAX_PARALLEL_DIALS,\n maxDialQueueLength: MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: DIAL_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n }\n}\n\ninterface DialQueueComponents {\n peerId: PeerId\n metrics?: Metrics\n peerStore: PeerStore\n peerRouting: PeerRouting\n transportManager: TransportManager\n connectionGater: ConnectionGater\n logger: ComponentLogger\n dns?: DNS\n}\n\nexport class DialQueue {\n public queue: Queue\n private readonly components: DialQueueComponents\n private readonly addressSorter: AddressSorter\n private readonly maxPeerAddrsToDial: number\n private readonly maxDialQueueLength: number\n private readonly dialTimeout: number\n private shutDownController: AbortController\n private readonly connections: PeerMap\n private readonly log: Logger\n\n constructor (components: DialQueueComponents, init: DialerInit = {}) {\n this.addressSorter = init.addressSorter ?? defaultOptions.addressSorter\n this.maxPeerAddrsToDial = init.maxPeerAddrsToDial ?? defaultOptions.maxPeerAddrsToDial\n this.maxDialQueueLength = init.maxDialQueueLength ?? defaultOptions.maxDialQueueLength\n this.dialTimeout = init.dialTimeout ?? defaultOptions.dialTimeout\n this.connections = init.connections ?? new PeerMap()\n this.log = components.logger.forComponent('libp2p:connection-manager:dial-queue')\n this.components = components\n\n this.shutDownController = new AbortController()\n setMaxListeners(Infinity, this.shutDownController.signal)\n\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n resolvers.set(key, value)\n }\n\n // controls dial concurrency\n this.queue = new Queue({\n concurrency: init.maxParallelDials ?? defaultOptions.maxParallelDials,\n metricName: 'libp2p_dial_queue',\n metrics: components.metrics\n })\n // a started job errored\n this.queue.addEventListener('error', (event) => {\n this.log.error('error in dial queue', event.detail)\n })\n }\n\n start (): void {\n this.shutDownController = new AbortController()\n setMaxListeners(Infinity, this.shutDownController.signal)\n }\n\n /**\n * Clears any pending dials\n */\n stop (): void {\n this.shutDownController.abort()\n this.queue.abort()\n }\n\n /**\n * Connects to a given peer, multiaddr or list of multiaddrs.\n *\n * If a peer is passed, all known multiaddrs will be tried. If a multiaddr or\n * multiaddrs are passed only those will be dialled.\n *\n * Where a list of multiaddrs is passed, if any contain a peer id then all\n * multiaddrs in the list must contain the same peer id.\n *\n * The dial to the first address that is successfully able to upgrade a\n * connection will be used, all other dials will be aborted when that happens.\n */\n async dial (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: DialOptions = {}): Promise {\n const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr)\n\n // make sure we don't have an existing connection to any of the addresses we\n // are about to dial\n const existingConnection = Array.from(this.connections.values()).flat().find(conn => {\n if (options.force === true) {\n return false\n }\n\n if (conn.remotePeer.equals(peerId)) {\n return true\n }\n\n return multiaddrs.find(addr => {\n return addr.equals(conn.remoteAddr)\n })\n })\n\n if (existingConnection != null) {\n this.log('already connected to %a', existingConnection.remoteAddr)\n return existingConnection\n }\n\n // ready to dial, all async work finished - make sure we don't have any\n // pending dials in progress for this peer or set of multiaddrs\n const existingDial = this.queue.queue.find(job => {\n if (peerId?.equals(job.options.peerId) === true) {\n return true\n }\n\n // does the dial contain any of the target multiaddrs?\n const addresses = job.options.multiaddrs\n\n if (addresses == null) {\n return false\n }\n\n for (const multiaddr of multiaddrs) {\n if (addresses.has(multiaddr.toString())) {\n return true\n }\n }\n\n return false\n })\n\n if (existingDial != null) {\n this.log('joining existing dial target for %p', peerId)\n\n // add all multiaddrs to the dial target\n for (const multiaddr of multiaddrs) {\n existingDial.options.multiaddrs.add(multiaddr.toString())\n }\n\n return existingDial.join(options)\n }\n\n if (this.queue.size >= this.maxDialQueueLength) {\n throw new CodeError('Dial queue is full', 'ERR_DIAL_QUEUE_FULL')\n }\n\n this.log('creating dial target for %p', peerId, multiaddrs.map(ma => ma.toString()))\n\n return this.queue.add(async (options) => {\n // create abort conditions - need to do this before `calculateMultiaddrs` as\n // we may be about to resolve a dns addr which can time out\n const signal = this.createDialAbortController(options?.signal)\n let addrsToDial: Address[]\n\n try {\n // load addresses from address book, resolve and dnsaddrs, filter\n // undiallables, add peer IDs, etc\n addrsToDial = await this.calculateMultiaddrs(peerId, options?.multiaddrs, {\n ...options,\n signal\n })\n\n addrsToDial.map(({ multiaddr }) => multiaddr.toString()).forEach(addr => {\n options?.multiaddrs.add(addr)\n })\n } catch (err) {\n signal.clear()\n throw err\n }\n\n try {\n let dialed = 0\n const errors: Error[] = []\n\n for (const address of addrsToDial) {\n if (dialed === this.maxPeerAddrsToDial) {\n this.log('dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others', dialed, peerId)\n\n throw new CodeError('Peer had more than maxPeerAddrsToDial', codes.ERR_TOO_MANY_ADDRESSES)\n }\n\n dialed++\n\n try {\n const conn = await this.components.transportManager.dial(address.multiaddr, {\n ...options,\n signal\n })\n\n this.log('dial to %a succeeded', address.multiaddr)\n\n return conn\n } catch (err: any) {\n this.log.error('dial failed to %a', address.multiaddr, err)\n\n if (peerId != null) {\n // record the failed dial\n try {\n await this.components.peerStore.patch(peerId, {\n metadata: {\n [LAST_DIAL_FAILURE_KEY]: uint8ArrayFromString(Date.now().toString())\n }\n })\n } catch (err: any) {\n this.log.error('could not update last dial failure key for %p', peerId, err)\n }\n }\n\n // the user/dial timeout/shutdown controller signal aborted\n if (signal.aborted) {\n throw new CodeError(err.message, ERR_TIMEOUT)\n }\n\n errors.push(err)\n }\n }\n\n if (errors.length === 1) {\n throw errors[0]\n }\n\n throw new AggregateCodeError(errors, 'All multiaddr dials failed', codes.ERR_TRANSPORT_DIAL_FAILED)\n } finally {\n // clean up abort signals/controllers\n signal.clear()\n }\n }, {\n peerId,\n priority: options.priority,\n multiaddrs: new Set(multiaddrs.map(ma => ma.toString())),\n signal: options.signal\n })\n }\n\n private createDialAbortController (userSignal?: AbortSignal): ClearableSignal {\n // let any signal abort the dial\n const signal = anySignal([\n AbortSignal.timeout(this.dialTimeout),\n this.shutDownController.signal,\n userSignal\n ])\n\n // This emitter gets listened to a lot\n setMaxListeners(Infinity, signal)\n\n return signal\n }\n\n // eslint-disable-next-line complexity\n private async calculateMultiaddrs (peerId?: PeerId, multiaddrs: Set = new Set(), options: DialOptions = {}): Promise {\n const addrs: Address[] = [...multiaddrs].map(ma => ({\n multiaddr: multiaddr(ma),\n isCertified: false\n }))\n\n // if a peer id or multiaddr(s) with a peer id, make sure it isn't our peer id and that we are allowed to dial it\n if (peerId != null) {\n if (this.components.peerId.equals(peerId)) {\n throw new CodeError('Tried to dial self', codes.ERR_DIALED_SELF)\n }\n\n if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {\n throw new CodeError('The dial request is blocked by gater.allowDialPeer', codes.ERR_PEER_DIAL_INTERCEPTED)\n }\n\n // if just a peer id was passed, load available multiaddrs for this peer\n // from the peer store\n if (addrs.length === 0) {\n this.log('loading multiaddrs for %p', peerId)\n try {\n const peer = await this.components.peerStore.get(peerId)\n addrs.push(...peer.addresses)\n this.log('loaded multiaddrs for %p', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()))\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n }\n\n // if we still don't have any addresses for this peer, try a lookup\n // using the peer routing\n if (addrs.length === 0) {\n this.log('looking up multiaddrs for %p in the peer routing', peerId)\n\n try {\n const peerInfo = await this.components.peerRouting.findPeer(peerId)\n\n this.log('found multiaddrs for %p in the peer routing', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()))\n\n addrs.push(...peerInfo.multiaddrs.map(multiaddr => ({\n multiaddr,\n isCertified: false\n })))\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_ROUTERS_AVAILABLE) {\n this.log.error('looking up multiaddrs for %p in the peer routing failed', peerId, err)\n }\n }\n }\n }\n\n // resolve addresses - this can result in a one-to-many translation when\n // dnsaddrs are resolved\n let resolvedAddresses = (await Promise.all(\n addrs.map(async addr => {\n const result = await resolveMultiaddrs(addr.multiaddr, {\n dns: this.components.dns,\n ...options,\n log: this.log\n })\n\n if (result.length === 1 && result[0].equals(addr.multiaddr)) {\n return addr\n }\n\n return result.map(multiaddr => ({\n multiaddr,\n isCertified: false\n }))\n })\n ))\n .flat()\n\n // ensure the peer id is appended to the multiaddr\n if (peerId != null) {\n const peerIdMultiaddr = `/p2p/${peerId.toString()}`\n resolvedAddresses = resolvedAddresses.map(addr => {\n const lastProto = addr.multiaddr.protos().pop()\n\n // do not append peer id to path multiaddrs\n if (lastProto?.path === true) {\n return addr\n }\n\n // append peer id to multiaddr if it is not already present\n if (addr.multiaddr.getPeerId() == null) {\n return {\n multiaddr: addr.multiaddr.encapsulate(peerIdMultiaddr),\n isCertified: addr.isCertified\n }\n }\n\n return addr\n })\n }\n\n const filteredAddrs = resolvedAddresses.filter(addr => {\n // filter out any multiaddrs that we do not have transports for\n if (this.components.transportManager.transportForMultiaddr(addr.multiaddr) == null) {\n return false\n }\n\n // if the resolved multiaddr has a PeerID but it's the wrong one, ignore it\n // - this can happen with addresses like bootstrap.libp2p.io that resolve\n // to multiple different peers\n const addrPeerId = addr.multiaddr.getPeerId()\n if (peerId != null && addrPeerId != null) {\n return peerId.equals(addrPeerId)\n }\n\n return true\n })\n\n // deduplicate addresses\n const dedupedAddrs = new Map()\n\n for (const addr of filteredAddrs) {\n const maStr = addr.multiaddr.toString()\n const existing = dedupedAddrs.get(maStr)\n\n if (existing != null) {\n existing.isCertified = existing.isCertified || addr.isCertified || false\n continue\n }\n\n dedupedAddrs.set(maStr, addr)\n }\n\n const dedupedMultiaddrs = [...dedupedAddrs.values()]\n\n // make sure we actually have some addresses to dial\n if (dedupedMultiaddrs.length === 0) {\n throw new CodeError('The dial request has no valid addresses', codes.ERR_NO_VALID_ADDRESSES)\n }\n\n const gatedAdrs: Address[] = []\n\n for (const addr of dedupedMultiaddrs) {\n if (this.components.connectionGater.denyDialMultiaddr != null && await this.components.connectionGater.denyDialMultiaddr(addr.multiaddr)) {\n continue\n }\n\n gatedAdrs.push(addr)\n }\n\n const sortedGatedAddrs = gatedAdrs.sort(this.addressSorter)\n\n // make sure we actually have some addresses to dial\n if (sortedGatedAddrs.length === 0) {\n throw new CodeError('The connection gater denied all addresses in the dial request', codes.ERR_NO_VALID_ADDRESSES)\n }\n\n this.log.trace('addresses for %p before filtering', peerId ?? 'unknown peer', resolvedAddresses.map(({ multiaddr }) => multiaddr.toString()))\n this.log.trace('addresses for %p after filtering', peerId ?? 'unknown peer', sortedGatedAddrs.map(({ multiaddr }) => multiaddr.toString()))\n\n return sortedGatedAddrs\n }\n}\n","\nexport interface ClearableSignal extends AbortSignal {\n clear: () => void\n}\n\n/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal (signals: Array): ClearableSignal {\n const controller = new globalThis.AbortController()\n\n function onAbort (): void {\n controller.abort()\n\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort()\n break\n }\n\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort)\n }\n }\n\n function clear (): void {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n const signal = controller.signal as ClearableSignal\n signal.clear = clear\n\n return signal\n}\n","import { resolvers } from '@multiformats/multiaddr'\nimport type { LoggerOptions } from '@libp2p/interface'\nimport type { Multiaddr, ResolveOptions } from '@multiformats/multiaddr'\n\n/**\n * Recursively resolve DNSADDR multiaddrs\n */\nexport async function resolveMultiaddrs (ma: Multiaddr, options: ResolveOptions & LoggerOptions): Promise {\n // check multiaddr resolvers\n let resolvable = false\n\n for (const key of resolvers.keys()) {\n resolvable = ma.protoNames().includes(key)\n\n if (resolvable) {\n break\n }\n }\n\n // return multiaddr if it is not resolvable\n if (!resolvable) {\n return [ma]\n }\n\n const output = await ma.resolve(options)\n\n options.log('resolved %s to', ma, output.map(ma => ma.toString()))\n\n return output\n}\n","import { CodeError, KEEP_ALIVE } from '@libp2p/interface'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { defaultAddressSort } from '@libp2p/utils/address-sort'\nimport { RateLimiter } from '@libp2p/utils/rate-limiter'\nimport { type Multiaddr, type Resolver, multiaddr } from '@multiformats/multiaddr'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport { codes } from '../errors.js'\nimport { getPeerAddress } from '../get-peer.js'\nimport { AutoDial } from './auto-dial.js'\nimport { ConnectionPruner } from './connection-pruner.js'\nimport { AUTO_DIAL_CONCURRENCY, AUTO_DIAL_MAX_QUEUE_LENGTH, AUTO_DIAL_PRIORITY, DIAL_TIMEOUT, INBOUND_CONNECTION_THRESHOLD, MAX_CONNECTIONS, MAX_DIAL_QUEUE_LENGTH, MAX_INCOMING_PENDING_CONNECTIONS, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL, MIN_CONNECTIONS } from './constants.js'\nimport { DialQueue } from './dial-queue.js'\nimport type { PendingDial, AddressSorter, Libp2pEvents, AbortOptions, ComponentLogger, Logger, Connection, MultiaddrConnection, ConnectionGater, TypedEventTarget, Metrics, PeerId, Peer, PeerStore, Startable, PendingDialStatus, PeerRouting } from '@libp2p/interface'\nimport type { ConnectionManager, OpenConnectionOptions, TransportManager } from '@libp2p/interface-internal'\nimport type { JobStatus } from '@libp2p/utils/queue'\n\nconst DEFAULT_DIAL_PRIORITY = 50\n\nexport interface ConnectionManagerInit {\n /**\n * The maximum number of connections libp2p is willing to have before it starts\n * pruning connections to reduce resource usage. (default: 300, 100 in browsers)\n */\n maxConnections?: number\n\n /**\n * The minimum number of connections below which libp2p will start to dial peers\n * from the peer book. Setting this to 0 effectively disables this behaviour.\n * (default: 50, 5 in browsers)\n */\n minConnections?: number\n\n /**\n * How long to wait between attempting to keep our number of concurrent connections\n * above minConnections (default: 5000)\n */\n autoDialInterval?: number\n\n /**\n * When dialling peers from the peer book to keep the number of open connections\n * above `minConnections`, add dials for this many peers to the dial queue\n * at once. (default: 25)\n */\n autoDialConcurrency?: number\n\n /**\n * To allow user dials to take priority over auto dials, use this value as the\n * dial priority. (default: 0)\n */\n autoDialPriority?: number\n\n /**\n * Limit the maximum number of peers to dial when trying to keep the number of\n * open connections above `minConnections`. (default: 100)\n */\n autoDialMaxQueueLength?: number\n\n /**\n * When we've failed to dial a peer, do not autodial them again within this\n * number of ms. (default: 1 minute, 7 minutes in browsers)\n */\n autoDialPeerRetryThreshold?: number\n\n /**\n * Newly discovered peers may be auto-dialed to increase the number of open\n * connections, but they can be discovered in quick succession so add a small\n * delay before attempting to dial them in case more peers have been\n * discovered. (default: 10ms)\n */\n autoDialDiscoveredPeersDebounce?: number\n\n /**\n * Sort the known addresses of a peer before trying to dial, By default public\n * addresses will be dialled before private (e.g. loopback or LAN) addresses.\n */\n addressSorter?: AddressSorter\n\n /**\n * The maximum number of dials across all peers to execute in parallel.\n * (default: 100, 50 in browsers)\n */\n maxParallelDials?: number\n\n /**\n * The maximum size the dial queue is allowed to grow to. Promises returned\n * when dialing peers after this limit is reached will not resolve until the\n * queue size falls beneath this size.\n *\n * @default 500\n */\n maxDialQueueLength?: number\n\n /**\n * Maximum number of addresses allowed for a given peer before giving up\n *\n * @default 25\n */\n maxPeerAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take, including DNS resolution\n * of the multiaddr, opening a socket and upgrading it to a Connection.\n */\n dialTimeout?: number\n\n /**\n * When a new inbound connection is opened, the upgrade process (e.g. protect,\n * encrypt, multiplex etc) must complete within this number of ms. (default: 30s)\n */\n inboundUpgradeTimeout?: number\n\n /**\n * Multiaddr resolvers to use when dialling\n */\n resolvers?: Record\n\n /**\n * A list of multiaddrs that will always be allowed (except if they are in the\n * deny list) to open connections to this node even if we've reached maxConnections\n */\n allow?: string[]\n\n /**\n * A list of multiaddrs that will never be allowed to open connections to\n * this node under any circumstances\n */\n deny?: string[]\n\n /**\n * If more than this many connections are opened per second by a single\n * host, reject subsequent connections. (default: 5)\n */\n inboundConnectionThreshold?: number\n\n /**\n * The maximum number of parallel incoming connections allowed that have yet to\n * complete the connection upgrade - e.g. choosing connection encryption, muxer, etc.\n * (default: 10)\n */\n maxIncomingPendingConnections?: number\n}\n\nconst defaultOptions = {\n minConnections: MIN_CONNECTIONS,\n maxConnections: MAX_CONNECTIONS,\n inboundConnectionThreshold: INBOUND_CONNECTION_THRESHOLD,\n maxIncomingPendingConnections: MAX_INCOMING_PENDING_CONNECTIONS,\n autoDialConcurrency: AUTO_DIAL_CONCURRENCY,\n autoDialPriority: AUTO_DIAL_PRIORITY,\n autoDialMaxQueueLength: AUTO_DIAL_MAX_QUEUE_LENGTH\n}\n\nexport interface DefaultConnectionManagerComponents {\n peerId: PeerId\n metrics?: Metrics\n peerStore: PeerStore\n peerRouting: PeerRouting\n transportManager: TransportManager\n connectionGater: ConnectionGater\n events: TypedEventTarget\n logger: ComponentLogger\n}\n\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager implements ConnectionManager, Startable {\n private started: boolean\n private readonly connections: PeerMap\n private readonly allow: Multiaddr[]\n private readonly deny: Multiaddr[]\n private readonly maxIncomingPendingConnections: number\n private incomingPendingConnections: number\n private readonly maxConnections: number\n\n public readonly dialQueue: DialQueue\n public readonly autoDial: AutoDial\n public readonly connectionPruner: ConnectionPruner\n private readonly inboundConnectionRateLimiter: RateLimiter\n\n private readonly peerStore: PeerStore\n private readonly metrics?: Metrics\n private readonly events: TypedEventTarget\n private readonly log: Logger\n\n constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerInit = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections\n const minConnections = init.minConnections ?? defaultOptions.minConnections\n\n if (this.maxConnections < minConnections) {\n throw new CodeError('Connection Manager maxConnections must be greater than minConnections', codes.ERR_INVALID_PARAMETERS)\n }\n\n /**\n * Map of connections per peer\n */\n this.connections = new PeerMap()\n\n this.started = false\n this.peerStore = components.peerStore\n this.metrics = components.metrics\n this.events = components.events\n this.log = components.logger.forComponent('libp2p:connection-manager')\n\n this.onConnect = this.onConnect.bind(this)\n this.onDisconnect = this.onDisconnect.bind(this)\n this.events.addEventListener('connection:open', this.onConnect)\n this.events.addEventListener('connection:close', this.onDisconnect)\n\n // allow/deny lists\n this.allow = (init.allow ?? []).map(ma => multiaddr(ma))\n this.deny = (init.deny ?? []).map(ma => multiaddr(ma))\n\n this.incomingPendingConnections = 0\n this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections\n\n // controls individual peers trying to dial us too quickly\n this.inboundConnectionRateLimiter = new RateLimiter({\n points: init.inboundConnectionThreshold ?? defaultOptions.inboundConnectionThreshold,\n duration: 1\n })\n\n // controls what happens when we don't have enough connections\n this.autoDial = new AutoDial({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n minConnections,\n autoDialConcurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n autoDialPriority: init.autoDialPriority ?? defaultOptions.autoDialPriority,\n maxQueueLength: init.autoDialMaxQueueLength ?? defaultOptions.autoDialMaxQueueLength\n })\n\n // controls what happens when we have too many connections\n this.connectionPruner = new ConnectionPruner({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n maxConnections: this.maxConnections,\n allow: this.allow\n })\n\n this.dialQueue = new DialQueue(components, {\n addressSorter: init.addressSorter ?? defaultAddressSort,\n maxParallelDials: init.maxParallelDials ?? MAX_PARALLEL_DIALS,\n maxDialQueueLength: init.maxDialQueueLength ?? MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: init.maxPeerAddrsToDial ?? MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: init.dialTimeout ?? DIAL_TIMEOUT,\n resolvers: init.resolvers ?? {\n dnsaddr: dnsaddrResolver\n },\n connections: this.connections\n })\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start (): Promise {\n // track inbound/outbound connections\n this.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {\n calculate: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n }\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.direction === 'inbound') {\n metric.inbound++\n } else {\n metric.outbound++\n }\n }\n }\n\n return metric\n }\n })\n\n // track total number of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {\n label: 'protocol',\n calculate: () => {\n const metric: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`\n\n metric[key] = (metric[key] ?? 0) + 1\n }\n }\n }\n\n return metric\n }\n })\n\n // track 90th percentile of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {\n label: 'protocol',\n calculate: () => {\n const allStreams: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams: Record = {}\n\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`\n\n streams[key] = (streams[key] ?? 0) + 1\n }\n\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? []\n allStreams[protocol].push(count)\n }\n }\n }\n\n const metric: Record = {}\n\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b)\n\n const index = Math.floor(counts.length * 0.9)\n metric[protocol] = counts[index]\n }\n\n return metric\n }\n })\n\n this.dialQueue.start()\n this.autoDial.start()\n\n this.started = true\n this.log('started')\n }\n\n async afterStart (): Promise {\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers: Peer[] = await this.peerStore.all({\n filters: [(peer) => {\n return peer.tags.has(KEEP_ALIVE)\n }]\n })\n\n await Promise.all(\n keepAlivePeers.map(async peer => {\n await this.openConnection(peer.id)\n .catch(err => {\n this.log.error(err)\n })\n })\n )\n })\n .catch(err => {\n this.log.error(err)\n })\n\n this.autoDial.afterStart()\n }\n\n /**\n * Stops the Connection Manager\n */\n async stop (): Promise {\n this.dialQueue.stop()\n this.autoDial.stop()\n\n // Close all connections we're tracking\n const tasks: Array> = []\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close()\n } catch (err) {\n this.log.error(err)\n }\n })())\n }\n }\n\n this.log('closing %d connections', tasks.length)\n await Promise.all(tasks)\n this.connections.clear()\n\n this.log('stopped')\n }\n\n onConnect (evt: CustomEvent): void {\n void this._onConnect(evt).catch(err => {\n this.log.error(err)\n })\n }\n\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect (evt: CustomEvent): Promise {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close()\n return\n }\n\n const peerId = connection.remotePeer\n const storedConns = this.connections.get(peerId)\n let isNewPeer = false\n\n if (storedConns != null) {\n storedConns.push(connection)\n } else {\n isNewPeer = true\n this.connections.set(peerId, [connection])\n }\n\n // only need to store RSA public keys, all other types are embedded in the peer id\n if (peerId.publicKey != null && peerId.type === 'RSA') {\n await this.peerStore.patch(peerId, {\n publicKey: peerId.publicKey\n })\n }\n\n if (isNewPeer) {\n this.events.safeDispatchEvent('peer:connect', { detail: connection.remotePeer })\n }\n }\n\n /**\n * Removes the connection from tracking\n */\n onDisconnect (evt: CustomEvent): void {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return\n }\n\n const peerId = connection.remotePeer\n let storedConn = this.connections.get(peerId)\n\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id)\n this.connections.set(peerId, storedConn)\n } else if (storedConn != null) {\n this.connections.delete(peerId)\n this.events.safeDispatchEvent('peer:disconnect', { detail: connection.remotePeer })\n }\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n if (peerId != null) {\n return this.connections.get(peerId) ?? []\n }\n\n let conns: Connection[] = []\n\n for (const c of this.connections.values()) {\n conns = conns.concat(c)\n }\n\n return conns\n }\n\n getConnectionsMap (): PeerMap {\n return this.connections\n }\n\n async openConnection (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: OpenConnectionOptions = {}): Promise {\n if (!this.isStarted()) {\n throw new CodeError('Not started', codes.ERR_NODE_NOT_STARTED)\n }\n\n options.signal?.throwIfAborted()\n\n const { peerId } = getPeerAddress(peerIdOrMultiaddr)\n\n if (peerId != null && options.force !== true) {\n this.log('dial %p', peerId)\n const existingConnection = this.getConnections(peerId)\n .find(conn => !conn.transient)\n\n if (existingConnection != null) {\n this.log('had an existing non-transient connection to %p', peerId)\n\n return existingConnection\n }\n }\n\n const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {\n ...options,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY\n })\n let peerConnections = this.connections.get(connection.remotePeer)\n\n if (peerConnections == null) {\n peerConnections = []\n this.connections.set(connection.remotePeer, peerConnections)\n }\n\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false\n\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true\n }\n }\n\n if (!trackedConnection) {\n peerConnections.push(connection)\n }\n\n return connection\n }\n\n async closeConnections (peerId: PeerId, options: AbortOptions = {}): Promise {\n const connections = this.connections.get(peerId) ?? []\n\n await Promise.all(\n connections.map(async connection => {\n try {\n await connection.close(options)\n } catch (err: any) {\n connection.abort(err)\n }\n })\n )\n }\n\n async acceptIncomingConnection (maConn: MultiaddrConnection): Promise {\n // check deny list\n const denyConnection = this.deny.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString())\n })\n\n if (denyConnection) {\n this.log('connection from %a refused - connection remote address was in deny list', maConn.remoteAddr)\n return false\n }\n\n // check allow list\n const allowConnection = this.allow.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString())\n })\n\n if (allowConnection) {\n this.incomingPendingConnections++\n\n return true\n }\n\n // check pending connections\n if (this.incomingPendingConnections === this.maxIncomingPendingConnections) {\n this.log('connection from %a refused - incomingPendingConnections exceeded by host', maConn.remoteAddr)\n return false\n }\n\n if (maConn.remoteAddr.isThinWaistAddress()) {\n const host = maConn.remoteAddr.nodeAddress().address\n\n try {\n await this.inboundConnectionRateLimiter.consume(host, 1)\n } catch {\n this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, host)\n return false\n }\n }\n\n if (this.getConnections().length < this.maxConnections) {\n this.incomingPendingConnections++\n\n return true\n }\n\n this.log('connection from %a refused - maxConnections exceeded', maConn.remoteAddr)\n return false\n }\n\n afterUpgradeInbound (): void {\n this.incomingPendingConnections--\n }\n\n getDialQueue (): PendingDial[] {\n const statusMap: Record = {\n queued: 'queued',\n running: 'active',\n errored: 'error',\n complete: 'success'\n }\n\n return this.dialQueue.queue.queue.map(job => {\n return {\n id: job.id,\n status: statusMap[job.status],\n peerId: job.options.peerId,\n multiaddrs: [...job.options.multiaddrs].map(ma => multiaddr(ma))\n }\n })\n }\n}\n","export const KEEP_ALIVE = 'keep-alive'\n","import { CodeError } from '@libp2p/interface'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport merge from 'it-merge'\nimport { codes, messages } from './errors.js'\nimport type { AbortOptions, ComponentLogger, ContentRouting, PeerInfo, PeerRouting, PeerStore, RoutingOptions, Startable } from '@libp2p/interface'\nimport type { CID } from 'multiformats/cid'\n\nexport interface CompoundContentRoutingInit {\n routers: ContentRouting[]\n}\n\nexport interface CompoundContentRoutingComponents {\n peerStore: PeerStore\n peerRouting: PeerRouting\n logger: ComponentLogger\n}\n\nexport class CompoundContentRouting implements ContentRouting, Startable {\n private readonly routers: ContentRouting[]\n private started: boolean\n private readonly components: CompoundContentRoutingComponents\n\n constructor (components: CompoundContentRoutingComponents, init: CompoundContentRoutingInit) {\n this.routers = init.routers ?? []\n this.started = false\n this.components = components\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n async start (): Promise {\n this.started = true\n }\n\n async stop (): Promise {\n this.started = false\n }\n\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async * findProviders (key: CID, options: RoutingOptions = {}): AsyncIterable {\n if (this.routers.length === 0) {\n throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n const self = this\n const seen = new PeerSet()\n\n for await (const peer of merge(\n ...self.routers.map(router => router.findProviders(key, options))\n )) {\n // the peer was yielded by a content router without multiaddrs and we\n // failed to load them\n if (peer == null) {\n continue\n }\n\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n }\n\n // deduplicate peers\n if (seen.has(peer.id)) {\n continue\n }\n\n seen.add(peer.id)\n\n yield peer\n }\n }\n\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide (key: CID, options: AbortOptions = {}): Promise {\n if (this.routers.length === 0) {\n throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n await Promise.all(this.routers.map(async (router) => {\n await router.provide(key, options)\n }))\n }\n\n /**\n * Store the given key/value pair in the available content routings\n */\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions): Promise {\n if (!this.isStarted()) {\n throw new CodeError(messages.NOT_STARTED_YET, codes.ERR_NODE_NOT_STARTED)\n }\n\n await Promise.all(this.routers.map(async (router) => {\n await router.put(key, value, options)\n }))\n }\n\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n if (!this.isStarted()) {\n throw new CodeError(messages.NOT_STARTED_YET, codes.ERR_NODE_NOT_STARTED)\n }\n\n return Promise.any(this.routers.map(async (router) => {\n return router.get(key, options)\n }))\n }\n}\n","/**\n * @packageDocumentation\n *\n * Takes an (async) iterable that emits promise-returning functions, invokes them in parallel up to the concurrency limit and emits the results as they become available, optionally in the same order as the input\n *\n * @example\n *\n * ```javascript\n * import parallel from 'it-parallel'\n * import all from 'it-all'\n * import delay from 'delay'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const input = [\n * async () => {\n * console.info('start 1')\n * await delay(500)\n *\n * console.info('end 1')\n * return 1\n * },\n * async () => {\n * console.info('start 2')\n * await delay(200)\n *\n * console.info('end 2')\n * return 2\n * },\n * async () => {\n * console.info('start 3')\n * await delay(100)\n *\n * console.info('end 3')\n * return 3\n * }\n * ]\n *\n * const result = await all(parallel(input, {\n * concurrency: 2\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [2, 3, 1]\n * ```\n *\n * If order is important, pass `ordered: true` as an option:\n *\n * ```javascript\n * const result = await all(parallel(input, {\n * concurrency: 2,\n * ordered: true\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [1, 2, 3]\n * ```\n */\n\nimport defer from 'p-defer'\n\ninterface Operation {\n done: boolean\n ok: boolean\n err: Error\n value: T\n}\n\nconst CustomEvent = globalThis.CustomEvent ?? Event\n\nexport interface ParallelOptions {\n /**\n * How many jobs to execute in parallel (default: )\n */\n concurrency?: number\n ordered?: boolean\n}\n\n/**\n * Takes an (async) iterator that emits promise-returning functions,\n * invokes them in parallel and emits the results as they become available but\n * in the same order as the input\n */\nexport default async function * parallel (source: Iterable<() => Promise> | AsyncIterable<() => Promise>, options: ParallelOptions = {}): AsyncGenerator {\n let concurrency = options.concurrency ?? Infinity\n\n if (concurrency < 1) {\n concurrency = Infinity\n }\n\n const ordered = options.ordered == null ? false : options.ordered\n const emitter = new EventTarget()\n\n const ops: Array> = []\n let slotAvailable = defer()\n let resultAvailable = defer()\n let sourceFinished = false\n let sourceErr: Error | undefined\n let opErred = false\n\n emitter.addEventListener('task-complete', () => {\n resultAvailable.resolve()\n })\n\n void Promise.resolve().then(async () => {\n try {\n for await (const task of source) {\n if (ops.length === concurrency) {\n slotAvailable = defer()\n await slotAvailable.promise\n }\n\n if (opErred) {\n break\n }\n\n const op: any = {\n done: false\n }\n ops.push(op)\n\n task()\n .then(result => {\n op.done = true\n op.ok = true\n op.value = result\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n }, err => {\n op.done = true\n op.err = err\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n })\n }\n\n sourceFinished = true\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n } catch (err: any) {\n sourceErr = err\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n }\n })\n\n function valuesAvailable (): boolean {\n if (ordered) {\n return ops[0]?.done\n }\n\n return Boolean(ops.find(op => op.done))\n }\n\n function * yieldOrderedValues (): Generator {\n while ((ops.length > 0) && ops[0].done) {\n const op = ops[0]\n ops.shift()\n\n if (op.ok) {\n yield op.value\n } else {\n // allow the source to exit\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n\n function * yieldUnOrderedValues (): Generator {\n // more values can become available while we wait for `yield`\n // to return control to this function\n while (valuesAvailable()) {\n for (let i = 0; i < ops.length; i++) {\n if (ops[i].done) {\n const op = ops[i]\n ops.splice(i, 1)\n i--\n\n if (op.ok) {\n yield op.value\n } else {\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n }\n }\n\n while (true) {\n if (!valuesAvailable()) {\n resultAvailable = defer()\n await resultAvailable.promise\n }\n\n if (sourceErr != null) {\n // the source threw an error, propagate it\n throw sourceErr\n }\n\n if (ordered) {\n yield * yieldOrderedValues()\n } else {\n yield * yieldUnOrderedValues()\n }\n\n if (sourceFinished && ops.length === 0) {\n // not waiting for any results and no more tasks so we are done\n break\n }\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport merge from 'it-merge'\nimport parallel from 'it-parallel'\nimport { codes, messages } from './errors.js'\nimport type { Logger, PeerId, PeerInfo, PeerRouting, PeerStore, RoutingOptions } from '@libp2p/interface'\nimport type { ComponentLogger } from '@libp2p/logger'\n\nexport interface PeerRoutingInit {\n routers?: PeerRouting[]\n}\n\nexport interface DefaultPeerRoutingComponents {\n peerId: PeerId\n peerStore: PeerStore\n logger: ComponentLogger\n}\n\nexport class DefaultPeerRouting implements PeerRouting {\n private readonly log: Logger\n private readonly peerId: PeerId\n private readonly peerStore: PeerStore\n private readonly routers: PeerRouting[]\n\n constructor (components: DefaultPeerRoutingComponents, init: PeerRoutingInit = {}) {\n this.log = components.logger.forComponent('libp2p:peer-routing')\n this.peerId = components.peerId\n this.peerStore = components.peerStore\n this.routers = init.routers ?? []\n }\n\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer (id: PeerId, options?: RoutingOptions): Promise {\n if (this.routers.length === 0) {\n throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n if (id.toString() === this.peerId.toString()) {\n throw new CodeError('Should not try to find self', codes.ERR_FIND_SELF)\n }\n\n const self = this\n const source = merge(\n ...this.routers.map(router => (async function * () {\n try {\n yield await router.findPeer(id, options)\n } catch (err) {\n self.log.error(err)\n }\n })())\n )\n\n for await (const peer of source) {\n if (peer == null) {\n continue\n }\n\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n }\n\n return peer\n }\n\n throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND)\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options: RoutingOptions = {}): AsyncIterable {\n if (this.routers.length === 0) {\n throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n const self = this\n const seen = new PeerSet()\n\n for await (const peer of parallel(\n async function * () {\n const source = merge(\n ...self.routers.map(router => router.getClosestPeers(key, options))\n )\n\n for await (let peer of source) {\n yield async () => {\n // find multiaddrs if they are missing\n if (peer.multiaddrs.length === 0) {\n try {\n peer = await self.findPeer(peer.id, {\n ...options,\n useCache: false\n })\n } catch (err) {\n self.log.error('could not find peer multiaddrs', err)\n return\n }\n }\n\n return peer\n }\n }\n }()\n )) {\n if (peer == null) {\n continue\n }\n\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n }\n\n // deduplicate peers\n if (seen.has(peer.id)) {\n continue\n }\n\n seen.add(peer.id)\n\n yield peer\n }\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport merge from 'merge-options'\nimport { codes } from './errors.js'\nimport type { IdentifyResult, Libp2pEvents, Logger, PeerUpdate, TypedEventTarget, PeerId, PeerStore, Topology } from '@libp2p/interface'\nimport type { ConnectionManager, StreamHandlerOptions, StreamHandlerRecord, Registrar, StreamHandler } from '@libp2p/interface-internal'\nimport type { ComponentLogger } from '@libp2p/logger'\n\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64\n\nexport interface RegistrarComponents {\n peerId: PeerId\n connectionManager: ConnectionManager\n peerStore: PeerStore\n events: TypedEventTarget\n logger: ComponentLogger\n}\n\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class DefaultRegistrar implements Registrar {\n private readonly log: Logger\n private readonly topologies: Map>\n private readonly handlers: Map\n private readonly components: RegistrarComponents\n\n constructor (components: RegistrarComponents) {\n this.log = components.logger.forComponent('libp2p:registrar')\n this.topologies = new Map()\n this.handlers = new Map()\n this.components = components\n\n this._onDisconnect = this._onDisconnect.bind(this)\n this._onPeerUpdate = this._onPeerUpdate.bind(this)\n this._onPeerIdentify = this._onPeerIdentify.bind(this)\n\n this.components.events.addEventListener('peer:disconnect', this._onDisconnect)\n this.components.events.addEventListener('peer:update', this._onPeerUpdate)\n this.components.events.addEventListener('peer:identify', this._onPeerIdentify)\n }\n\n getProtocols (): string[] {\n return Array.from(new Set([\n ...this.handlers.keys()\n ])).sort()\n }\n\n getHandler (protocol: string): StreamHandlerRecord {\n const handler = this.handlers.get(protocol)\n\n if (handler == null) {\n throw new CodeError(`No handler registered for protocol ${protocol}`, codes.ERR_NO_HANDLER_FOR_PROTOCOL)\n }\n\n return handler\n }\n\n getTopologies (protocol: string): Topology[] {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n return []\n }\n\n return [\n ...topologies.values()\n ]\n }\n\n /**\n * Registers the `handler` for each protocol\n */\n async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise {\n if (this.handlers.has(protocol)) {\n throw new CodeError(`Handler already registered for protocol ${protocol}`, codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED)\n }\n\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts)\n\n this.handlers.set(protocol, {\n handler,\n options\n })\n\n // Add new protocol to self protocols in the peer store\n await this.components.peerStore.merge(this.components.peerId, {\n protocols: [protocol]\n })\n }\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle (protocols: string | string[]): Promise {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols]\n\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol)\n })\n\n // Update self protocols in the peer store\n await this.components.peerStore.patch(this.components.peerId, {\n protocols: this.getProtocols()\n })\n }\n\n /**\n * Register handlers for a set of multicodecs given\n */\n async register (protocol: string, topology: Topology): Promise {\n if (topology == null) {\n throw new CodeError('invalid topology', codes.ERR_INVALID_PARAMETERS)\n }\n\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n\n let topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n topologies = new Map()\n this.topologies.set(protocol, topologies)\n }\n\n topologies.set(id, topology)\n\n return id\n }\n\n /**\n * Unregister topology\n */\n unregister (id: string): void {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id)\n\n if (topologies.size === 0) {\n this.topologies.delete(protocol)\n }\n }\n }\n }\n\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect (evt: CustomEvent): void {\n const remotePeer = evt.detail\n\n void this.components.peerStore.get(remotePeer)\n .then(peer => {\n for (const protocol of peer.protocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect?.(remotePeer)\n }\n }\n })\n .catch(err => {\n if (err.code === codes.ERR_NOT_FOUND) {\n // peer has not completed identify so they are not in the peer store\n return\n }\n\n this.log.error('could not inform topologies of disconnecting peer %p', remotePeer, err)\n })\n }\n\n /**\n * When a peer is updated, if they have removed supported protocols notify any\n * topologies interested in the removed protocols.\n */\n _onPeerUpdate (evt: CustomEvent): void {\n const { peer, previous } = evt.detail\n const removed = (previous?.protocols ?? []).filter(protocol => !peer.protocols.includes(protocol))\n\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect?.(peer.id)\n }\n }\n }\n\n /**\n * After identify has completed and we have received the list of supported\n * protocols, notify any topologies interested in those protocols.\n */\n _onPeerIdentify (evt: CustomEvent): void {\n const protocols = evt.detail.protocols\n const connection = evt.detail.connection\n const peerId = evt.detail.peerId\n\n for (const protocol of protocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n if (connection.transient && topology.notifyOnTransient !== true) {\n continue\n }\n\n topology.onConnect?.(peerId, connection)\n }\n }\n }\n}\n","import type { Metric, Metrics } from '@libp2p/interface'\n\nexport interface TrackedMapInit {\n name: string\n metrics: Metrics\n}\n\nclass TrackedMap extends Map {\n private readonly metric: Metric\n\n constructor (init: TrackedMapInit) {\n super()\n\n const { name, metrics } = init\n\n this.metric = metrics.registerMetric(name)\n this.updateComponentMetric()\n }\n\n set (key: K, value: V): this {\n super.set(key, value)\n this.updateComponentMetric()\n return this\n }\n\n delete (key: K): boolean {\n const deleted = super.delete(key)\n this.updateComponentMetric()\n return deleted\n }\n\n clear (): void {\n super.clear()\n this.updateComponentMetric()\n }\n\n private updateComponentMetric (): void {\n this.metric.update(this.size)\n }\n}\n\nexport interface CreateTrackedMapInit {\n /**\n * The metric name to use\n */\n name: string\n\n /**\n * A metrics implementation\n */\n metrics?: Metrics\n}\n\nexport function trackedMap (config: CreateTrackedMapInit): Map {\n const { name, metrics } = config\n let map: Map\n\n if (metrics != null) {\n map = new TrackedMap({ name, metrics })\n } else {\n map = new Map()\n }\n\n return map\n}\n","import { CodeError, FaultTolerance } from '@libp2p/interface'\nimport { trackedMap } from '@libp2p/utils/tracked-map'\nimport { codes } from './errors.js'\nimport type { Libp2pEvents, AbortOptions, ComponentLogger, Logger, Connection, TypedEventTarget, Metrics, Startable, Listener, Transport, Upgrader } from '@libp2p/interface'\nimport type { AddressManager, TransportManager } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface TransportManagerInit {\n faultTolerance?: FaultTolerance\n}\n\nexport interface DefaultTransportManagerComponents {\n metrics?: Metrics\n addressManager: AddressManager\n upgrader: Upgrader\n events: TypedEventTarget\n logger: ComponentLogger\n}\n\nexport class DefaultTransportManager implements TransportManager, Startable {\n private readonly log: Logger\n private readonly components: DefaultTransportManagerComponents\n private readonly transports: Map\n private readonly listeners: Map\n private readonly faultTolerance: FaultTolerance\n private started: boolean\n\n constructor (components: DefaultTransportManagerComponents, init: TransportManagerInit = {}) {\n this.log = components.logger.forComponent('libp2p:transports')\n this.components = components\n this.started = false\n this.transports = new Map()\n this.listeners = trackedMap({\n name: 'libp2p_transport_manager_listeners',\n metrics: this.components.metrics\n })\n this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL\n }\n\n /**\n * Adds a `Transport` to the manager\n */\n add (transport: Transport): void {\n const tag = transport[Symbol.toStringTag]\n\n if (tag == null) {\n throw new CodeError('Transport must have a valid tag', codes.ERR_INVALID_KEY)\n }\n\n if (this.transports.has(tag)) {\n throw new CodeError(`There is already a transport with the tag ${tag}`, codes.ERR_DUPLICATE_TRANSPORT)\n }\n\n this.log('adding transport %s', tag)\n\n this.transports.set(tag, transport)\n\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, [])\n }\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n }\n\n async afterStart (): Promise {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.addressManager.getListenAddrs()\n\n await this.listen(addrs)\n }\n\n /**\n * Stops all listeners\n */\n async stop (): Promise {\n const tasks = []\n for (const [key, listeners] of this.listeners) {\n this.log('closing listeners for %s', key)\n while (listeners.length > 0) {\n const listener = listeners.pop()\n\n if (listener == null) {\n continue\n }\n\n tasks.push(listener.close())\n }\n }\n\n await Promise.all(tasks)\n this.log('all listeners closed')\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, [])\n }\n\n this.started = false\n }\n\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial (ma: Multiaddr, options?: AbortOptions): Promise {\n const transport = this.transportForMultiaddr(ma)\n\n if (transport == null) {\n throw new CodeError(`No transport available for address ${String(ma)}`, codes.ERR_TRANSPORT_UNAVAILABLE)\n }\n\n try {\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.upgrader\n })\n } catch (err: any) {\n if (err.code == null) {\n err.code = codes.ERR_TRANSPORT_DIAL_FAILED\n }\n\n throw err\n }\n }\n\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs (): Multiaddr[] {\n let addrs: Multiaddr[] = []\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()]\n }\n }\n return addrs\n }\n\n /**\n * Returns all the transports instances\n */\n getTransports (): Transport[] {\n return Array.of(...this.transports.values())\n }\n\n /**\n * Returns all the listener instances\n */\n getListeners (): Listener[] {\n return Array.of(...this.listeners.values()).flat()\n }\n\n /**\n * Finds a transport that matches the given Multiaddr\n */\n transportForMultiaddr (ma: Multiaddr): Transport | undefined {\n for (const transport of this.transports.values()) {\n const addrs = transport.filter([ma])\n\n if (addrs.length > 0) {\n return transport\n }\n }\n }\n\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen (addrs: Multiaddr[]): Promise {\n if (!this.isStarted()) {\n throw new CodeError('Not started', codes.ERR_NODE_NOT_STARTED)\n }\n\n if (addrs == null || addrs.length === 0) {\n this.log('no addresses were provided for listening, this node is dial only')\n return\n }\n\n const couldNotListen = []\n\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.filter(addrs)\n const tasks = []\n\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n this.log('creating listener for %s on %a', key, addr)\n const listener = transport.createListener({\n upgrader: this.components.upgrader\n })\n\n let listeners: Listener[] = this.listeners.get(key) ?? []\n\n if (listeners == null) {\n listeners = []\n this.listeners.set(key, listeners)\n }\n\n listeners.push(listener)\n\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.components.events.safeDispatchEvent('transport:listening', {\n detail: listener\n })\n })\n listener.addEventListener('close', () => {\n const index = listeners.findIndex(l => l === listener)\n\n // remove the listener\n listeners.splice(index, 1)\n\n this.components.events.safeDispatchEvent('transport:close', {\n detail: listener\n })\n })\n\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr))\n }\n\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key)\n continue\n }\n\n const results = await Promise.allSettled(tasks)\n // If we are listening on at least 1 address, succeed.\n // TODO: we should look at adding a retry (`p-retry`) here to better support\n // listening on remote addresses as they may be offline. We could then potentially\n // just wait for any (`p-any`) listener to succeed on each transport before returning\n const isListening = results.find(r => r.status === 'fulfilled')\n if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) {\n throw new CodeError(`Transport (${key}) could not listen on any available address`, codes.ERR_NO_VALID_ADDRESSES)\n }\n }\n\n // If no transports were able to listen, throw an error. This likely\n // means we were given addresses we do not have transports for\n if (couldNotListen.length === this.transports.size) {\n const message = `no valid addresses were provided for transports [${couldNotListen.join(', ')}]`\n if (this.faultTolerance === FaultTolerance.FATAL_ALL) {\n throw new CodeError(message, codes.ERR_NO_VALID_ADDRESSES)\n }\n this.log(`libp2p in dial mode only: ${message}`)\n }\n }\n\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove (key: string): Promise {\n const listeners = this.listeners.get(key) ?? []\n this.log.trace('removing transport %s', key)\n\n // Close any running listeners\n const tasks = []\n this.log.trace('closing listeners for %s', key)\n while (listeners.length > 0) {\n const listener = listeners.pop()\n\n if (listener == null) {\n continue\n }\n\n tasks.push(listener.close())\n }\n await Promise.all(tasks)\n\n this.transports.delete(key)\n this.listeners.delete(key)\n }\n\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll (): Promise {\n const tasks = []\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key))\n }\n\n await Promise.all(tasks)\n }\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","export const PROTOCOL_ID = '/multistream/1.0.0'\n\n// Conforming to go-libp2p\n// See https://github.com/multiformats/go-multistream/blob/master/multistream.go#L297\nexport const MAX_PROTOCOL_LENGTH = 1024\n","import { CodeError } from '@libp2p/interface'\nimport { type Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { AbortOptions, LoggerOptions } from '@libp2p/interface'\nimport type { LengthPrefixedStream } from 'it-length-prefixed-stream'\nimport type { Duplex, Source } from 'it-stream-types'\n\nconst NewLine = uint8ArrayFromString('\\n')\n\n/**\n * `write` encodes and writes a single buffer\n */\nexport async function write (writer: LengthPrefixedStream, Source>>, buffer: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise {\n await writer.write(buffer, options)\n}\n\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport async function writeAll (writer: LengthPrefixedStream, Source>>, buffers: Uint8Array[], options?: AbortOptions): Promise {\n await writer.writeV(buffers, options)\n}\n\n/**\n * Read a length-prefixed buffer from the passed stream, stripping the final newline character\n */\nexport async function read (reader: LengthPrefixedStream, Source>>, options: AbortOptions & LoggerOptions): Promise {\n const buf = await reader.read(options)\n\n if (buf.byteLength === 0 || buf.get(buf.byteLength - 1) !== NewLine[0]) {\n options.log.error('Invalid mss message - missing newline', buf)\n throw new CodeError('missing newline', 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n return buf.sublist(0, -1) // Remove newline\n}\n\n/**\n * Read a length-prefixed string from the passed stream, stripping the final newline character\n */\nexport async function readString (reader: LengthPrefixedStream, Source>>, options: AbortOptions & LoggerOptions): Promise {\n const buf = await read(reader, options)\n\n return uint8ArrayToString(buf.subarray())\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { encode } from 'it-length-prefixed'\nimport { lpStream } from 'it-length-prefixed-stream'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { MAX_PROTOCOL_LENGTH, PROTOCOL_ID } from './constants.js'\nimport * as multistream from './multistream.js'\nimport type { MultistreamSelectInit, ProtocolStream } from './index.js'\nimport type { Duplex } from 'it-stream-types'\n\n/**\n * Handle multistream protocol selections for the given list of protocols.\n *\n * Note that after a protocol is handled `listener` can no longer be used.\n *\n * @param stream - A duplex iterable stream to listen on\n * @param protocols - A list of protocols (or single protocol) that this listener is able to speak.\n * @param options - an options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex({\n * async onStream (muxedStream) {\n * // mss.handle(handledProtocols)\n * // Returns selected stream and protocol\n * const { stream, protocol } = await mss.handle(muxedStream, [\n * '/ipfs-dht/1.0.0',\n * '/ipfs-bitswap/1.0.0'\n * ])\n *\n * // Typically here we'd call the handler function that was registered in\n * // libp2p for the given protocol:\n * // e.g. handlers[protocol].handler(stream)\n * //\n * // If protocol was /ipfs-dht/1.0.0 it might do something like this:\n * // try {\n * // await pipe(\n * // dhtStream,\n * // source => (async function * () {\n * // for await (const chunk of source)\n * // // Incoming DHT data -> process and yield to respond\n * // })(),\n * // dhtStream\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * }\n * })\n * ```\n */\nexport async function handle > (stream: Stream, protocols: string | string[], options: MultistreamSelectInit): Promise> {\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n options.log.trace('handle: available protocols %s', protocols)\n\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH,\n maxLengthLength: 2 // 2 bytes is enough to length-prefix MAX_PROTOCOL_LENGTH\n })\n\n while (true) {\n options.log.trace('handle: reading incoming string')\n const protocol = await multistream.readString(lp, options)\n options.log.trace('handle: read \"%s\"', protocol)\n\n if (protocol === PROTOCOL_ID) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol)\n await multistream.write(lp, uint8ArrayFromString(`${PROTOCOL_ID}\\n`), options)\n options.log.trace('handle: responded with \"%s\" for \"%s\"', PROTOCOL_ID, protocol)\n continue\n }\n\n if (protocols.includes(protocol)) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', protocol, protocol)\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options)\n options.log.trace('handle: responded with \"%s\" for \"%s\"', protocol, protocol)\n\n return { stream: lp.unwrap(), protocol }\n }\n\n if (protocol === 'ls') {\n // \\n\\n\\n\n const protos = new Uint8ArrayList(\n ...protocols.map(p => encode.single(uint8ArrayFromString(`${p}\\n`))),\n uint8ArrayFromString('\\n')\n )\n\n options.log.trace('handle: respond with \"%s\" for %s', protocols, protocol)\n await multistream.write(lp, protos, options)\n options.log.trace('handle: responded with \"%s\" for %s', protocols, protocol)\n continue\n }\n\n options.log('handle: respond with \"na\" for \"%s\"', protocol)\n await multistream.write(lp, uint8ArrayFromString('na\\n'), options)\n options.log('handle: responded with \"na\" for \"%s\"', protocol)\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { lpStream } from 'it-length-prefixed-stream'\nimport pDefer from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { MAX_PROTOCOL_LENGTH } from './constants.js'\nimport * as multistream from './multistream.js'\nimport { PROTOCOL_ID } from './index.js'\nimport type { MultistreamSelectInit, ProtocolStream } from './index.js'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface SelectStream extends Duplex {\n readStatus?: string\n closeWrite?(options?: AbortOptions): Promise\n closeRead?(options?: AbortOptions): Promise\n close?(options?: AbortOptions): Promise\n}\n\n/**\n * Negotiate a protocol to use from a list of protocols.\n *\n * @param stream - A duplex iterable stream to dial on\n * @param protocols - A list of protocols (or single protocol) to negotiate with. Protocols are attempted in order until a match is made.\n * @param options - An options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`.\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex()\n * const muxedStream = muxer.newStream()\n *\n * // mss.select(protocol(s))\n * // Select from one of the passed protocols (in priority order)\n * // Returns selected stream and protocol\n * const { stream: dhtStream, protocol } = await mss.select(muxedStream, [\n * // This might just be different versions of DHT, but could be different impls\n * '/ipfs-dht/2.0.0', // Most of the time this will probably just be one item.\n * '/ipfs-dht/1.0.0'\n * ])\n *\n * // Typically this stream will be passed back to the caller of libp2p.dialProtocol\n * //\n * // ...it might then do something like this:\n * // try {\n * // await pipe(\n * // [uint8ArrayFromString('Some DHT data')]\n * // dhtStream,\n * // async source => {\n * // for await (const chunk of source)\n * // // DHT response data\n * // }\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * ```\n */\nexport async function select (stream: Stream, protocols: string | string[], options: MultistreamSelectInit): Promise> {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols]\n\n if (protocols.length === 1 && options.negotiateFully === false) {\n return optimisticSelect(stream, protocols[0], options)\n }\n\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n })\n const protocol = protocols.shift()\n\n if (protocol == null) {\n throw new Error('At least one protocol must be specified')\n }\n\n options.log.trace('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol)\n const p1 = uint8ArrayFromString(`${PROTOCOL_ID}\\n`)\n const p2 = uint8ArrayFromString(`${protocol}\\n`)\n await multistream.writeAll(lp, [p1, p2], options)\n\n options.log.trace('select: reading multistream-select header')\n let response = await multistream.readString(lp, options)\n options.log.trace('select: read \"%s\"', response)\n\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n options.log.trace('select: reading protocol response')\n response = await multistream.readString(lp, options)\n options.log.trace('select: read \"%s\"', response)\n }\n\n // We're done\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol }\n }\n\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n options.log.trace('select: write \"%s\"', protocol)\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options)\n options.log.trace('select: reading protocol response')\n const response = await multistream.readString(lp, options)\n options.log.trace('select: read \"%s\" for \"%s\"', response, protocol)\n\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol }\n }\n }\n\n throw new CodeError('protocol selection failed', 'ERR_UNSUPPORTED_PROTOCOL')\n}\n\n/**\n * Optimistically negotiates a protocol.\n *\n * It *does not* block writes waiting for the other end to respond. Instead, it\n * simply assumes the negotiation went successfully and starts writing data.\n *\n * Use when it is known that the receiver supports the desired protocol.\n */\nfunction optimisticSelect (stream: Stream, protocol: string, options: MultistreamSelectInit): ProtocolStream {\n const originalSink = stream.sink.bind(stream)\n const originalSource = stream.source\n\n let negotiated = false\n let negotiating = false\n const doneNegotiating = pDefer()\n\n let sentProtocol = false\n let sendingProtocol = false\n const doneSendingProtocol = pDefer()\n\n let readProtocol = false\n let readingProtocol = false\n const doneReadingProtocol = pDefer()\n\n const lp = lpStream({\n sink: originalSink,\n source: originalSource\n }, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n })\n\n stream.sink = async source => {\n const { sink } = lp.unwrap()\n\n await sink(async function * () {\n let sentData = false\n\n for await (const buf of source) {\n // started reading before the source yielded, wait for protocol send\n if (sendingProtocol) {\n await doneSendingProtocol.promise\n }\n\n // writing before reading, send the protocol and the first chunk of data\n if (!sentProtocol) {\n sendingProtocol = true\n\n options.log.trace('optimistic: write [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength)\n\n const protocolString = `${protocol}\\n`\n\n // send protocols in first chunk of data written to transport\n yield new Uint8ArrayList(\n Uint8Array.from([19]), // length of PROTOCOL_ID plus newline\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`),\n varint.encode(protocolString.length),\n uint8ArrayFromString(protocolString),\n buf\n ).subarray()\n\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength)\n\n sentProtocol = true\n sendingProtocol = false\n doneSendingProtocol.resolve()\n\n // read the negotiation response but don't block more sending\n negotiate()\n .catch(err => {\n options.log.error('could not finish optimistic protocol negotiation of %s', protocol, err)\n })\n } else {\n yield buf\n }\n\n sentData = true\n }\n\n // special case - the source passed to the sink has ended but we didn't\n // negotiated the protocol yet so do it now\n if (!sentData) {\n await negotiate()\n }\n }())\n }\n\n async function negotiate (): Promise {\n if (negotiating) {\n options.log.trace('optimistic: already negotiating %s stream', protocol)\n await doneNegotiating.promise\n return\n }\n\n negotiating = true\n\n try {\n // we haven't sent the protocol yet, send it now\n if (!sentProtocol) {\n options.log.trace('optimistic: doing send protocol for %s stream', protocol)\n await doSendProtocol()\n }\n\n // if we haven't read the protocol response yet, do it now\n if (!readProtocol) {\n options.log.trace('optimistic: doing read protocol for %s stream', protocol)\n await doReadProtocol()\n }\n } finally {\n negotiating = false\n negotiated = true\n doneNegotiating.resolve()\n }\n }\n\n async function doSendProtocol (): Promise {\n if (sendingProtocol) {\n await doneSendingProtocol.promise\n return\n }\n\n sendingProtocol = true\n\n try {\n options.log.trace('optimistic: write [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol)\n await lp.writeV([\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`),\n uint8ArrayFromString(`${protocol}\\n`)\n ])\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol)\n } finally {\n sentProtocol = true\n sendingProtocol = false\n doneSendingProtocol.resolve()\n }\n }\n\n async function doReadProtocol (): Promise {\n if (readingProtocol) {\n await doneReadingProtocol.promise\n return\n }\n\n readingProtocol = true\n\n try {\n options.log.trace('optimistic: reading multistream select header')\n let response = await multistream.readString(lp, options)\n options.log.trace('optimistic: read multistream select header \"%s\"', response)\n\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(lp, options)\n }\n\n options.log.trace('optimistic: read protocol \"%s\", expecting \"%s\"', response, protocol)\n\n if (response !== protocol) {\n throw new CodeError('protocol selection failed', 'ERR_UNSUPPORTED_PROTOCOL')\n }\n } finally {\n readProtocol = true\n readingProtocol = false\n doneReadingProtocol.resolve()\n }\n }\n\n stream.source = (async function * () {\n // make sure we've done protocol negotiation before we read stream data\n await negotiate()\n\n options.log.trace('optimistic: reading data from \"%s\" stream', protocol)\n yield * lp.unwrap().source\n })()\n\n if (stream.closeRead != null) {\n const originalCloseRead = stream.closeRead.bind(stream)\n\n stream.closeRead = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the readable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close read', err)\n })\n }\n\n // protocol has been negotiated, ok to close the readable end\n await originalCloseRead(opts)\n }\n }\n\n if (stream.closeWrite != null) {\n const originalCloseWrite = stream.closeWrite.bind(stream)\n\n stream.closeWrite = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the writable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close write', err)\n })\n }\n\n // protocol has been negotiated, ok to close the writable end\n await originalCloseWrite(opts)\n }\n }\n\n if (stream.close != null) {\n const originalClose = stream.close.bind(stream)\n\n stream.close = async (opts) => {\n // if we are in the process of negotiation, let it finish before closing\n // because we may have unsent early data\n const tasks = []\n\n if (sendingProtocol) {\n tasks.push(doneSendingProtocol.promise)\n }\n\n if (readingProtocol) {\n tasks.push(doneReadingProtocol.promise)\n }\n\n if (tasks.length > 0) {\n // let the in-flight protocol negotiation finish gracefully\n await raceSignal(\n Promise.all(tasks),\n opts?.signal\n )\n } else {\n // no protocol negotiation attempt has occurred so don't start one\n negotiated = true\n negotiating = false\n doneNegotiating.resolve()\n }\n\n // protocol has been negotiated, ok to close the writable end\n await originalClose(opts)\n }\n }\n\n return {\n stream,\n protocol\n }\n}\n","import type { AbortOptions, Logger } from '../index.js'\nimport type { PeerId } from '../peer-id/index.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Duplex, Source } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface ConnectionTimeline {\n /**\n * When the connection was opened\n */\n open: number\n\n /**\n * When the MultiaddrConnection was upgraded to a Connection - e.g. the type\n * of connection encryption and multiplexing was negotiated.\n */\n upgraded?: number\n\n /**\n * When the connection was closed.\n */\n close?: number\n}\n\n/**\n * Outbound connections are opened by the local node, inbound streams are opened by the remote\n */\nexport type Direction = 'inbound' | 'outbound'\n\nexport interface StreamTimeline {\n /**\n * A timestamp of when the stream was opened\n */\n open: number\n\n /**\n * A timestamp of when the stream was closed for both reading and writing\n */\n close?: number\n\n /**\n * A timestamp of when the stream was closed for reading\n */\n closeRead?: number\n\n /**\n * A timestamp of when the stream was closed for writing\n */\n closeWrite?: number\n\n /**\n * A timestamp of when the stream was reset\n */\n reset?: number\n\n /**\n * A timestamp of when the stream was aborted\n */\n abort?: number\n}\n\n/**\n * The states a stream can be in\n */\nexport type StreamStatus = 'open' | 'closing' | 'closed' | 'aborted' | 'reset'\n\n/**\n * The states the readable end of a stream can be in\n *\n * ready - the readable end is ready for reading\n * closing - the readable end is closing\n * closed - the readable end has closed\n */\nexport type ReadStatus = 'ready' | 'closing' | 'closed'\n\n/**\n * The states the writable end of a stream can be in\n *\n * ready - the writable end is ready for writing\n * writing - the writable end is in the process of being written to\n * done - the source passed to the `.sink` function yielded all values without error\n * closing - the writable end is closing\n * closed - the writable end has closed\n */\nexport type WriteStatus = 'ready' | 'writing' | 'done' | 'closing' | 'closed'\n\n/**\n * A Stream is a data channel between two peers that\n * can be written to and read from at both ends.\n *\n * It may be encrypted and multiplexed depending on the\n * configuration of the nodes.\n */\nexport interface Stream extends Duplex, Source, Promise> {\n /**\n * Closes the stream for **reading** *and* **writing**.\n *\n * Any buffered data in the source can still be consumed and the stream will end normally.\n *\n * This will cause a `CLOSE` message to be sent to the remote, *unless* the sink has already ended.\n *\n * The sink and the source will return normally.\n */\n close(options?: AbortOptions): Promise\n\n /**\n * Closes the stream for **reading**. If iterating over the source of this stream in a `for await of` loop, it will return (exit the loop) after any buffered data has been consumed.\n *\n * This function is called automatically by the muxer when it receives a `CLOSE` message from the remote.\n *\n * The source will return normally, the sink will continue to consume.\n */\n closeRead(options?: AbortOptions): Promise\n\n /**\n * Closes the stream for **writing**. If iterating over the source of this stream in a `for await of` loop, it will return (exit the loop) after any buffered data has been consumed.\n *\n * The source will return normally, the sink will continue to consume.\n */\n closeWrite(options?: AbortOptions): Promise\n\n /**\n * Closes the stream for **reading** *and* **writing**. This should be called when a *local error* has occurred.\n *\n * Note, if called without an error any buffered data in the source can still be consumed and the stream will end normally.\n *\n * This will cause a `RESET` message to be sent to the remote, *unless* the sink has already ended.\n *\n * The sink will return and the source will throw if an error is passed or return normally if not.\n */\n abort(err: Error): void\n\n /**\n * Unique identifier for a stream. Identifiers are not unique across muxers.\n */\n id: string\n\n /**\n * Outbound streams are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the stream\n */\n timeline: StreamTimeline\n\n /**\n * The protocol negotiated for this stream\n */\n protocol?: string\n\n /**\n * User defined stream metadata\n */\n metadata: Record\n\n /**\n * The current status of the stream\n */\n status: StreamStatus\n\n /**\n * The current status of the readable end of the stream\n */\n readStatus: ReadStatus\n\n /**\n * The current status of the writable end of the stream\n */\n writeStatus: WriteStatus\n\n /**\n * The stream logger\n */\n log: Logger\n}\n\nexport interface NewStreamOptions extends AbortOptions {\n /**\n * If specified, and no handler has been registered with the registrar for the\n * successfully negotiated protocol, use this as the max outbound stream limit\n * for the protocol\n */\n maxOutboundStreams?: number\n\n /**\n * Opt-in to running over a transient connection - one that has time/data limits\n * placed on it.\n *\n * @default false\n */\n runOnTransientConnection?: boolean\n\n /**\n * By default when negotiating a protocol the dialer writes then protocol name\n * then reads the response.\n *\n * When a only a single protocol is being negotiated on an outbound stream,\n * and the stream is written to before being read from, we can optimistically\n * write the protocol name and the first chunk of data together in the first\n * message.\n *\n * Reading and handling the protocol response is done asynchronously, which\n * means we can skip a round trip on writing to newly opened streams which\n * significantly reduces the time-to-first-byte on a stream.\n *\n * The side-effect of this is that the underlying stream won't negotiate the\n * protocol until either data is written to or read from the stream so it will\n * not be opened on the remote until this is done.\n *\n * Pass `false` here to optimistically write the protocol name and first chunk\n * of data in the first message.\n *\n * If multiple protocols are being negotiated, negotiation is always completed\n * in full before the stream is returned so this option has no effect.\n *\n * @default true\n */\n negotiateFully?: boolean\n}\n\nexport type ConnectionStatus = 'open' | 'closing' | 'closed'\n\n/**\n * A Connection is a high-level representation of a connection\n * to a remote peer that may have been secured by encryption and\n * multiplexed, depending on the configuration of the nodes\n * between which the connection is made.\n */\nexport interface Connection {\n /**\n * The unique identifier for this connection\n */\n id: string\n\n /**\n * The address of the remote end of the connection\n */\n remoteAddr: Multiaddr\n\n /**\n * The id of the peer at the remote end of the connection\n */\n remotePeer: PeerId\n\n /**\n * A list of tags applied to this connection\n */\n tags: string[]\n\n /**\n * A list of open streams on this connection\n */\n streams: Stream[]\n\n /**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the connection\n */\n timeline: ConnectionTimeline\n\n /**\n * The multiplexer negotiated for this connection\n */\n multiplexer?: string\n\n /**\n * The encryption protocol negotiated for this connection\n */\n encryption?: string\n\n /**\n * The current status of the connection\n */\n status: ConnectionStatus\n\n /**\n * A transient connection is one that is not expected to be open for very long\n * or one that cannot transfer very much data, such as one being used as a\n * circuit relay connection. Protocols need to explicitly opt-in to being run\n * over transient connections.\n */\n transient: boolean\n\n /**\n * Create a new stream on this connection and negotiate one of the passed protocols\n */\n newStream(protocols: string | string[], options?: NewStreamOptions): Promise\n\n /**\n * Gracefully close the connection. All queued data will be written to the\n * underlying transport.\n */\n close(options?: AbortOptions): Promise\n\n /**\n * Immediately close the connection, any queued data will be discarded\n */\n abort(err: Error): void\n\n /**\n * The connection logger\n */\n log: Logger\n}\n\nexport const connectionSymbol = Symbol.for('@libp2p/connection')\n\nexport function isConnection (other: any): other is Connection {\n return other != null && Boolean(other[connectionSymbol])\n}\n\nexport interface ConnectionProtector {\n /**\n * Takes a given Connection and creates a private encryption stream\n * between its two peers from the PSK the Protector instance was\n * created with.\n */\n protect(connection: MultiaddrConnection): Promise\n}\n\nexport interface MultiaddrConnectionTimeline {\n /**\n * When the connection was opened\n */\n open: number\n\n /**\n * When the MultiaddrConnection was upgraded to a Connection - the type of\n * connection encryption and multiplexing was negotiated.\n */\n upgraded?: number\n\n /**\n * When the connection was closed.\n */\n close?: number\n}\n\n/**\n * A MultiaddrConnection is returned by transports after dialing\n * a peer. It is a low-level primitive and is the raw connection\n * without encryption or stream multiplexing.\n */\nexport interface MultiaddrConnection extends Duplex> {\n /**\n * Gracefully close the connection. All queued data will be written to the\n * underlying transport.\n */\n close(options?: AbortOptions): Promise\n\n /**\n * Immediately close the connection, any queued data will be discarded\n */\n abort(err: Error): void\n\n /**\n * The address of the remote end of the connection\n */\n remoteAddr: Multiaddr\n\n /**\n * When connection lifecycle events occurred\n */\n timeline: MultiaddrConnectionTimeline\n\n /**\n * The multiaddr connection logger\n */\n log: Logger\n}\n","import { connectionSymbol, CodeError, setMaxListeners } from '@libp2p/interface'\nimport type { AbortOptions, Logger, ComponentLogger, Direction, Connection, Stream, ConnectionTimeline, ConnectionStatus, NewStreamOptions, PeerId } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst CLOSE_TIMEOUT = 500\n\ninterface ConnectionInit {\n remoteAddr: Multiaddr\n remotePeer: PeerId\n newStream(protocols: string[], options?: AbortOptions): Promise\n close(options?: AbortOptions): Promise\n abort(err: Error): void\n getStreams(): Stream[]\n status: ConnectionStatus\n direction: Direction\n timeline: ConnectionTimeline\n multiplexer?: string\n encryption?: string\n transient?: boolean\n logger: ComponentLogger\n}\n\n/**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\nexport class ConnectionImpl implements Connection {\n /**\n * Connection identifier.\n */\n public readonly id: string\n\n /**\n * Observed multiaddr of the remote peer\n */\n public readonly remoteAddr: Multiaddr\n\n /**\n * Remote peer id\n */\n public readonly remotePeer: PeerId\n\n public direction: Direction\n public timeline: ConnectionTimeline\n public multiplexer?: string\n public encryption?: string\n public status: ConnectionStatus\n public transient: boolean\n public readonly log: Logger\n\n /**\n * User provided tags\n *\n */\n public tags: string[]\n\n /**\n * Reference to the new stream function of the multiplexer\n */\n private readonly _newStream: (protocols: string[], options?: NewStreamOptions) => Promise\n\n /**\n * Reference to the close function of the raw connection\n */\n private readonly _close: (options?: AbortOptions) => Promise\n\n private readonly _abort: (err: Error) => void\n\n /**\n * Reference to the getStreams function of the muxer\n */\n private readonly _getStreams: () => Stream[]\n\n /**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\n constructor (init: ConnectionInit) {\n const { remoteAddr, remotePeer, newStream, close, abort, getStreams } = init\n\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`\n this.remoteAddr = remoteAddr\n this.remotePeer = remotePeer\n this.direction = init.direction\n this.status = 'open'\n this.timeline = init.timeline\n this.multiplexer = init.multiplexer\n this.encryption = init.encryption\n this.transient = init.transient ?? false\n this.log = init.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`)\n\n if (this.remoteAddr.getPeerId() == null) {\n this.remoteAddr = this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)\n }\n\n this._newStream = newStream\n this._close = close\n this._abort = abort\n this._getStreams = getStreams\n this.tags = []\n }\n\n readonly [Symbol.toStringTag] = 'Connection'\n\n readonly [connectionSymbol] = true\n\n /**\n * Get all the streams of the muxer\n */\n get streams (): Stream[] {\n return this._getStreams()\n }\n\n /**\n * Create a new stream from this connection\n */\n async newStream (protocols: string | string[], options?: NewStreamOptions): Promise {\n if (this.status === 'closing') {\n throw new CodeError('the connection is being closed', 'ERR_CONNECTION_BEING_CLOSED')\n }\n\n if (this.status === 'closed') {\n throw new CodeError('the connection is closed', 'ERR_CONNECTION_CLOSED')\n }\n\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n if (this.transient && options?.runOnTransientConnection !== true) {\n throw new CodeError('Cannot open protocol stream on transient connection', 'ERR_TRANSIENT_CONNECTION')\n }\n\n const stream = await this._newStream(protocols, options)\n\n stream.direction = 'outbound'\n\n return stream\n }\n\n /**\n * Close the connection\n */\n async close (options: AbortOptions = {}): Promise {\n if (this.status === 'closed' || this.status === 'closing') {\n return\n }\n\n this.log('closing connection to %a', this.remoteAddr)\n\n this.status = 'closing'\n\n if (options.signal == null) {\n const signal = AbortSignal.timeout(CLOSE_TIMEOUT)\n setMaxListeners(Infinity, signal)\n\n options = {\n ...options,\n signal\n }\n }\n\n try {\n this.log.trace('closing all streams')\n\n // close all streams gracefully - this can throw if we're not multiplexed\n await Promise.all(\n this.streams.map(async s => s.close(options))\n )\n\n this.log.trace('closing underlying transport')\n\n // close raw connection\n await this._close(options)\n\n this.log.trace('updating timeline with close time')\n\n this.status = 'closed'\n this.timeline.close = Date.now()\n } catch (err: any) {\n this.log.error('error encountered during graceful close of connection to %a', this.remoteAddr, err)\n this.abort(err)\n }\n }\n\n abort (err: Error): void {\n this.log.error('aborting connection to %a due to error', this.remoteAddr, err)\n\n this.status = 'closing'\n this.streams.forEach(s => { s.abort(err) })\n\n this.log.error('all streams aborted', this.streams.length)\n\n // Abort raw connection\n this._abort(err)\n\n this.timeline.close = Date.now()\n this.status = 'closed'\n }\n}\n\nexport function createConnection (init: ConnectionInit): Connection {\n return new ConnectionImpl(init)\n}\n","import { CodeError, ERR_TIMEOUT, setMaxListeners } from '@libp2p/interface'\nimport * as mss from '@libp2p/multistream-select'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { createConnection } from './connection/index.js'\nimport { INBOUND_UPGRADE_TIMEOUT } from './connection-manager/constants.js'\nimport { codes } from './errors.js'\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'\nimport type { Libp2pEvents, AbortOptions, ComponentLogger, MultiaddrConnection, Connection, Stream, ConnectionProtector, NewStreamOptions, ConnectionEncrypter, SecuredConnection, ConnectionGater, TypedEventTarget, Metrics, PeerId, PeerStore, StreamMuxer, StreamMuxerFactory, Upgrader, UpgraderOptions } from '@libp2p/interface'\nimport type { ConnectionManager, Registrar } from '@libp2p/interface-internal'\n\nconst DEFAULT_PROTOCOL_SELECT_TIMEOUT = 30000\n\ninterface CreateConnectionOptions {\n cryptoProtocol: string\n direction: 'inbound' | 'outbound'\n maConn: MultiaddrConnection\n upgradedConn: MultiaddrConnection\n remotePeer: PeerId\n muxerFactory?: StreamMuxerFactory\n transient?: boolean\n}\n\ninterface OnStreamOptions {\n connection: Connection\n stream: Stream\n protocol: string\n}\n\nexport interface CryptoResult extends SecuredConnection {\n protocol: string\n}\n\nexport interface UpgraderInit {\n connectionEncryption: ConnectionEncrypter[]\n muxers: StreamMuxerFactory[]\n\n /**\n * An amount of ms by which an inbound connection upgrade\n * must complete\n */\n inboundUpgradeTimeout?: number\n}\n\nfunction findIncomingStreamLimit (protocol: string, registrar: Registrar): number | undefined {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxInboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_INBOUND_STREAMS\n}\n\nfunction findOutgoingStreamLimit (protocol: string, registrar: Registrar, options: NewStreamOptions = {}): number {\n try {\n const { options } = registrar.getHandler(protocol)\n\n if (options.maxOutboundStreams != null) {\n return options.maxOutboundStreams\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return options.maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS\n}\n\nfunction countStreams (protocol: string, direction: 'inbound' | 'outbound', connection: Connection): number {\n let streamCount = 0\n\n connection.streams.forEach(stream => {\n if (stream.direction === direction && stream.protocol === protocol) {\n streamCount++\n }\n })\n\n return streamCount\n}\n\nexport interface DefaultUpgraderComponents {\n peerId: PeerId\n metrics?: Metrics\n connectionManager: ConnectionManager\n connectionGater: ConnectionGater\n connectionProtector?: ConnectionProtector\n registrar: Registrar\n peerStore: PeerStore\n events: TypedEventTarget\n logger: ComponentLogger\n}\n\ntype ConnectionDeniedType = keyof Pick\n\nexport class DefaultUpgrader implements Upgrader {\n private readonly components: DefaultUpgraderComponents\n private readonly connectionEncryption: Map\n private readonly muxers: Map\n private readonly inboundUpgradeTimeout: number\n private readonly events: TypedEventTarget\n\n constructor (components: DefaultUpgraderComponents, init: UpgraderInit) {\n this.components = components\n this.connectionEncryption = new Map()\n\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter)\n })\n\n this.muxers = new Map()\n\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer)\n })\n\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? INBOUND_UPGRADE_TIMEOUT\n this.events = components.events\n }\n\n async shouldBlockConnection (remotePeer: PeerId, maConn: MultiaddrConnection, connectionType: ConnectionDeniedType): Promise {\n const connectionGater = this.components.connectionGater[connectionType]\n\n if (connectionGater !== undefined) {\n if (await connectionGater(remotePeer, maConn)) {\n throw new CodeError(`The multiaddr connection is blocked by gater.${connectionType}`, codes.ERR_CONNECTION_INTERCEPTED)\n }\n }\n }\n\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise {\n const accept = await this.components.connectionManager.acceptIncomingConnection(maConn)\n\n if (!accept) {\n throw new CodeError('connection denied', codes.ERR_CONNECTION_DENIED)\n }\n\n let encryptedConn: MultiaddrConnection\n let remotePeer\n let upgradedConn: MultiaddrConnection\n let muxerFactory: StreamMuxerFactory | undefined\n let cryptoProtocol\n\n const signal = AbortSignal.timeout(this.inboundUpgradeTimeout)\n\n const onAbort = (): void => {\n maConn.abort(new CodeError('inbound upgrade timeout', ERR_TIMEOUT))\n }\n\n signal.addEventListener('abort', onAbort, { once: true })\n\n setMaxListeners(Infinity, signal)\n\n try {\n if ((await this.components.connectionGater.denyInboundConnection?.(maConn)) === true) {\n throw new CodeError('The multiaddr connection is blocked by gater.acceptConnection', codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n this.components.metrics?.trackMultiaddrConnection(maConn)\n\n maConn.log('starting the inbound connection upgrade')\n\n // Protect\n let protectedConn = maConn\n\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector\n\n if (protector != null) {\n maConn.log('protecting the inbound connection')\n protectedConn = await protector.protect(maConn)\n }\n }\n\n try {\n // Encrypt the connection\n encryptedConn = protectedConn\n if (opts?.skipEncryption !== true) {\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptInbound(protectedConn))\n\n const maConn: MultiaddrConnection = {\n ...protectedConn,\n ...encryptedConn\n }\n\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundEncryptedConnection')\n } else {\n const idStr = maConn.remoteAddr.getPeerId()\n\n if (idStr == null) {\n throw new CodeError('inbound connection that skipped encryption must have a peer id', codes.ERR_INVALID_MULTIADDR)\n }\n\n const remotePeerId = peerIdFromString(idStr)\n\n cryptoProtocol = 'native'\n remotePeer = remotePeerId\n }\n\n upgradedConn = encryptedConn\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory\n } else if (this.muxers.size > 0) {\n // Multiplex the connection\n const multiplexed = await this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers)\n muxerFactory = multiplexed.muxerFactory\n upgradedConn = multiplexed.stream\n }\n } catch (err: any) {\n maConn.log.error('failed to upgrade inbound connection', err)\n throw err\n }\n\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundUpgradedConnection')\n\n maConn.log('successfully upgraded inbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n })\n } finally {\n signal.removeEventListener('abort', onAbort)\n\n this.components.connectionManager.afterUpgradeInbound()\n }\n }\n\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise {\n const idStr = maConn.remoteAddr.getPeerId()\n let remotePeerId: PeerId | undefined\n\n if (idStr != null) {\n remotePeerId = peerIdFromString(idStr)\n\n await this.shouldBlockConnection(remotePeerId, maConn, 'denyOutboundConnection')\n }\n\n let encryptedConn: MultiaddrConnection\n let remotePeer: PeerId\n let upgradedConn: MultiaddrConnection\n let cryptoProtocol\n let muxerFactory\n\n this.components.metrics?.trackMultiaddrConnection(maConn)\n\n maConn.log('starting the outbound connection upgrade')\n\n // If the transport natively supports encryption, skip connection\n // protector and encryption\n\n // Protect\n let protectedConn = maConn\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector\n\n if (protector != null) {\n protectedConn = await protector.protect(maConn)\n }\n }\n\n try {\n // Encrypt the connection\n encryptedConn = protectedConn\n if (opts?.skipEncryption !== true) {\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptOutbound(protectedConn, remotePeerId))\n\n const maConn: MultiaddrConnection = {\n ...protectedConn,\n ...encryptedConn\n }\n\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundEncryptedConnection')\n } else {\n if (remotePeerId == null) {\n throw new CodeError('Encryption was skipped but no peer id was passed', codes.ERR_INVALID_PEER)\n }\n\n cryptoProtocol = 'native'\n remotePeer = remotePeerId\n }\n\n upgradedConn = encryptedConn\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory\n } else if (this.muxers.size > 0) {\n // Multiplex the connection\n const multiplexed = await this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers)\n muxerFactory = multiplexed.muxerFactory\n upgradedConn = multiplexed.stream\n }\n } catch (err: any) {\n maConn.log.error('failed to upgrade outbound connection', err)\n await maConn.close(err)\n throw err\n }\n\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundUpgradedConnection')\n\n maConn.log('successfully upgraded outbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n })\n }\n\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection (opts: CreateConnectionOptions): Connection {\n const {\n cryptoProtocol,\n direction,\n maConn,\n upgradedConn,\n remotePeer,\n muxerFactory,\n transient\n } = opts\n\n let muxer: StreamMuxer | undefined\n let newStream: ((multicodecs: string[], options?: AbortOptions) => Promise) | undefined\n let connection: Connection // eslint-disable-line prefer-const\n\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return\n }\n\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.registrar.getProtocols()\n const { stream, protocol } = await mss.handle(muxedStream, protocols, {\n log: muxedStream.log,\n yieldBytes: false\n })\n\n if (connection == null) {\n return\n }\n\n connection.log('incoming stream opened on %s', protocol)\n\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar)\n const streamCount = countStreams(protocol, 'inbound', connection)\n\n if (streamCount === incomingLimit) {\n const err = new CodeError(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`, codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS)\n muxedStream.abort(err)\n\n throw err\n }\n\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source\n muxedStream.sink = stream.sink\n muxedStream.protocol = protocol\n\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite\n }\n\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead\n }\n\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close\n }\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n })\n\n this.components.metrics?.trackProtocolStream(muxedStream, connection)\n\n this._onStream({ connection, stream: muxedStream, protocol })\n })\n .catch(async err => {\n connection.log.error('error handling incoming stream id %s', muxedStream.id, err.message, err.code, err.stack)\n\n if (muxedStream.timeline.close == null) {\n await muxedStream.close()\n }\n })\n }\n })\n\n newStream = async (protocols: string[], options: NewStreamOptions = {}): Promise => {\n if (muxer == null) {\n throw new CodeError('Stream is not multiplexed', codes.ERR_MUXER_UNAVAILABLE)\n }\n\n connection.log('starting new stream for protocols %s', protocols)\n const muxedStream = await muxer.newStream()\n connection.log.trace('started new stream %s for protocols %s', muxedStream.id, protocols)\n\n try {\n if (options.signal == null) {\n muxedStream.log('no abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)\n\n const signal = AbortSignal.timeout(DEFAULT_PROTOCOL_SELECT_TIMEOUT)\n setMaxListeners(Infinity, signal)\n\n options = {\n ...options,\n signal\n }\n }\n\n muxedStream.log.trace('selecting protocol from protocols %s', protocols)\n\n const {\n stream,\n protocol\n } = await mss.select(muxedStream, protocols, {\n ...options,\n log: muxedStream.log,\n yieldBytes: true\n })\n\n muxedStream.log('selected protocol %s', protocol)\n\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar, options)\n const streamCount = countStreams(protocol, 'outbound', connection)\n\n if (streamCount >= outgoingLimit) {\n const err = new CodeError(`Too many outbound protocol streams for protocol \"${protocol}\" - limit ${outgoingLimit}`, codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS)\n muxedStream.abort(err)\n\n throw err\n }\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n })\n\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source\n muxedStream.sink = stream.sink\n muxedStream.protocol = protocol\n\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite\n }\n\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead\n }\n\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close\n }\n\n this.components.metrics?.trackProtocolStream(muxedStream, connection)\n\n return muxedStream\n } catch (err: any) {\n connection.log.error('could not create new stream for protocols %s', protocols, err)\n\n if (muxedStream.timeline.close == null) {\n muxedStream.abort(err)\n }\n\n if (err.code != null) {\n throw err\n }\n\n throw new CodeError(String(err), codes.ERR_UNSUPPORTED_PROTOCOL)\n }\n }\n\n // Pipe all data through the muxer\n void Promise.all([\n muxer.sink(upgradedConn.source),\n upgradedConn.sink(muxer.source)\n ]).catch(err => {\n connection.log.error('error piping data through muxer', err)\n })\n }\n\n const _timeline = maConn.timeline\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (connection != null && args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.status === 'open') {\n await connection.close()\n }\n } catch (err: any) {\n connection.log.error('error closing connection after timeline close', err)\n } finally {\n this.events.safeDispatchEvent('connection:close', {\n detail: connection\n })\n }\n })().catch(err => {\n connection.log.error('error thrown while dispatching connection:close event', err)\n })\n }\n\n return Reflect.set(...args)\n }\n })\n maConn.timeline.upgraded = Date.now()\n\n const errConnectionNotMultiplexed = (): any => {\n throw new CodeError('connection is not multiplexed', codes.ERR_CONNECTION_NOT_MULTIPLEXED)\n }\n\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer,\n status: 'open',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol,\n transient,\n logger: this.components.logger,\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => { if (muxer != null) { return muxer.streams } else { return [] } },\n close: async (options?: AbortOptions) => {\n // Ensure remaining streams are closed gracefully\n if (muxer != null) {\n connection.log.trace('close muxer')\n await muxer.close(options)\n }\n\n connection.log.trace('close maconn')\n // close the underlying transport\n await maConn.close(options)\n connection.log.trace('closed maconn')\n },\n abort: (err) => {\n maConn.abort(err)\n // Ensure remaining streams are aborted\n if (muxer != null) {\n muxer.abort(err)\n }\n }\n })\n\n this.events.safeDispatchEvent('connection:open', {\n detail: connection\n })\n\n return connection\n }\n\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream (opts: OnStreamOptions): void {\n const { connection, stream, protocol } = opts\n const { handler, options } = this.components.registrar.getHandler(protocol)\n\n if (connection.transient && options.runOnTransientConnection !== true) {\n throw new CodeError('Cannot open protocol stream on transient connection', 'ERR_TRANSIENT_CONNECTION')\n }\n\n handler({ connection, stream })\n }\n\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound (connection: MultiaddrConnection): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n connection.log('handling inbound crypto protocol selection', protocols)\n\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n log: connection.log\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n connection.log('encrypting inbound connection using', protocol)\n\n return {\n ...await encrypter.secureInbound(this.components.peerId, stream),\n protocol\n }\n } catch (err: any) {\n connection.log.error('encrypting inbound connection to %p failed', err)\n throw new CodeError(err.message, codes.ERR_ENCRYPTION_FAILED)\n }\n }\n\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound (connection: MultiaddrConnection, remotePeerId?: PeerId): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n connection.log('selecting outbound crypto protocol', protocols)\n\n try {\n connection.log.trace('selecting encrypter from %s', protocols)\n\n const {\n stream,\n protocol\n } = await mss.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n })\n\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n connection.log('encrypting outbound connection to %p using %s', remotePeerId, encrypter)\n\n return {\n ...await encrypter.secureOutbound(this.components.peerId, stream, remotePeerId),\n protocol\n }\n } catch (err: any) {\n connection.log.error('encrypting outbound connection to %p failed', err)\n throw new CodeError(err.message, codes.ERR_ENCRYPTION_FAILED)\n }\n }\n\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {\n const protocols = Array.from(muxers.keys())\n connection.log('outbound selecting muxer %s', protocols)\n try {\n connection.log.trace('selecting stream muxer from %s', protocols)\n\n const {\n stream,\n protocol\n } = await mss.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n })\n\n connection.log('selected %s as muxer protocol', protocol)\n const muxerFactory = muxers.get(protocol)\n\n return { stream, muxerFactory }\n } catch (err: any) {\n connection.log.error('error multiplexing outbound connection', err)\n throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound (connection: MultiaddrConnection, muxers: Map): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {\n const protocols = Array.from(muxers.keys())\n connection.log('inbound handling muxers %s', protocols)\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n log: connection.log\n })\n const muxerFactory = muxers.get(protocol)\n\n return { stream, muxerFactory }\n } catch (err: any) {\n connection.log.error('error multiplexing inbound connection', err)\n throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n}\n","import { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { contentRoutingSymbol, CodeError, TypedEventEmitter, CustomEvent, setMaxListeners, peerDiscoverySymbol, peerRoutingSymbol } from '@libp2p/interface'\nimport { defaultLogger } from '@libp2p/logger'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { createEd25519PeerId } from '@libp2p/peer-id-factory'\nimport { PersistentPeerStore } from '@libp2p/peer-store'\nimport { isMultiaddr, type Multiaddr } from '@multiformats/multiaddr'\nimport { MemoryDatastore } from 'datastore-core/memory'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { DefaultAddressManager } from './address-manager/index.js'\nimport { defaultComponents } from './components.js'\nimport { connectionGater } from './config/connection-gater.js'\nimport { validateConfig } from './config.js'\nimport { DefaultConnectionManager } from './connection-manager/index.js'\nimport { CompoundContentRouting } from './content-routing.js'\nimport { codes } from './errors.js'\nimport { DefaultPeerRouting } from './peer-routing.js'\nimport { DefaultRegistrar } from './registrar.js'\nimport { DefaultTransportManager } from './transport-manager.js'\nimport { DefaultUpgrader } from './upgrader.js'\nimport * as pkg from './version.js'\nimport type { Components } from './components.js'\nimport type { Libp2p, Libp2pInit, Libp2pOptions } from './index.js'\nimport type { PeerRouting, ContentRouting, Libp2pEvents, PendingDial, ServiceMap, AbortOptions, ComponentLogger, Logger, Connection, NewStreamOptions, Stream, Metrics, PeerId, PeerInfo, PeerStore, Topology, Libp2pStatus } from '@libp2p/interface'\nimport type { StreamHandler, StreamHandlerOptions } from '@libp2p/interface-internal'\n\nexport class Libp2pNode> extends TypedEventEmitter implements Libp2p {\n public peerId: PeerId\n public peerStore: PeerStore\n public contentRouting: ContentRouting\n public peerRouting: PeerRouting\n public metrics?: Metrics\n public services: T\n public logger: ComponentLogger\n public status: Libp2pStatus\n\n public components: Components\n private readonly log: Logger\n\n constructor (init: Libp2pInit) {\n super()\n\n this.status = 'stopped'\n\n // event bus - components can listen to this emitter to be notified of system events\n // and also cause them to be emitted\n const events = new TypedEventEmitter()\n const originalDispatch = events.dispatchEvent.bind(events)\n events.dispatchEvent = (evt: any) => {\n const internalResult = originalDispatch(evt)\n const externalResult = this.dispatchEvent(\n new CustomEvent(evt.type, { detail: evt.detail })\n )\n\n return internalResult || externalResult\n }\n\n // This emitter gets listened to a lot\n setMaxListeners(Infinity, events)\n\n this.peerId = init.peerId\n this.logger = init.logger ?? defaultLogger()\n this.log = this.logger.forComponent('libp2p')\n // @ts-expect-error {} may not be of type T\n this.services = {}\n const components = this.components = defaultComponents({\n peerId: init.peerId,\n privateKey: init.privateKey,\n nodeInfo: init.nodeInfo ?? {\n name: pkg.name,\n version: pkg.version\n },\n logger: this.logger,\n events,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: connectionGater(init.connectionGater),\n dns: init.dns\n })\n\n this.peerStore = this.configureComponent('peerStore', new PersistentPeerStore(components, {\n addressFilter: this.components.connectionGater.filterMultiaddrForPeer,\n ...init.peerStore\n }))\n\n // Create Metrics\n if (init.metrics != null) {\n this.metrics = this.configureComponent('metrics', init.metrics(this.components))\n }\n\n components.events.addEventListener('peer:update', evt => {\n // if there was no peer previously in the peer store this is a new peer\n if (evt.detail.previous == null) {\n const peerInfo: PeerInfo = {\n id: evt.detail.peer.id,\n multiaddrs: evt.detail.peer.addresses.map(a => a.multiaddr)\n }\n\n components.events.safeDispatchEvent('peer:discovery', { detail: peerInfo })\n }\n })\n\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.configureComponent('connectionProtector', init.connectionProtector(components))\n }\n\n // Set up the Upgrader\n this.components.upgrader = new DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map((fn, index) => this.configureComponent(`connection-encryption-${index}`, fn(this.components))),\n muxers: (init.streamMuxers ?? []).map((fn, index) => this.configureComponent(`stream-muxers-${index}`, fn(this.components))),\n inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout\n })\n\n // Setup the transport manager\n this.configureComponent('transportManager', new DefaultTransportManager(this.components, init.transportManager))\n\n // Create the Connection Manager\n this.configureComponent('connectionManager', new DefaultConnectionManager(this.components, init.connectionManager))\n\n // Create the Registrar\n this.configureComponent('registrar', new DefaultRegistrar(this.components))\n\n // Addresses {listen, announce, noAnnounce}\n this.configureComponent('addressManager', new DefaultAddressManager(this.components, init.addresses))\n\n // Peer routers\n const peerRouters: PeerRouting[] = (init.peerRouters ?? []).map((fn, index) => this.configureComponent(`peer-router-${index}`, fn(this.components)))\n this.peerRouting = this.components.peerRouting = this.configureComponent('peerRouting', new DefaultPeerRouting(this.components, {\n routers: peerRouters\n }))\n\n // Content routers\n const contentRouters: ContentRouting[] = (init.contentRouters ?? []).map((fn, index) => this.configureComponent(`content-router-${index}`, fn(this.components)))\n this.contentRouting = this.components.contentRouting = this.configureComponent('contentRouting', new CompoundContentRouting(this.components, {\n routers: contentRouters\n }))\n\n // Discovery modules\n ;(init.peerDiscovery ?? []).forEach((fn, index) => {\n const service = this.configureComponent(`peer-discovery-${index}`, fn(this.components))\n\n service.addEventListener('peer', (evt) => {\n this.#onDiscoveryPeer(evt)\n })\n })\n\n // Transport modules\n init.transports?.forEach((fn, index) => {\n this.components.transportManager.add(this.configureComponent(`transport-${index}`, fn(this.components)))\n })\n\n // User defined modules\n if (init.services != null) {\n for (const name of Object.keys(init.services)) {\n const createService = init.services[name]\n const service: any = createService(this.components)\n\n if (service == null) {\n this.log.error('service factory %s returned null or undefined instance', name)\n continue\n }\n\n this.services[name as keyof T] = service\n this.configureComponent(name, service)\n\n if (service[contentRoutingSymbol] != null) {\n this.log('registering service %s for content routing', name)\n contentRouters.push(service[contentRoutingSymbol])\n }\n\n if (service[peerRoutingSymbol] != null) {\n this.log('registering service %s for peer routing', name)\n peerRouters.push(service[peerRoutingSymbol])\n }\n\n if (service[peerDiscoverySymbol] != null) {\n this.log('registering service %s for peer discovery', name)\n service[peerDiscoverySymbol].addEventListener?.('peer', (evt: CustomEvent) => {\n this.#onDiscoveryPeer(evt)\n })\n }\n }\n }\n }\n\n private configureComponent (name: string, component: T): T {\n if (component == null) {\n this.log.error('component %s was null or undefined', name)\n }\n\n this.components[name] = component\n\n return component\n }\n\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start (): Promise {\n if (this.status !== 'stopped') {\n return\n }\n\n this.status = 'starting'\n\n this.log('libp2p is starting')\n\n try {\n await this.components.beforeStart?.()\n await this.components.start()\n await this.components.afterStart?.()\n\n this.status = 'started'\n this.safeDispatchEvent('start', { detail: this })\n this.log('libp2p has started')\n } catch (err: any) {\n this.log.error('An error occurred starting libp2p', err)\n // set status to 'started' so this.stop() will stop any running components\n this.status = 'started'\n await this.stop()\n throw err\n }\n }\n\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop (): Promise {\n if (this.status !== 'started') {\n return\n }\n\n this.log('libp2p is stopping')\n\n this.status = 'stopping'\n\n await this.components.beforeStop?.()\n await this.components.stop()\n await this.components.afterStop?.()\n\n this.status = 'stopped'\n this.safeDispatchEvent('stop', { detail: this })\n this.log('libp2p has stopped')\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n return this.components.connectionManager.getConnections(peerId)\n }\n\n getDialQueue (): PendingDial[] {\n return this.components.connectionManager.getDialQueue()\n }\n\n getPeers (): PeerId[] {\n const peerSet = new PeerSet()\n\n for (const conn of this.components.connectionManager.getConnections()) {\n peerSet.add(conn.remotePeer)\n }\n\n return Array.from(peerSet)\n }\n\n async dial (peer: PeerId | Multiaddr | Multiaddr[], options: AbortOptions = {}): Promise {\n return this.components.connectionManager.openConnection(peer, {\n // ensure any userland dials take top priority in the queue\n priority: 75,\n ...options\n })\n }\n\n async dialProtocol (peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options: NewStreamOptions = {}): Promise {\n if (protocols == null) {\n throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n\n if (protocols.length === 0) {\n throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n const connection = await this.dial(peer, options)\n\n return connection.newStream(protocols, options)\n }\n\n getMultiaddrs (): Multiaddr[] {\n return this.components.addressManager.getAddresses()\n }\n\n getProtocols (): string[] {\n return this.components.registrar.getProtocols()\n }\n\n async hangUp (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n if (isMultiaddr(peer)) {\n peer = peerIdFromString(peer.getPeerId() ?? '')\n }\n\n await this.components.connectionManager.closeConnections(peer, options)\n }\n\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey (peer: PeerId, options: AbortOptions = {}): Promise {\n this.log('getPublicKey %p', peer)\n\n if (peer.publicKey != null) {\n return peer.publicKey\n }\n\n try {\n const peerInfo = await this.peerStore.get(peer)\n\n if (peerInfo.id.publicKey != null) {\n return peerInfo.id.publicKey\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.multihash.digest\n ])\n\n // search any available content routing methods\n const bytes = await this.contentRouting.get(peerKey, options)\n\n // ensure the returned key is valid\n unmarshalPublicKey(bytes)\n\n await this.peerStore.patch(peer, {\n publicKey: bytes\n })\n\n return bytes\n }\n\n async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.registrar.handle(protocol, handler, options)\n })\n )\n }\n\n async unhandle (protocols: string[] | string): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.registrar.unhandle(protocol)\n })\n )\n }\n\n async register (protocol: string, topology: Topology): Promise {\n return this.components.registrar.register(protocol, topology)\n }\n\n unregister (id: string): void {\n this.components.registrar.unregister(id)\n }\n\n /**\n * Called whenever peer discovery services emit `peer` events and adds peers\n * to the peer store.\n */\n #onDiscoveryPeer (evt: CustomEvent): void {\n const { detail: peer } = evt\n\n if (peer.id.toString() === this.peerId.toString()) {\n this.log.error(new Error(codes.ERR_DISCOVERED_SELF))\n return\n }\n\n void this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n .catch(err => { this.log.error(err) })\n }\n}\n\n/**\n * Returns a new Libp2pNode instance - this exposes more of the internals than the\n * libp2p interface and is useful for testing and debugging.\n */\nexport async function createLibp2pNode > (options: Libp2pOptions = {}): Promise> {\n const peerId = options.peerId ??= await createEd25519PeerId()\n\n if (peerId.privateKey == null) {\n throw new CodeError('peer id was missing private key', 'ERR_MISSING_PRIVATE_KEY')\n }\n\n options.privateKey ??= await unmarshalPrivateKey(peerId.privateKey as Uint8Array)\n\n return new Libp2pNode(await validateConfig(options))\n}\n","export const version = '1.3.3'\nexport const name = 'libp2p'\n","/**\n * @packageDocumentation\n *\n * Use the `createLibp2p` function to create a libp2p node.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n *\n * const node = await createLibp2p({\n * // ...other options\n * })\n * ```\n */\n\nimport { createLibp2pNode } from './libp2p.js'\nimport type { AddressManagerInit } from './address-manager/index.js'\nimport type { Components } from './components.js'\nimport type { ConnectionManagerInit } from './connection-manager/index.js'\nimport type { TransportManagerInit } from './transport-manager.js'\nimport type { Libp2p, ServiceMap, RecursivePartial, ComponentLogger, NodeInfo, ConnectionProtector, ConnectionEncrypter, ConnectionGater, ContentRouting, Metrics, PeerDiscovery, PeerId, PeerRouting, StreamMuxerFactory, Transport, PrivateKey } from '@libp2p/interface'\nimport type { PersistentPeerStoreInit } from '@libp2p/peer-store'\nimport type { DNS } from '@multiformats/dns'\nimport type { Datastore } from 'interface-datastore'\n\nexport type ServiceFactoryMap = Record> = {\n [Property in keyof T]: (components: Components) => T[Property]\n}\n\n/**\n * For Libp2p configurations and modules details read the [Configuration Document](./CONFIGURATION.md).\n */\nexport interface Libp2pInit }> {\n /**\n * peerId instance (it will be created if not provided)\n */\n peerId: PeerId\n\n /**\n * Private key associated with the peerId\n */\n privateKey: PrivateKey\n\n /**\n * Metadata about the node - implementation name, version number, etc\n */\n nodeInfo: NodeInfo\n\n /**\n * Addresses for transport listening and to advertise to the network\n */\n addresses: AddressManagerInit\n\n /**\n * libp2p Connection Manager configuration\n */\n connectionManager: ConnectionManagerInit\n\n /**\n * A connection gater can deny new connections based on user criteria\n */\n connectionGater: ConnectionGater\n\n /**\n * libp2p transport manager configuration\n */\n transportManager: TransportManagerInit\n\n /**\n * An optional datastore to persist peer information, DHT records, etc.\n *\n * An in-memory datastore will be used if one is not provided.\n */\n datastore: Datastore\n\n /**\n * libp2p PeerStore configuration\n */\n peerStore: PersistentPeerStoreInit\n\n /**\n * An array that must include at least 1 compliant transport\n */\n transports?: Array<(components: Components) => Transport>\n streamMuxers?: Array<(components: Components) => StreamMuxerFactory>\n connectionEncryption?: Array<(components: Components) => ConnectionEncrypter>\n peerDiscovery?: Array<(components: Components) => PeerDiscovery>\n peerRouters?: Array<(components: Components) => PeerRouting>\n contentRouters?: Array<(components: Components) => ContentRouting>\n\n /**\n * A Metrics implementation can be supplied to collect metrics on this node\n */\n metrics?(components: Components): Metrics\n\n /**\n * A ConnectionProtector can be used to create a secure overlay on top of the network using pre-shared keys\n */\n connectionProtector?(components: Components): ConnectionProtector\n\n /**\n * Arbitrary libp2p modules\n */\n services: ServiceFactoryMap\n\n /**\n * An optional logging implementation that can be used to write runtime logs.\n *\n * Set the `DEBUG` env var or the `debug` key on LocalStorage to see logs.\n *\n * @example\n *\n * Node.js:\n *\n * ```console\n * $ DEBUG=\"*libp2p:*\" node myscript.js\n * ```\n *\n * Browsers:\n *\n * ```TypeScript\n * localStorage.setItem('debug', '*libp2p:*')\n * ```\n */\n logger?: ComponentLogger\n\n /**\n * An optional DNS resolver configuration. If omitted the default DNS resolver\n * for the platform will be used which means `node:dns` on Node.js and\n * DNS-JSON-over-HTTPS for browsers using Google and Cloudflare servers.\n */\n dns?: DNS\n}\n\nexport type { Libp2p }\n\nexport type Libp2pOptions> = RecursivePartial> & { start?: boolean }\n\n/**\n * Returns a new instance of the Libp2p interface, generating a new PeerId\n * if one is not passed as part of the options.\n *\n * The node will be started unless `start: false` is passed as an option.\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { tcp } from '@libp2p/tcp'\n * import { mplex } from '@libp2p/mplex'\n * import { noise } from '@chainsafe/libp2p-noise'\n * import { yamux } from '@chainsafe/libp2p-yamux'\n *\n * // specify options\n * const options = {\n * transports: [tcp()],\n * streamMuxers: [yamux(), mplex()],\n * connectionEncryption: [noise()]\n * }\n *\n * // create libp2p\n * const libp2p = await createLibp2p(options)\n * ```\n */\nexport async function createLibp2p }> (options: Libp2pOptions = {}): Promise> {\n const node = await createLibp2pNode(options)\n\n if (options.start !== false) {\n await node.start()\n }\n\n return node\n}\n","import { IBaseProtocolSDK } from \"..\";\n\ninterface Options {\n numPeersToUse?: number;\n}\n\nconst DEFAULT_NUM_PEERS_TO_USE = 3;\n\nexport class BaseProtocolSDK implements IBaseProtocolSDK {\n public readonly numPeers: number;\n\n constructor(options: Options) {\n this.numPeers = options?.numPeersToUse ?? DEFAULT_NUM_PEERS_TO_USE;\n }\n}\n","import type { PeerId } from \"@libp2p/interface\";\nimport { LightPushCore } from \"@waku/core\";\nimport {\n Failure,\n type IEncoder,\n ILightPushSDK,\n type IMessage,\n type Libp2p,\n type ProtocolCreateOptions,\n ProtocolError,\n type SendResult\n} from \"@waku/interfaces\";\nimport { ensurePubsubTopicIsConfigured, Logger } from \"@waku/utils\";\n\nimport { BaseProtocolSDK } from \"./base_protocol.js\";\n\nconst DEFAULT_NUM_PEERS = 3;\nconst log = new Logger(\"sdk:light-push\");\n\nexport class LightPushSDK extends BaseProtocolSDK implements ILightPushSDK {\n public readonly protocol: LightPushCore;\n\n constructor(libp2p: Libp2p, options?: ProtocolCreateOptions) {\n super({ numPeersToUse: options?.numPeersToUse ?? DEFAULT_NUM_PEERS });\n this.protocol = new LightPushCore(libp2p, options);\n }\n\n async send(encoder: IEncoder, message: IMessage): Promise {\n const successes: PeerId[] = [];\n const failures: Failure[] = [];\n\n const { pubsubTopic } = encoder;\n try {\n ensurePubsubTopicIsConfigured(pubsubTopic, this.protocol.pubsubTopics);\n } catch (error) {\n log.error(\"Failed to send waku light push: pubsub topic not configured\");\n return {\n failures: [\n {\n error: ProtocolError.TOPIC_NOT_CONFIGURED\n }\n ],\n successes: []\n };\n }\n\n const peers = await this.protocol.getPeers();\n if (!peers.length) {\n return {\n successes,\n failures: [{ error: ProtocolError.NO_PEER_AVAILABLE }]\n };\n }\n\n const sendPromises = peers.map((peer) =>\n this.protocol.send(encoder, message, peer)\n );\n\n const results = await Promise.allSettled(sendPromises);\n\n for (const result of results) {\n if (result.status === \"fulfilled\") {\n const { failure, success } = result.value;\n if (success) {\n successes.push(success);\n }\n if (failure) {\n failures.push(failure);\n }\n } else {\n log.error(\"Failed to send message to peer\", result.reason);\n failures.push({ error: ProtocolError.GENERIC_FAIL });\n // TODO: handle renewing faulty peers with new peers (https://github.com/waku-org/js-waku/issues/1463)\n }\n }\n\n return {\n successes,\n failures\n };\n }\n}\n\nexport function wakuLightPush(\n init: Partial = {}\n): (libp2p: Libp2p) => ILightPushSDK {\n return (libp2p: Libp2p) => new LightPushSDK(libp2p, init);\n}\n","import { sha256 } from \"@noble/hashes/sha256\";\nimport { StoreCore, waku_store } from \"@waku/core\";\nimport {\n Cursor,\n IDecodedMessage,\n IDecoder,\n IStoreSDK,\n type Libp2p,\n PageDirection,\n type ProtocolCreateOptions\n} from \"@waku/interfaces\";\nimport { ensurePubsubTopicIsConfigured, isDefined, Logger } from \"@waku/utils\";\nimport { concat } from \"@waku/utils/bytes\";\n\nimport { utf8ToBytes } from \"../index.js\";\n\nimport { BaseProtocolSDK } from \"./base_protocol.js\";\n\nexport const DefaultPageSize = 10;\n\nconst DEFAULT_NUM_PEERS = 1;\n\nconst log = new Logger(\"waku:store:protocol\");\n\nexport class StoreSDK extends BaseProtocolSDK implements IStoreSDK {\n public readonly protocol: StoreCore;\n\n constructor(libp2p: Libp2p, options?: ProtocolCreateOptions) {\n // TODO: options.numPeersToUse is disregarded: https://github.com/waku-org/js-waku/issues/1685\n super({ numPeersToUse: DEFAULT_NUM_PEERS });\n\n this.protocol = new StoreCore(libp2p, options);\n }\n\n /**\n * Do a query to a Waku Store to retrieve historical/missed messages.\n *\n * This is a generator, useful if you want most control on how messages\n * are processed.\n *\n * The order of the messages returned by the remote Waku node SHOULD BE\n * as follows:\n * - within a page, messages SHOULD be ordered from oldest to most recent\n * - pages direction depends on { @link QueryOptions.pageDirection }\n * @throws If not able to reach a Waku Store peer to query,\n * or if an error is encountered when processing the reply,\n * or if two decoders with the same content topic are passed.\n *\n * This API only supports querying a single pubsub topic at a time.\n * If multiple decoders are provided, they must all have the same pubsub topic.\n * @throws If multiple decoders with different pubsub topics are provided.\n * @throws If no decoders are provided.\n * @throws If no decoders are found for the provided pubsub topic.\n */\n async *queryGenerator(\n decoders: IDecoder[],\n options?: waku_store.QueryOptions\n ): AsyncGenerator[]> {\n const { pubsubTopic, contentTopics, decodersAsMap } =\n this.validateDecodersAndPubsubTopic(decoders, options);\n\n const queryOpts = this.constructOptions(\n pubsubTopic,\n contentTopics,\n options\n );\n\n const peer = (\n await this.protocol.getPeers({\n numPeers: this.numPeers,\n maxBootstrapPeers: 1\n })\n )[0];\n\n if (!peer) throw new Error(\"No peers available to query\");\n\n const responseGenerator = this.protocol.queryPerPage(\n queryOpts,\n decodersAsMap,\n peer\n );\n\n for await (const messages of responseGenerator) {\n yield messages;\n }\n }\n\n /**\n * Do a query to a Waku Store to retrieve historical/missed messages.\n *\n * The callback function takes a `WakuMessage` in input,\n * messages are processed in order:\n * - oldest to latest if `options.pageDirection` == { @link PageDirection.FORWARD }\n * - latest to oldest if `options.pageDirection` == { @link PageDirection.BACKWARD }\n *\n * The ordering may affect performance.\n * The ordering depends on the behavior of the remote store node.\n * If strong ordering is needed, you may need to handle this at application level\n * and set your own timestamps too (the WakuMessage timestamps are not certified).\n *\n * @throws If not able to reach a Waku Store peer to query,\n * or if an error is encountered when processing the reply,\n * or if two decoders with the same content topic are passed.\n */\n async queryWithOrderedCallback(\n decoders: IDecoder[],\n callback: (message: T) => Promise | boolean | void,\n options?: waku_store.QueryOptions\n ): Promise {\n for await (const promises of this.queryGenerator(decoders, options)) {\n if (await this.processMessages(promises, callback, options)) break;\n }\n }\n\n /**\n * Do a query to a Waku Store to retrieve historical/missed messages.\n * The callback function takes a `Promise` in input,\n * useful if messages need to be decrypted and performance matters.\n *\n * The order of the messages passed to the callback is as follows:\n * - within a page, messages are expected to be ordered from oldest to most recent\n * - pages direction depends on { @link QueryOptions.pageDirection }\n *\n * Do note that the resolution of the `Promise(\n decoders: IDecoder[],\n callback: (\n message: Promise\n ) => Promise | boolean | void,\n options?: waku_store.QueryOptions\n ): Promise {\n let abort = false;\n for await (const page of this.queryGenerator(decoders, options)) {\n const _promises = page.map(async (msgPromise) => {\n if (abort) return;\n abort = Boolean(await callback(msgPromise));\n });\n\n await Promise.all(_promises);\n if (abort) break;\n }\n }\n\n createCursor(message: IDecodedMessage): Cursor {\n if (\n !message ||\n !message.timestamp ||\n !message.payload ||\n !message.contentTopic\n ) {\n throw new Error(\"Message is missing required fields\");\n }\n\n const contentTopicBytes = utf8ToBytes(message.contentTopic);\n\n const digest = sha256(concat([contentTopicBytes, message.payload]));\n\n const messageTime = BigInt(message.timestamp.getTime()) * BigInt(1000000);\n\n return {\n digest,\n pubsubTopic: message.pubsubTopic,\n senderTime: messageTime,\n receiverTime: messageTime\n };\n }\n\n private validateDecodersAndPubsubTopic(\n decoders: IDecoder[],\n options?: waku_store.QueryOptions\n ): {\n pubsubTopic: string;\n contentTopics: string[];\n decodersAsMap: Map>;\n } {\n if (decoders.length === 0) {\n throw new Error(\"No decoders provided\");\n }\n\n // convert array to set to remove duplicates\n const uniquePubsubTopicsInQuery = Array.from(\n new Set(decoders.map((decoder) => decoder.pubsubTopic))\n );\n // If multiple pubsub topics are provided, throw an error\n if (uniquePubsubTopicsInQuery.length > 1) {\n throw new Error(\n \"API does not support querying multiple pubsub topics at once\"\n );\n }\n\n // we can be certain that there is only one pubsub topic in the query\n const pubsubTopicForQuery = uniquePubsubTopicsInQuery[0];\n\n ensurePubsubTopicIsConfigured(\n pubsubTopicForQuery,\n this.protocol.pubsubTopics\n );\n\n // check that the pubsubTopic from the Cursor and Decoder match\n if (\n options?.cursor?.pubsubTopic &&\n options.cursor.pubsubTopic !== pubsubTopicForQuery\n ) {\n throw new Error(\n `Cursor pubsub topic (${options?.cursor?.pubsubTopic}) does not match decoder pubsub topic (${pubsubTopicForQuery})`\n );\n }\n\n const decodersAsMap = new Map();\n decoders.forEach((dec) => {\n if (decodersAsMap.has(dec.contentTopic)) {\n throw new Error(\n \"API does not support different decoder per content topic\"\n );\n }\n decodersAsMap.set(dec.contentTopic, dec);\n });\n\n const contentTopics = decoders\n .filter((decoder) => decoder.pubsubTopic === pubsubTopicForQuery)\n .map((dec) => dec.contentTopic);\n\n if (contentTopics.length === 0) {\n throw new Error(\"No decoders found for topic \" + pubsubTopicForQuery);\n }\n\n return {\n pubsubTopic: pubsubTopicForQuery,\n contentTopics,\n decodersAsMap\n };\n }\n\n private constructOptions(\n pubsubTopic: string,\n contentTopics: string[],\n options: waku_store.QueryOptions = {}\n ): waku_store.Params {\n let startTime, endTime;\n\n if (options?.timeFilter) {\n startTime = options.timeFilter.startTime;\n endTime = options.timeFilter.endTime;\n }\n\n if (!startTime) {\n log.warn(\"No start time provided\");\n }\n if (!endTime) {\n log.warn(\"No end time provided\");\n }\n\n const queryOpts = Object.assign(\n {\n pubsubTopic: pubsubTopic,\n pageDirection: PageDirection.BACKWARD,\n pageSize: DefaultPageSize\n },\n options,\n { contentTopics, startTime, endTime }\n );\n\n return queryOpts;\n }\n\n /**\n * Processes messages based on the provided callback and options.\n * @private\n */\n private async processMessages(\n messages: Promise[],\n callback: (message: T) => Promise | boolean | void,\n options?: waku_store.QueryOptions\n ): Promise {\n let abort = false;\n const messagesOrUndef: Array = await Promise.all(messages);\n let processedMessages: Array = messagesOrUndef.filter(isDefined);\n\n if (this.shouldReverseOrder(options)) {\n processedMessages = processedMessages.reverse();\n }\n\n await Promise.all(\n processedMessages.map(async (msg) => {\n if (msg && !abort) {\n abort = Boolean(await callback(msg));\n }\n })\n );\n\n return abort;\n }\n\n /**\n * Determines whether to reverse the order of messages based on the provided options.\n *\n * Messages in pages are ordered from oldest (first) to most recent (last).\n * https://github.com/vacp2p/rfc/issues/533\n *\n * @private\n */\n private shouldReverseOrder(options?: waku_store.QueryOptions): boolean {\n return (\n typeof options?.pageDirection === \"undefined\" ||\n options?.pageDirection === PageDirection.BACKWARD\n );\n }\n}\n\nexport function wakuStore(\n init: Partial = {}\n): (libp2p: Libp2p) => IStoreSDK {\n return (libp2p: Libp2p) => new StoreSDK(libp2p, init);\n}\n","import { wakuFilter } from \"@waku/core\";\nimport { type Libp2pComponents, type LightNode } from \"@waku/interfaces\";\n\nimport { wakuLightPush } from \"../protocols/light_push.js\";\nimport { wakuStore } from \"../protocols/store.js\";\nimport { createLibp2pAndUpdateOptions } from \"../utils/libp2p.js\";\nimport { CreateWakuNodeOptions, WakuNode, WakuOptions } from \"../waku.js\";\n\nexport { Libp2pComponents };\n\n/**\n * Create a Waku node configured to use autosharding or static sharding.\n */\nexport async function createNode(\n options: CreateWakuNodeOptions = { pubsubTopics: [] }\n): Promise {\n if (!options.shardInfo) {\n throw new Error(\"Shard info must be set\");\n }\n\n const libp2p = await createLibp2pAndUpdateOptions(options);\n\n const store = wakuStore(options);\n const lightPush = wakuLightPush(options);\n const filter = wakuFilter(options);\n\n return new WakuNode(\n options as WakuOptions,\n libp2p,\n store,\n lightPush,\n filter\n ) as LightNode;\n}\n\n/**\n * Create a Waku node that uses Waku Light Push, Filter and Store to send and\n * receive messages, enabling low resource consumption.\n * Uses Waku Filter V2 by default.\n */\nexport async function createLightNode(\n options: CreateWakuNodeOptions = {}\n): Promise {\n const libp2p = await createLibp2pAndUpdateOptions(options);\n\n const store = wakuStore(options);\n const lightPush = wakuLightPush(options);\n const filter = wakuFilter(options);\n\n return new WakuNode(\n options as WakuOptions,\n libp2p,\n store,\n lightPush,\n filter\n ) as LightNode;\n}\n","import type { GossipSub } from \"@chainsafe/libp2p-gossipsub\";\nimport { noise } from \"@chainsafe/libp2p-noise\";\nimport { bootstrap } from \"@libp2p/bootstrap\";\nimport { identify } from \"@libp2p/identify\";\nimport { mplex } from \"@libp2p/mplex\";\nimport { ping } from \"@libp2p/ping\";\nimport { webSockets } from \"@libp2p/websockets\";\nimport { all as filterAll } from \"@libp2p/websockets/filters\";\nimport { wakuMetadata } from \"@waku/core\";\nimport {\n type CreateLibp2pOptions,\n DefaultPubsubTopic,\n type IMetadata,\n type Libp2p,\n type Libp2pComponents,\n type ShardInfo\n} from \"@waku/interfaces\";\nimport { wakuGossipSub } from \"@waku/relay\";\nimport { ensureShardingConfigured } from \"@waku/utils\";\nimport { createLibp2p } from \"libp2p\";\n\nimport { CreateWakuNodeOptions, DefaultUserAgent } from \"../waku.js\";\n\nimport { defaultPeerDiscoveries } from \"./discovery.js\";\n\ntype PubsubService = {\n pubsub?: (components: Libp2pComponents) => GossipSub;\n};\n\ntype MetadataService = {\n metadata?: (components: Libp2pComponents) => IMetadata;\n};\n\nexport async function defaultLibp2p(\n shardInfo?: ShardInfo,\n wakuGossipSub?: PubsubService[\"pubsub\"],\n options?: Partial,\n userAgent?: string\n): Promise {\n if (!options?.hideWebSocketInfo && process?.env?.NODE_ENV !== \"test\") {\n /* eslint-disable no-console */\n console.info(\n \"%cIgnore WebSocket connection failures\",\n \"background: gray; color: white; font-size: x-large\"\n );\n console.info(\n \"%cWaku tries to discover peers and some of them are expected to fail\",\n \"background: gray; color: white; font-size: x-large\"\n );\n /* eslint-enable no-console */\n }\n\n const pubsubService: PubsubService = wakuGossipSub\n ? { pubsub: wakuGossipSub }\n : {};\n\n const metadataService: MetadataService = shardInfo\n ? { metadata: wakuMetadata(shardInfo) }\n : {};\n\n return createLibp2p({\n connectionManager: {\n minConnections: 1\n },\n transports: [webSockets({ filter: filterAll })],\n streamMuxers: [mplex()],\n connectionEncryption: [noise()],\n ...options,\n services: {\n identify: identify({\n agentVersion: userAgent ?? DefaultUserAgent\n }),\n ping: ping(),\n ...metadataService,\n ...pubsubService,\n ...options?.services\n }\n }) as any as Libp2p; // TODO: make libp2p include it;\n}\n\nexport async function createLibp2pAndUpdateOptions(\n options: CreateWakuNodeOptions\n): Promise {\n const shardInfo = options.shardInfo\n ? ensureShardingConfigured(options.shardInfo)\n : undefined;\n\n options.pubsubTopics = shardInfo?.pubsubTopics ??\n options.pubsubTopics ?? [DefaultPubsubTopic];\n\n const libp2pOptions = options?.libp2p ?? {};\n const peerDiscovery = libp2pOptions.peerDiscovery ?? [];\n\n if (options?.defaultBootstrap) {\n peerDiscovery.push(...defaultPeerDiscoveries(options.pubsubTopics));\n }\n\n if (options?.bootstrapPeers) {\n peerDiscovery.push(bootstrap({ list: options.bootstrapPeers }));\n }\n\n libp2pOptions.peerDiscovery = peerDiscovery;\n\n const libp2p = await defaultLibp2p(\n shardInfo?.shardInfo,\n wakuGossipSub(options),\n libp2pOptions,\n options?.userAgent\n );\n\n return libp2p;\n}\n","import type { PeerDiscovery } from \"@libp2p/interface\";\nimport {\n enrTree,\n wakuDnsDiscovery,\n wakuLocalPeerCacheDiscovery,\n wakuPeerExchangeDiscovery\n} from \"@waku/discovery\";\nimport { type Libp2pComponents, PubsubTopic } from \"@waku/interfaces\";\n\nconst DEFAULT_NODE_REQUIREMENTS = {\n lightPush: 1,\n filter: 1,\n store: 1\n};\n\nexport function defaultPeerDiscoveries(\n pubsubTopics: PubsubTopic[]\n): ((components: Libp2pComponents) => PeerDiscovery)[] {\n const discoveries = [\n wakuDnsDiscovery([enrTree[\"SANDBOX\"]], DEFAULT_NODE_REQUIREMENTS),\n wakuLocalPeerCacheDiscovery(),\n wakuPeerExchangeDiscovery(pubsubTopics)\n ];\n return discoveries;\n}\n","import type { Multiaddr } from \"@multiformats/multiaddr\";\nimport { createDecoder, DecodedMessage, waitForRemotePeer } from \"@waku/core\";\nimport {\n Callback,\n IDecoder,\n IFilterSubscription,\n LightNode,\n Protocols\n} from \"@waku/interfaces\";\nimport {\n contentTopicToPubsubTopic,\n shardInfoToPubsubTopics\n} from \"@waku/utils\";\n\nimport { createLightNode } from \"../light-node/index.js\";\n\ninterface CreateTopicOptions {\n waku?: LightNode;\n peer: Multiaddr;\n}\n\n// Given a Waku node, peer Multiaddr, and content topic, creates a decoder and\n// subscription for that content topic.\nasync function prepareSubscription(\n waku: LightNode,\n contentTopic: string,\n peer: Multiaddr\n): Promise<{\n decoder: IDecoder;\n subscription: IFilterSubscription;\n}> {\n // Validate that the Waku node matches assumptions\n if (!waku.filter) {\n throw new Error(\"Filter protocol missing from Waku node\");\n }\n const { shardInfo } = waku.libp2p.components.metadata;\n if (!shardInfo) {\n throw new Error(\"Shard info missing from Waku node.\");\n }\n\n // Validate content topic and ensure node is configured for its corresponding pubsub topic\n const pubsubTopics = shardInfoToPubsubTopics(shardInfo);\n const pubsubTopic = contentTopicToPubsubTopic(contentTopic);\n if (!pubsubTopics.includes(pubsubTopic))\n throw new Error(\n \"Content topic does not match any pubsub topic in shard info.\"\n );\n\n await waku.dial(peer);\n await waitForRemotePeer(waku, [Protocols.Filter]);\n\n // Create decoder and subscription\n let decoder = createDecoder(contentTopic, pubsubTopic);\n if (decoder) decoder = decoder ?? decoder;\n const subscription = await waku.filter.createSubscription(pubsubTopic);\n\n return { decoder, subscription };\n}\n\n/**\n * Creates a subscription and streams all new messages for a content topic.\n * Will create a light node configured for the content topic with default settings if a node is not provided in `opts`.\n * Assumes node is using autosharding.\n * @param contentTopic\n * @param opts\n */\nexport async function streamContentTopic(\n contentTopic: string,\n opts: CreateTopicOptions\n): Promise<[ReadableStream, LightNode]> {\n opts.waku =\n opts.waku ??\n (await createLightNode({\n shardInfo: { contentTopics: [contentTopic] }\n }));\n const { decoder, subscription } = await prepareSubscription(\n opts.waku,\n contentTopic,\n opts.peer\n );\n\n // Create a ReadableStream that receives any messages for the content topic\n const messageStream = new ReadableStream({\n async start(controller) {\n await subscription.subscribe(decoder, (message) => {\n controller.enqueue(message);\n });\n },\n cancel() {\n return subscription.unsubscribe([contentTopic]);\n }\n });\n return [messageStream, opts.waku];\n}\n\n/**\n * Subscribes to new messages for a content topic via callback function.\n * Will create a light node configured for the content topic with default settings if a node is not provided in `opts`.\n * Assumes node is using autosharding.\n * @param contentTopic\n * @param callback Called every time a new message is received on the content topic\n * @param opts\n */\nexport async function subscribeToContentTopic(\n contentTopic: string,\n callback: Callback,\n opts: CreateTopicOptions\n): Promise<{ subscription: IFilterSubscription; waku: LightNode }> {\n opts.waku =\n opts.waku ??\n (await createLightNode({\n shardInfo: { contentTopics: [contentTopic] }\n }));\n const { decoder, subscription } = await prepareSubscription(\n opts.waku,\n contentTopic,\n opts.peer\n );\n await subscription.subscribe(decoder, callback);\n return { subscription, waku: opts.waku };\n}\n","import type { Stream } from \"@libp2p/interface\";\nimport { isPeerId, PeerId } from \"@libp2p/interface\";\nimport { multiaddr, Multiaddr, MultiaddrInput } from \"@multiformats/multiaddr\";\nimport { ConnectionManager, DecodedMessage } from \"@waku/core\";\nimport type {\n Callback,\n IFilter,\n IFilterSubscription,\n ILightPushSDK,\n IRelay,\n IStoreSDK,\n Libp2p,\n LightNode,\n ProtocolCreateOptions,\n PubsubTopic,\n Waku\n} from \"@waku/interfaces\";\nimport { Protocols } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\n\nimport { subscribeToContentTopic } from \"./utils/content_topic.js\";\n\nexport const DefaultPingKeepAliveValueSecs = 5 * 60;\nexport const DefaultRelayKeepAliveValueSecs = 5 * 60;\nexport const DefaultUserAgent = \"js-waku\";\n\nconst log = new Logger(\"waku\");\n\nexport interface WakuOptions {\n /**\n * Set keep alive frequency in seconds: Waku will send a `/ipfs/ping/1.0.0`\n * request to each peer after the set number of seconds. Set to 0 to disable.\n *\n * @default {@link @waku/core.DefaultPingKeepAliveValueSecs}\n */\n pingKeepAlive?: number;\n /**\n * Set keep alive frequency in seconds: Waku will send a ping message over\n * relay to each peer after the set number of seconds. Set to 0 to disable.\n *\n * @default {@link @waku/core.DefaultRelayKeepAliveValueSecs}\n */\n relayKeepAlive?: number;\n /**\n * Set the user agent string to be used in identification of the node.\n * @default {@link @waku/core.DefaultUserAgent}\n */\n userAgent?: string;\n pubsubTopics: PubsubTopic[];\n}\n\nexport type CreateWakuNodeOptions = ProtocolCreateOptions &\n Partial;\n\nexport class WakuNode implements Waku {\n public libp2p: Libp2p;\n public relay?: IRelay;\n public store?: IStoreSDK;\n public filter?: IFilter;\n public lightPush?: ILightPushSDK;\n public connectionManager: ConnectionManager;\n public readonly pubsubTopics: PubsubTopic[];\n\n constructor(\n options: WakuOptions,\n libp2p: Libp2p,\n store?: (libp2p: Libp2p) => IStoreSDK,\n lightPush?: (libp2p: Libp2p) => ILightPushSDK,\n filter?: (libp2p: Libp2p) => IFilter,\n relay?: (libp2p: Libp2p) => IRelay\n ) {\n if (options.pubsubTopics.length == 0) {\n throw new Error(\"At least one pubsub topic must be provided\");\n }\n this.pubsubTopics = options.pubsubTopics;\n\n this.libp2p = libp2p;\n\n if (store) {\n this.store = store(libp2p);\n }\n if (filter) {\n this.filter = filter(libp2p);\n }\n if (lightPush) {\n this.lightPush = lightPush(libp2p);\n }\n\n if (relay) {\n this.relay = relay(libp2p);\n }\n\n const pingKeepAlive =\n options.pingKeepAlive || DefaultPingKeepAliveValueSecs;\n const relayKeepAlive = this.relay\n ? options.relayKeepAlive || DefaultRelayKeepAliveValueSecs\n : 0;\n\n const peerId = this.libp2p.peerId.toString();\n\n this.connectionManager = ConnectionManager.create(\n peerId,\n libp2p,\n { pingKeepAlive, relayKeepAlive },\n this.pubsubTopics,\n this.relay\n );\n\n log.info(\n \"Waku node created\",\n peerId,\n `relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this\n .lightPush}, filter: ${!!this.filter}`\n );\n }\n\n /**\n * Dials to the provided peer.\n *\n * @param peer The peer to dial\n * @param protocols Waku protocols we expect from the peer; Defaults to mounted protocols\n */\n async dial(\n peer: PeerId | MultiaddrInput,\n protocols?: Protocols[]\n ): Promise {\n const _protocols = protocols ?? [];\n const peerId = mapToPeerIdOrMultiaddr(peer);\n\n if (typeof protocols === \"undefined\") {\n this.relay && _protocols.push(Protocols.Relay);\n this.store && _protocols.push(Protocols.Store);\n this.filter && _protocols.push(Protocols.Filter);\n this.lightPush && _protocols.push(Protocols.LightPush);\n }\n\n const codecs: string[] = [];\n if (_protocols.includes(Protocols.Relay)) {\n if (this.relay) {\n this.relay.gossipSub.multicodecs.forEach((codec: string) =>\n codecs.push(codec)\n );\n } else {\n log.error(\n \"Relay codec not included in dial codec: protocol not mounted locally\"\n );\n }\n }\n if (_protocols.includes(Protocols.Store)) {\n if (this.store) {\n codecs.push(this.store.protocol.multicodec);\n } else {\n log.error(\n \"Store codec not included in dial codec: protocol not mounted locally\"\n );\n }\n }\n if (_protocols.includes(Protocols.LightPush)) {\n if (this.lightPush) {\n codecs.push(this.lightPush.protocol.multicodec);\n } else {\n log.error(\n \"Light Push codec not included in dial codec: protocol not mounted locally\"\n );\n }\n }\n if (_protocols.includes(Protocols.Filter)) {\n if (this.filter) {\n codecs.push(this.filter.multicodec);\n } else {\n log.error(\n \"Filter codec not included in dial codec: protocol not mounted locally\"\n );\n }\n }\n\n log.info(`Dialing to ${peerId.toString()} with protocols ${_protocols}`);\n\n return this.libp2p.dialProtocol(peerId, codecs);\n }\n\n async start(): Promise {\n await this.libp2p.start();\n }\n\n async stop(): Promise {\n this.connectionManager.stop();\n await this.libp2p.stop();\n }\n\n async subscribeToContentTopic(\n contentTopic: string,\n peer: Multiaddr,\n callback: Callback\n ): Promise {\n return (\n await subscribeToContentTopic(contentTopic, callback, {\n waku: this as LightNode,\n peer\n })\n ).subscription;\n }\n\n isStarted(): boolean {\n return this.libp2p.status == \"started\";\n }\n\n isConnected(): boolean {\n return this.connectionManager.isConnected();\n }\n\n /**\n * Return the local multiaddr with peer id on which libp2p is listening.\n *\n * @throws if libp2p is not listening on localhost.\n */\n getLocalMultiaddrWithID(): string {\n const localMultiaddr = this.libp2p\n .getMultiaddrs()\n .find((addr) => addr.toString().match(/127\\.0\\.0\\.1/));\n if (!localMultiaddr || localMultiaddr.toString() === \"\") {\n throw \"Not listening on localhost\";\n }\n return localMultiaddr + \"/p2p/\" + this.libp2p.peerId.toString();\n }\n}\nfunction mapToPeerIdOrMultiaddr(\n peerId: PeerId | MultiaddrInput\n): PeerId | Multiaddr {\n return isPeerId(peerId) ? peerId : multiaddr(peerId);\n}\n","import type { NodeCapabilityCount } from \"@waku/interfaces\";\n\nexport const enrTree = {\n TEST: \"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im\",\n SANDBOX:\n \"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im\"\n};\n\nexport const DEFAULT_BOOTSTRAP_TAG_NAME = \"bootstrap\";\nexport const DEFAULT_BOOTSTRAP_TAG_VALUE = 50;\nexport const DEFAULT_BOOTSTRAP_TAG_TTL = 100_000_000;\n\nexport const DEFAULT_NODE_REQUIREMENTS: Partial = {\n store: 2,\n filter: 1,\n lightPush: 1\n};\n","/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\nimport * as nodeCrypto from 'crypto';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _3n = BigInt(3);\nconst _8n = BigInt(8);\nconst CURVE = Object.freeze({\n a: _0n,\n b: BigInt(7),\n P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: _1n,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n});\nconst divNearest = (a, b) => (a + b / _2n) / b;\nconst endo = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar(k) {\n const { n } = CURVE;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000');\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalarEndo: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n};\nconst fieldLen = 32;\nconst groupLen = 32;\nconst hashLen = 32;\nconst compressedLen = fieldLen + 1;\nconst uncompressedLen = 2 * fieldLen + 1;\nexport { CURVE };\nfunction weierstrass(x) {\n const { a, b } = CURVE;\n const x2 = mod(x * x);\n const x3 = mod(x2 * x);\n return mod(x3 + a * x + b);\n}\nconst USE_ENDOMORPHISM = CURVE.a === _0n;\nclass ShaError extends Error {\n constructor(message) {\n super(message);\n }\n}\nfunction assertJacPoint(other) {\n if (!(other instanceof JacobianPoint))\n throw new TypeError('JacobianPoint expected');\n}\nclass JacobianPoint {\n constructor(x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n static fromAffine(p) {\n if (!(p instanceof Point)) {\n throw new TypeError('JacobianPoint#fromAffine: expected Point');\n }\n if (p.equals(Point.ZERO))\n return JacobianPoint.ZERO;\n return new JacobianPoint(p.x, p.y, _1n);\n }\n static toAffineBatch(points) {\n const toInv = invertBatch(points.map((p) => p.z));\n return points.map((p, i) => p.toAffine(toInv[i]));\n }\n static normalizeZ(points) {\n return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine);\n }\n equals(other) {\n assertJacPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n const Z1Z1 = mod(Z1 * Z1);\n const Z2Z2 = mod(Z2 * Z2);\n const U1 = mod(X1 * Z2Z2);\n const U2 = mod(X2 * Z1Z1);\n const S1 = mod(mod(Y1 * Z2) * Z2Z2);\n const S2 = mod(mod(Y2 * Z1) * Z1Z1);\n return U1 === U2 && S1 === S2;\n }\n negate() {\n return new JacobianPoint(this.x, mod(-this.y), this.z);\n }\n double() {\n const { x: X1, y: Y1, z: Z1 } = this;\n const A = mod(X1 * X1);\n const B = mod(Y1 * Y1);\n const C = mod(B * B);\n const x1b = X1 + B;\n const D = mod(_2n * (mod(x1b * x1b) - A - C));\n const E = mod(_3n * A);\n const F = mod(E * E);\n const X3 = mod(F - _2n * D);\n const Y3 = mod(E * (D - X3) - _8n * C);\n const Z3 = mod(_2n * Y1 * Z1);\n return new JacobianPoint(X3, Y3, Z3);\n }\n add(other) {\n assertJacPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n if (X2 === _0n || Y2 === _0n)\n return this;\n if (X1 === _0n || Y1 === _0n)\n return other;\n const Z1Z1 = mod(Z1 * Z1);\n const Z2Z2 = mod(Z2 * Z2);\n const U1 = mod(X1 * Z2Z2);\n const U2 = mod(X2 * Z1Z1);\n const S1 = mod(mod(Y1 * Z2) * Z2Z2);\n const S2 = mod(mod(Y2 * Z1) * Z1Z1);\n const H = mod(U2 - U1);\n const r = mod(S2 - S1);\n if (H === _0n) {\n if (r === _0n) {\n return this.double();\n }\n else {\n return JacobianPoint.ZERO;\n }\n }\n const HH = mod(H * H);\n const HHH = mod(H * HH);\n const V = mod(U1 * HH);\n const X3 = mod(r * r - HHH - _2n * V);\n const Y3 = mod(r * (V - X3) - S1 * HHH);\n const Z3 = mod(Z1 * Z2 * H);\n return new JacobianPoint(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiplyUnsafe(scalar) {\n const P0 = JacobianPoint.ZERO;\n if (typeof scalar === 'bigint' && scalar === _0n)\n return P0;\n let n = normalizeScalar(scalar);\n if (n === _1n)\n return this;\n if (!USE_ENDOMORPHISM) {\n let p = P0;\n let d = this;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = P0;\n let k2p = P0;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);\n return k1p.add(k2p);\n }\n precomputeWindow(W) {\n const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1;\n const points = [];\n let p = this;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n for (let i = 1; i < 2 ** (W - 1); i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n wNAF(n, affinePoint) {\n if (!affinePoint && this.equals(JacobianPoint.BASE))\n affinePoint = Point.BASE;\n const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;\n if (256 % W) {\n throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');\n }\n let precomputes = affinePoint && pointPrecomputes.get(affinePoint);\n if (!precomputes) {\n precomputes = this.precomputeWindow(W);\n if (affinePoint && W !== 1) {\n precomputes = JacobianPoint.normalizeZ(precomputes);\n pointPrecomputes.set(affinePoint, precomputes);\n }\n }\n let p = JacobianPoint.ZERO;\n let f = JacobianPoint.BASE;\n const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W);\n const windowSize = 2 ** (W - 1);\n const mask = BigInt(2 ** W - 1);\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n let wbits = Number(n & mask);\n n >>= shiftBy;\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1;\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n return { p, f };\n }\n multiply(scalar, affinePoint) {\n let n = normalizeScalar(scalar);\n let point;\n let fake;\n if (USE_ENDOMORPHISM) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);\n let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);\n k1p = constTimeNegate(k1neg, k1p);\n k2p = constTimeNegate(k2neg, k2p);\n k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n, affinePoint);\n point = p;\n fake = f;\n }\n return JacobianPoint.normalizeZ([point, fake])[0];\n }\n toAffine(invZ) {\n const { x, y, z } = this;\n const is0 = this.equals(JacobianPoint.ZERO);\n if (invZ == null)\n invZ = is0 ? _8n : invert(z);\n const iz1 = invZ;\n const iz2 = mod(iz1 * iz1);\n const iz3 = mod(iz2 * iz1);\n const ax = mod(x * iz2);\n const ay = mod(y * iz3);\n const zz = mod(z * iz1);\n if (is0)\n return Point.ZERO;\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return new Point(ax, ay);\n }\n}\nJacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n);\nJacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n);\nfunction constTimeNegate(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\nconst pointPrecomputes = new WeakMap();\nexport class Point {\n constructor(x, y) {\n this.x = x;\n this.y = y;\n }\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n hasEvenY() {\n return this.y % _2n === _0n;\n }\n static fromCompressedHex(bytes) {\n const isShort = bytes.length === 32;\n const x = bytesToNumber(isShort ? bytes : bytes.subarray(1));\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrass(x);\n let y = sqrtMod(y2);\n const isYOdd = (y & _1n) === _1n;\n if (isShort) {\n if (isYOdd)\n y = mod(-y);\n }\n else {\n const isFirstByteOdd = (bytes[0] & 1) === 1;\n if (isFirstByteOdd !== isYOdd)\n y = mod(-y);\n }\n const point = new Point(x, y);\n point.assertValidity();\n return point;\n }\n static fromUncompressedHex(bytes) {\n const x = bytesToNumber(bytes.subarray(1, fieldLen + 1));\n const y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1));\n const point = new Point(x, y);\n point.assertValidity();\n return point;\n }\n static fromHex(hex) {\n const bytes = ensureBytes(hex);\n const len = bytes.length;\n const header = bytes[0];\n if (len === fieldLen)\n return this.fromCompressedHex(bytes);\n if (len === compressedLen && (header === 0x02 || header === 0x03)) {\n return this.fromCompressedHex(bytes);\n }\n if (len === uncompressedLen && header === 0x04)\n return this.fromUncompressedHex(bytes);\n throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${len}`);\n }\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normalizePrivateKey(privateKey));\n }\n static fromSignature(msgHash, signature, recovery) {\n const { r, s } = normalizeSignature(signature);\n if (![0, 1, 2, 3].includes(recovery))\n throw new Error('Cannot recover: invalid recovery bit');\n const h = truncateHash(ensureBytes(msgHash));\n const { n } = CURVE;\n const radj = recovery === 2 || recovery === 3 ? r + n : r;\n const rinv = invert(radj, n);\n const u1 = mod(-h * rinv, n);\n const u2 = mod(s * rinv, n);\n const prefix = recovery & 1 ? '03' : '02';\n const R = Point.fromHex(prefix + numTo32bStr(radj));\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);\n if (!Q)\n throw new Error('Cannot recover signature: point at infinify');\n Q.assertValidity();\n return Q;\n }\n toRawBytes(isCompressed = false) {\n return hexToBytes(this.toHex(isCompressed));\n }\n toHex(isCompressed = false) {\n const x = numTo32bStr(this.x);\n if (isCompressed) {\n const prefix = this.hasEvenY() ? '02' : '03';\n return `${prefix}${x}`;\n }\n else {\n return `04${x}${numTo32bStr(this.y)}`;\n }\n }\n toHexX() {\n return this.toHex(true).slice(2);\n }\n toRawX() {\n return this.toRawBytes(true).slice(1);\n }\n assertValidity() {\n const msg = 'Point is not on elliptic curve';\n const { x, y } = this;\n if (!isValidFieldElement(x) || !isValidFieldElement(y))\n throw new Error(msg);\n const left = mod(y * y);\n const right = weierstrass(x);\n if (mod(left - right) !== _0n)\n throw new Error(msg);\n }\n equals(other) {\n return this.x === other.x && this.y === other.y;\n }\n negate() {\n return new Point(this.x, mod(-this.y));\n }\n double() {\n return JacobianPoint.fromAffine(this).double().toAffine();\n }\n add(other) {\n return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine();\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiply(scalar) {\n return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine();\n }\n multiplyAndAddUnsafe(Q, a, b) {\n const P = JacobianPoint.fromAffine(this);\n const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);\n const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b);\n const sum = aP.add(bQ);\n return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine();\n }\n}\nPoint.BASE = new Point(CURVE.Gx, CURVE.Gy);\nPoint.ZERO = new Point(_0n, _0n);\nfunction sliceDER(s) {\n return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s;\n}\nfunction parseDERInt(data) {\n if (data.length < 2 || data[0] !== 0x02) {\n throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);\n }\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len) {\n throw new Error(`Invalid signature integer: wrong length`);\n }\n if (res[0] === 0x00 && res[1] <= 0x7f) {\n throw new Error('Invalid signature integer: trailing length');\n }\n return { data: bytesToNumber(res), left: data.subarray(len + 2) };\n}\nfunction parseDERSignature(data) {\n if (data.length < 2 || data[0] != 0x30) {\n throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);\n }\n if (data[1] !== data.length - 2) {\n throw new Error('Invalid signature: incorrect length');\n }\n const { data: r, left: sBytes } = parseDERInt(data.subarray(2));\n const { data: s, left: rBytesLeft } = parseDERInt(sBytes);\n if (rBytesLeft.length) {\n throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);\n }\n return { r, s };\n}\nexport class Signature {\n constructor(r, s) {\n this.r = r;\n this.s = s;\n this.assertValidity();\n }\n static fromCompact(hex) {\n const arr = hex instanceof Uint8Array;\n const name = 'Signature.fromCompact';\n if (typeof hex !== 'string' && !arr)\n throw new TypeError(`${name}: Expected string or Uint8Array`);\n const str = arr ? bytesToHex(hex) : hex;\n if (str.length !== 128)\n throw new Error(`${name}: Expected 64-byte hex`);\n return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));\n }\n static fromDER(hex) {\n const arr = hex instanceof Uint8Array;\n if (typeof hex !== 'string' && !arr)\n throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);\n const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex));\n return new Signature(r, s);\n }\n static fromHex(hex) {\n return this.fromDER(hex);\n }\n assertValidity() {\n const { r, s } = this;\n if (!isWithinCurveOrder(r))\n throw new Error('Invalid Signature: r must be 0 < r < n');\n if (!isWithinCurveOrder(s))\n throw new Error('Invalid Signature: s must be 0 < s < n');\n }\n hasHighS() {\n const HALF = CURVE.n >> _1n;\n return this.s > HALF;\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this;\n }\n toDERRawBytes() {\n return hexToBytes(this.toDERHex());\n }\n toDERHex() {\n const sHex = sliceDER(numberToHexUnpadded(this.s));\n const rHex = sliceDER(numberToHexUnpadded(this.r));\n const sHexL = sHex.length / 2;\n const rHexL = rHex.length / 2;\n const sLen = numberToHexUnpadded(sHexL);\n const rLen = numberToHexUnpadded(rHexL);\n const length = numberToHexUnpadded(rHexL + sHexL + 4);\n return `30${length}02${rLen}${rHex}02${sLen}${sHex}`;\n }\n toRawBytes() {\n return this.toDERRawBytes();\n }\n toHex() {\n return this.toDERHex();\n }\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numTo32bStr(this.r) + numTo32bStr(this.s);\n }\n}\nfunction concatBytes(...arrays) {\n if (!arrays.every((b) => b instanceof Uint8Array))\n throw new Error('Uint8Array list expected');\n if (arrays.length === 1)\n return arrays[0];\n const length = arrays.reduce((a, arr) => a + arr.length, 0);\n const result = new Uint8Array(length);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const arr = arrays[i];\n result.set(arr, pad);\n pad += arr.length;\n }\n return result;\n}\nconst hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\nfunction bytesToHex(uint8a) {\n if (!(uint8a instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n let hex = '';\n for (let i = 0; i < uint8a.length; i++) {\n hex += hexes[uint8a[i]];\n }\n return hex;\n}\nconst POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');\nfunction numTo32bStr(num) {\n if (typeof num !== 'bigint')\n throw new Error('Expected bigint');\n if (!(_0n <= num && num < POW_2_256))\n throw new Error('Expected number 0 <= n < 2^256');\n return num.toString(16).padStart(64, '0');\n}\nfunction numTo32b(num) {\n const b = hexToBytes(numTo32bStr(num));\n if (b.length !== 32)\n throw new Error('Error: expected 32 bytes');\n return b;\n}\nfunction numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nfunction hexToNumber(hex) {\n if (typeof hex !== 'string') {\n throw new TypeError('hexToNumber: expected string, got ' + typeof hex);\n }\n return BigInt(`0x${hex}`);\n}\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string') {\n throw new TypeError('hexToBytes: expected string, got ' + typeof hex);\n }\n if (hex.length % 2)\n throw new Error('hexToBytes: received invalid unpadded hex' + hex.length);\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\nfunction bytesToNumber(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nfunction ensureBytes(hex) {\n return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);\n}\nfunction normalizeScalar(num) {\n if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0)\n return BigInt(num);\n if (typeof num === 'bigint' && isWithinCurveOrder(num))\n return num;\n throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n');\n}\nfunction mod(a, b = CURVE.P) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\nfunction pow2(x, power) {\n const { P } = CURVE;\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= P;\n }\n return res;\n}\nfunction sqrtMod(x) {\n const { P } = CURVE;\n const _6n = BigInt(6);\n const _11n = BigInt(11);\n const _22n = BigInt(22);\n const _23n = BigInt(23);\n const _44n = BigInt(44);\n const _88n = BigInt(88);\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\n const b6 = (pow2(b3, _3n) * b3) % P;\n const b9 = (pow2(b6, _3n) * b3) % P;\n const b11 = (pow2(b9, _2n) * b2) % P;\n const b22 = (pow2(b11, _11n) * b11) % P;\n const b44 = (pow2(b22, _22n) * b22) % P;\n const b88 = (pow2(b44, _44n) * b44) % P;\n const b176 = (pow2(b88, _88n) * b88) % P;\n const b220 = (pow2(b176, _44n) * b44) % P;\n const b223 = (pow2(b220, _3n) * b3) % P;\n const t1 = (pow2(b223, _23n) * b22) % P;\n const t2 = (pow2(t1, _6n) * b2) % P;\n const rt = pow2(t2, _2n);\n const xc = (rt * rt) % P;\n if (xc !== x)\n throw new Error('Cannot find square root');\n return rt;\n}\nfunction invert(number, modulo = CURVE.P) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n let a = mod(number, modulo);\n let b = modulo;\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction invertBatch(nums, p = CURVE.P) {\n const scratch = new Array(nums.length);\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (num === _0n)\n return acc;\n scratch[i] = acc;\n return mod(acc * num, p);\n }, _1n);\n const inverted = invert(lastMultiplied, p);\n nums.reduceRight((acc, num, i) => {\n if (num === _0n)\n return acc;\n scratch[i] = mod(acc * scratch[i], p);\n return mod(acc * num, p);\n }, inverted);\n return scratch;\n}\nfunction bits2int_2(bytes) {\n const delta = bytes.length * 8 - groupLen * 8;\n const num = bytesToNumber(bytes);\n return delta > 0 ? num >> BigInt(delta) : num;\n}\nfunction truncateHash(hash, truncateOnly = false) {\n const h = bits2int_2(hash);\n if (truncateOnly)\n return h;\n const { n } = CURVE;\n return h >= n ? h - n : h;\n}\nlet _sha256Sync;\nlet _hmacSha256Sync;\nclass HmacDrbg {\n constructor(hashLen, qByteLen) {\n this.hashLen = hashLen;\n this.qByteLen = qByteLen;\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n this.v = new Uint8Array(hashLen).fill(1);\n this.k = new Uint8Array(hashLen).fill(0);\n this.counter = 0;\n }\n hmac(...values) {\n return utils.hmacSha256(this.k, ...values);\n }\n hmacSync(...values) {\n return _hmacSha256Sync(this.k, ...values);\n }\n checkSync() {\n if (typeof _hmacSha256Sync !== 'function')\n throw new ShaError('hmacSha256Sync needs to be set');\n }\n incr() {\n if (this.counter >= 1000)\n throw new Error('Tried 1,000 k values for sign(), all were invalid');\n this.counter += 1;\n }\n async reseed(seed = new Uint8Array()) {\n this.k = await this.hmac(this.v, Uint8Array.from([0x00]), seed);\n this.v = await this.hmac(this.v);\n if (seed.length === 0)\n return;\n this.k = await this.hmac(this.v, Uint8Array.from([0x01]), seed);\n this.v = await this.hmac(this.v);\n }\n reseedSync(seed = new Uint8Array()) {\n this.checkSync();\n this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed);\n this.v = this.hmacSync(this.v);\n if (seed.length === 0)\n return;\n this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed);\n this.v = this.hmacSync(this.v);\n }\n async generate() {\n this.incr();\n let len = 0;\n const out = [];\n while (len < this.qByteLen) {\n this.v = await this.hmac(this.v);\n const sl = this.v.slice();\n out.push(sl);\n len += this.v.length;\n }\n return concatBytes(...out);\n }\n generateSync() {\n this.checkSync();\n this.incr();\n let len = 0;\n const out = [];\n while (len < this.qByteLen) {\n this.v = this.hmacSync(this.v);\n const sl = this.v.slice();\n out.push(sl);\n len += this.v.length;\n }\n return concatBytes(...out);\n }\n}\nfunction isWithinCurveOrder(num) {\n return _0n < num && num < CURVE.n;\n}\nfunction isValidFieldElement(num) {\n return _0n < num && num < CURVE.P;\n}\nfunction kmdToSig(kBytes, m, d, lowS = true) {\n const { n } = CURVE;\n const k = truncateHash(kBytes, true);\n if (!isWithinCurveOrder(k))\n return;\n const kinv = invert(k, n);\n const q = Point.BASE.multiply(k);\n const r = mod(q.x, n);\n if (r === _0n)\n return;\n const s = mod(kinv * mod(m + d * r, n), n);\n if (s === _0n)\n return;\n let sig = new Signature(r, s);\n let recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n);\n if (lowS && sig.hasHighS()) {\n sig = sig.normalizeS();\n recovery ^= 1;\n }\n return { sig, recovery };\n}\nfunction normalizePrivateKey(key) {\n let num;\n if (typeof key === 'bigint') {\n num = key;\n }\n else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) {\n num = BigInt(key);\n }\n else if (typeof key === 'string') {\n if (key.length !== 2 * groupLen)\n throw new Error('Expected 32 bytes of private key');\n num = hexToNumber(key);\n }\n else if (key instanceof Uint8Array) {\n if (key.length !== groupLen)\n throw new Error('Expected 32 bytes of private key');\n num = bytesToNumber(key);\n }\n else {\n throw new TypeError('Expected valid private key');\n }\n if (!isWithinCurveOrder(num))\n throw new Error('Expected private key: 0 < key < n');\n return num;\n}\nfunction normalizePublicKey(publicKey) {\n if (publicKey instanceof Point) {\n publicKey.assertValidity();\n return publicKey;\n }\n else {\n return Point.fromHex(publicKey);\n }\n}\nfunction normalizeSignature(signature) {\n if (signature instanceof Signature) {\n signature.assertValidity();\n return signature;\n }\n try {\n return Signature.fromDER(signature);\n }\n catch (error) {\n return Signature.fromCompact(signature);\n }\n}\nexport function getPublicKey(privateKey, isCompressed = false) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n}\nexport function recoverPublicKey(msgHash, signature, recovery, isCompressed = false) {\n return Point.fromSignature(msgHash, signature, recovery).toRawBytes(isCompressed);\n}\nfunction isProbPub(item) {\n const arr = item instanceof Uint8Array;\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === compressedLen * 2 || len === uncompressedLen * 2;\n if (item instanceof Point)\n return true;\n return false;\n}\nexport function getSharedSecret(privateA, publicB, isCompressed = false) {\n if (isProbPub(privateA))\n throw new TypeError('getSharedSecret: first arg must be private key');\n if (!isProbPub(publicB))\n throw new TypeError('getSharedSecret: second arg must be public key');\n const b = normalizePublicKey(publicB);\n b.assertValidity();\n return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed);\n}\nfunction bits2int(bytes) {\n const slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes;\n return bytesToNumber(slice);\n}\nfunction bits2octets(bytes) {\n const z1 = bits2int(bytes);\n const z2 = mod(z1, CURVE.n);\n return int2octets(z2 < _0n ? z1 : z2);\n}\nfunction int2octets(num) {\n return numTo32b(num);\n}\nfunction initSigArgs(msgHash, privateKey, extraEntropy) {\n if (msgHash == null)\n throw new Error(`sign: expected valid message hash, not \"${msgHash}\"`);\n const h1 = ensureBytes(msgHash);\n const d = normalizePrivateKey(privateKey);\n const seedArgs = [int2octets(d), bits2octets(h1)];\n if (extraEntropy != null) {\n if (extraEntropy === true)\n extraEntropy = utils.randomBytes(fieldLen);\n const e = ensureBytes(extraEntropy);\n if (e.length !== fieldLen)\n throw new Error(`sign: Expected ${fieldLen} bytes of extra data`);\n seedArgs.push(e);\n }\n const seed = concatBytes(...seedArgs);\n const m = bits2int(h1);\n return { seed, m, d };\n}\nfunction finalizeSig(recSig, opts) {\n const { sig, recovery } = recSig;\n const { der, recovered } = Object.assign({ canonical: true, der: true }, opts);\n const hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes();\n return recovered ? [hashed, recovery] : hashed;\n}\nasync function sign(msgHash, privKey, opts = {}) {\n const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);\n const drbg = new HmacDrbg(hashLen, groupLen);\n await drbg.reseed(seed);\n let sig;\n while (!(sig = kmdToSig(await drbg.generate(), m, d, opts.canonical)))\n await drbg.reseed();\n return finalizeSig(sig, opts);\n}\nfunction signSync(msgHash, privKey, opts = {}) {\n const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);\n const drbg = new HmacDrbg(hashLen, groupLen);\n drbg.reseedSync(seed);\n let sig;\n while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical)))\n drbg.reseedSync();\n return finalizeSig(sig, opts);\n}\nexport { sign, signSync };\nconst vopts = { strict: true };\nexport function verify(signature, msgHash, publicKey, opts = vopts) {\n let sig;\n try {\n sig = normalizeSignature(signature);\n msgHash = ensureBytes(msgHash);\n }\n catch (error) {\n return false;\n }\n const { r, s } = sig;\n if (opts.strict && sig.hasHighS())\n return false;\n const h = truncateHash(msgHash);\n let P;\n try {\n P = normalizePublicKey(publicKey);\n }\n catch (error) {\n return false;\n }\n const { n } = CURVE;\n const sinv = invert(s, n);\n const u1 = mod(h * sinv, n);\n const u2 = mod(r * sinv, n);\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2);\n if (!R)\n return false;\n const v = mod(R.x, n);\n return v === r;\n}\nfunction schnorrChallengeFinalize(ch) {\n return mod(bytesToNumber(ch), CURVE.n);\n}\nclass SchnorrSignature {\n constructor(r, s) {\n this.r = r;\n this.s = s;\n this.assertValidity();\n }\n static fromHex(hex) {\n const bytes = ensureBytes(hex);\n if (bytes.length !== 64)\n throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`);\n const r = bytesToNumber(bytes.subarray(0, 32));\n const s = bytesToNumber(bytes.subarray(32, 64));\n return new SchnorrSignature(r, s);\n }\n assertValidity() {\n const { r, s } = this;\n if (!isValidFieldElement(r) || !isWithinCurveOrder(s))\n throw new Error('Invalid signature');\n }\n toHex() {\n return numTo32bStr(this.r) + numTo32bStr(this.s);\n }\n toRawBytes() {\n return hexToBytes(this.toHex());\n }\n}\nfunction schnorrGetPublicKey(privateKey) {\n return Point.fromPrivateKey(privateKey).toRawX();\n}\nclass InternalSchnorrSignature {\n constructor(message, privateKey, auxRand = utils.randomBytes()) {\n if (message == null)\n throw new TypeError(`sign: Expected valid message, not \"${message}\"`);\n this.m = ensureBytes(message);\n const { x, scalar } = this.getScalar(normalizePrivateKey(privateKey));\n this.px = x;\n this.d = scalar;\n this.rand = ensureBytes(auxRand);\n if (this.rand.length !== 32)\n throw new TypeError('sign: Expected 32 bytes of aux randomness');\n }\n getScalar(priv) {\n const point = Point.fromPrivateKey(priv);\n const scalar = point.hasEvenY() ? priv : CURVE.n - priv;\n return { point, scalar, x: point.toRawX() };\n }\n initNonce(d, t0h) {\n return numTo32b(d ^ bytesToNumber(t0h));\n }\n finalizeNonce(k0h) {\n const k0 = mod(bytesToNumber(k0h), CURVE.n);\n if (k0 === _0n)\n throw new Error('sign: Creation of signature failed. k is zero');\n const { point: R, x: rx, scalar: k } = this.getScalar(k0);\n return { R, rx, k };\n }\n finalizeSig(R, k, e, d) {\n return new SchnorrSignature(R.x, mod(k + e * d, CURVE.n)).toRawBytes();\n }\n error() {\n throw new Error('sign: Invalid signature produced');\n }\n async calc() {\n const { m, d, px, rand } = this;\n const tag = utils.taggedHash;\n const t = this.initNonce(d, await tag(TAGS.aux, rand));\n const { R, rx, k } = this.finalizeNonce(await tag(TAGS.nonce, t, px, m));\n const e = schnorrChallengeFinalize(await tag(TAGS.challenge, rx, px, m));\n const sig = this.finalizeSig(R, k, e, d);\n if (!(await schnorrVerify(sig, m, px)))\n this.error();\n return sig;\n }\n calcSync() {\n const { m, d, px, rand } = this;\n const tag = utils.taggedHashSync;\n const t = this.initNonce(d, tag(TAGS.aux, rand));\n const { R, rx, k } = this.finalizeNonce(tag(TAGS.nonce, t, px, m));\n const e = schnorrChallengeFinalize(tag(TAGS.challenge, rx, px, m));\n const sig = this.finalizeSig(R, k, e, d);\n if (!schnorrVerifySync(sig, m, px))\n this.error();\n return sig;\n }\n}\nasync function schnorrSign(msg, privKey, auxRand) {\n return new InternalSchnorrSignature(msg, privKey, auxRand).calc();\n}\nfunction schnorrSignSync(msg, privKey, auxRand) {\n return new InternalSchnorrSignature(msg, privKey, auxRand).calcSync();\n}\nfunction initSchnorrVerify(signature, message, publicKey) {\n const raw = signature instanceof SchnorrSignature;\n const sig = raw ? signature : SchnorrSignature.fromHex(signature);\n if (raw)\n sig.assertValidity();\n return {\n ...sig,\n m: ensureBytes(message),\n P: normalizePublicKey(publicKey),\n };\n}\nfunction finalizeSchnorrVerify(r, P, s, e) {\n const R = Point.BASE.multiplyAndAddUnsafe(P, normalizePrivateKey(s), mod(-e, CURVE.n));\n if (!R || !R.hasEvenY() || R.x !== r)\n return false;\n return true;\n}\nasync function schnorrVerify(signature, message, publicKey) {\n try {\n const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);\n const e = schnorrChallengeFinalize(await utils.taggedHash(TAGS.challenge, numTo32b(r), P.toRawX(), m));\n return finalizeSchnorrVerify(r, P, s, e);\n }\n catch (error) {\n return false;\n }\n}\nfunction schnorrVerifySync(signature, message, publicKey) {\n try {\n const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);\n const e = schnorrChallengeFinalize(utils.taggedHashSync(TAGS.challenge, numTo32b(r), P.toRawX(), m));\n return finalizeSchnorrVerify(r, P, s, e);\n }\n catch (error) {\n if (error instanceof ShaError)\n throw error;\n return false;\n }\n}\nexport const schnorr = {\n Signature: SchnorrSignature,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n signSync: schnorrSignSync,\n verifySync: schnorrVerifySync,\n};\nPoint.BASE._setWindowSize(8);\nconst crypto = {\n node: nodeCrypto,\n web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,\n};\nconst TAGS = {\n challenge: 'BIP0340/challenge',\n aux: 'BIP0340/aux',\n nonce: 'BIP0340/nonce',\n};\nconst TAGGED_HASH_PREFIXES = {};\nexport const utils = {\n bytesToHex,\n hexToBytes,\n concatBytes,\n mod,\n invert,\n isValidPrivateKey(privateKey) {\n try {\n normalizePrivateKey(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n _bigintTo32Bytes: numTo32b,\n _normalizePrivateKey: normalizePrivateKey,\n hashToPrivateKey: (hash) => {\n hash = ensureBytes(hash);\n const minLen = groupLen + 8;\n if (hash.length < minLen || hash.length > 1024) {\n throw new Error(`Expected valid bytes of private key as per FIPS 186`);\n }\n const num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n;\n return numTo32b(num);\n },\n randomBytes: (bytesLength = 32) => {\n if (crypto.web) {\n return crypto.web.getRandomValues(new Uint8Array(bytesLength));\n }\n else if (crypto.node) {\n const { randomBytes } = crypto.node;\n return Uint8Array.from(randomBytes(bytesLength));\n }\n else {\n throw new Error(\"The environment doesn't have randomBytes function\");\n }\n },\n randomPrivateKey: () => utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)),\n precompute(windowSize = 8, point = Point.BASE) {\n const cached = point === Point.BASE ? point : new Point(point.x, point.y);\n cached._setWindowSize(windowSize);\n cached.multiply(_3n);\n return cached;\n },\n sha256: async (...messages) => {\n if (crypto.web) {\n const buffer = await crypto.web.subtle.digest('SHA-256', concatBytes(...messages));\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n const { createHash } = crypto.node;\n const hash = createHash('sha256');\n messages.forEach((m) => hash.update(m));\n return Uint8Array.from(hash.digest());\n }\n else {\n throw new Error(\"The environment doesn't have sha256 function\");\n }\n },\n hmacSha256: async (key, ...messages) => {\n if (crypto.web) {\n const ckey = await crypto.web.subtle.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);\n const message = concatBytes(...messages);\n const buffer = await crypto.web.subtle.sign('HMAC', ckey, message);\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n const { createHmac } = crypto.node;\n const hash = createHmac('sha256', key);\n messages.forEach((m) => hash.update(m));\n return Uint8Array.from(hash.digest());\n }\n else {\n throw new Error(\"The environment doesn't have hmac-sha256 function\");\n }\n },\n sha256Sync: undefined,\n hmacSha256Sync: undefined,\n taggedHash: async (tag, ...messages) => {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = await utils.sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return utils.sha256(tagP, ...messages);\n },\n taggedHashSync: (tag, ...messages) => {\n if (typeof _sha256Sync !== 'function')\n throw new ShaError('sha256Sync is undefined, you need to set it');\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = _sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return _sha256Sync(tagP, ...messages);\n },\n _JacobianPoint: JacobianPoint,\n};\nObject.defineProperties(utils, {\n sha256Sync: {\n configurable: false,\n get() {\n return _sha256Sync;\n },\n set(val) {\n if (!_sha256Sync)\n _sha256Sync = val;\n },\n },\n hmacSha256Sync: {\n configurable: false,\n get() {\n return _hmacSha256Sync;\n },\n set(val) {\n if (!_hmacSha256Sync)\n _hmacSha256Sync = val;\n },\n },\n});\n","import * as secp from \"@noble/secp256k1\";\nimport { concat } from \"@waku/utils/bytes\";\nimport sha3 from \"js-sha3\";\n\n/**\n * ECDSA Sign a message with the given private key.\n *\n * @param message The message to sign, usually a hash.\n * @param privateKey The ECDSA private key to use to sign the message.\n *\n * @returns The signature and the recovery id concatenated.\n */\nexport async function sign(\n message: Uint8Array,\n privateKey: Uint8Array\n): Promise {\n const [signature, recoveryId] = await secp.sign(message, privateKey, {\n recovered: true,\n der: false\n });\n return concat(\n [signature, new Uint8Array([recoveryId])],\n signature.length + 1\n );\n}\n\nexport function keccak256(input: Uint8Array): Uint8Array {\n return new Uint8Array(sha3.keccak256.arrayBuffer(input));\n}\n\nexport function compressPublicKey(publicKey: Uint8Array): Uint8Array {\n if (publicKey.length === 64) {\n publicKey = concat([new Uint8Array([4]), publicKey], 65);\n }\n const point = secp.Point.fromHex(publicKey);\n return point.toRawBytes(true);\n}\n\n/**\n * Verify an ECDSA signature.\n */\nexport function verifySignature(\n signature: Uint8Array,\n message: Uint8Array | string,\n publicKey: Uint8Array\n): boolean {\n try {\n const _signature = secp.Signature.fromCompact(signature.slice(0, 64));\n return secp.verify(_signature, message, publicKey);\n } catch {\n return false;\n }\n}\n","// Maximum encoded size of an ENR\nexport const MAX_RECORD_SIZE = 300;\n\nexport const ERR_INVALID_ID = \"Invalid record id\";\n\nexport const ERR_NO_SIGNATURE = \"No valid signature found\";\n\n// The maximum length of byte size of a multiaddr to encode in the `multiaddr` field\n// The size is a big endian 16-bit unsigned integer\nexport const MULTIADDR_LENGTH_SIZE = 2;\n","import { Multiaddr } from \"@multiformats/multiaddr\";\nimport type { IEnr } from \"@waku/interfaces\";\n\nimport { multiaddrFromFields } from \"./multiaddr_from_fields.js\";\n\nexport function locationMultiaddrFromEnrFields(\n enr: IEnr,\n protocol: \"udp\" | \"udp4\" | \"udp6\" | \"tcp\" | \"tcp4\" | \"tcp6\"\n): Multiaddr | undefined {\n switch (protocol) {\n case \"udp\":\n return (\n locationMultiaddrFromEnrFields(enr, \"udp4\") ||\n locationMultiaddrFromEnrFields(enr, \"udp6\")\n );\n case \"tcp\":\n return (\n locationMultiaddrFromEnrFields(enr, \"tcp4\") ||\n locationMultiaddrFromEnrFields(enr, \"tcp6\")\n );\n }\n const isIpv6 = protocol.endsWith(\"6\");\n const ipVal = enr.get(isIpv6 ? \"ip6\" : \"ip\");\n if (!ipVal) return;\n\n const protoName = protocol.slice(0, 3);\n let protoVal;\n switch (protoName) {\n case \"udp\":\n protoVal = isIpv6 ? enr.get(\"udp6\") : enr.get(\"udp\");\n break;\n case \"tcp\":\n protoVal = isIpv6 ? enr.get(\"tcp6\") : enr.get(\"tcp\");\n break;\n default:\n return;\n }\n\n if (!protoVal) return;\n\n return multiaddrFromFields(\n isIpv6 ? \"ip6\" : \"ip4\",\n protoName,\n ipVal,\n protoVal\n );\n}\n","import { multiaddr } from \"@multiformats/multiaddr\";\nimport type { Multiaddr } from \"@multiformats/multiaddr\";\nimport { convertToString } from \"@multiformats/multiaddr/convert\";\n\nexport function multiaddrFromFields(\n ipFamily: string,\n protocol: string,\n ipBytes: Uint8Array,\n protocolBytes: Uint8Array\n): Multiaddr {\n let ma = multiaddr(\"/\" + ipFamily + \"/\" + convertToString(ipFamily, ipBytes));\n\n ma = ma.encapsulate(\n multiaddr(\"/\" + protocol + \"/\" + convertToString(protocol, protocolBytes))\n );\n\n return ma;\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n\nexport function isPromise (thing: any): thing is Promise {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n","import { ed25519 as ed } from '@noble/curves/ed25519'\nimport type { Uint8ArrayKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32\nconst PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed (seed: Uint8Array): Uint8ArrayKeyPair {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw)\n}\n\nexport function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH)\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i]\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i]\n }\n return privateKey\n}\n","/* eslint-env browser */\n\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get (win = globalThis) {\n const nativeCrypto = win.crypto\n\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n 'Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n","import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\n\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' }\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions): AESCipher {\n const algorithm = opts?.algorithm ?? 'AES-GCM'\n let keyLength = opts?.keyLength ?? 16\n const nonceLength = opts?.nonceLength ?? 12\n const digest = opts?.digest ?? 'SHA-256'\n const saltLength = opts?.saltLength ?? 16\n const iterations = opts?.iterations ?? 32767\n\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\n }\n } else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt'])\n }\n\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data)\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)])\n }\n\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt (data: Uint8Array, password: string | Uint8Array): Promise {\n const salt = data.subarray(0, saltLength)\n const nonce = data.subarray(saltLength, saltLength + nonceLength)\n const ciphertext = data.subarray(saltLength + nonceLength)\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: CryptoKey\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt'])\n } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt'])\n }\n } else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } }\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey'])\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt'])\n }\n\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext)\n return new Uint8Array(plaintext)\n }\n\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n","import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n","import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\nimport type { Multibase } from 'multiformats'\n\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter (privateKey: Uint8Array, password: string): Promise> {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\n","const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n","import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = (): Codec => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n","import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n\n this.code = code\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { isPromise } from '../util.js'\nimport * as crypto from './ed25519.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Ed25519PublicKey {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id (): Promise {\n const encoding = identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n }\n\n bytes = ensureKey(bytes, crypto.privateKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength)\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)\n}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const { privateKey, publicKey } = crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array): Promise {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE')\n }\n return key\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport * as utils from './rsa-utils.js'\nimport type { JWKKeyPair } from './interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport { utils }\n\nexport async function generateKey (bits: number): Promise {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey): Promise {\n return webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\nexport function keySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE')\n } else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n","import { CodeError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH')\n }\n return randB(length)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2'\nimport { sha512 } from '@noble/hashes/sha512'\nimport * as asn1js from 'asn1js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport randomBytes from '../random-bytes.js'\nimport webcrypto from '../webcrypto.js'\nimport { type RsaPrivateKey, unmarshalRsaPrivateKey } from './rsa-class.js'\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value\n\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n }\n\n return key\n}\n\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const { result } = asn1js.fromBER(bytes)\n\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values: asn1js.Integer[] = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value\n\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n }\n}\n\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n })\n\n const der = root.toBER()\n\n return new Uint8Array(der, 0, der.byteLength)\n}\n\nfunction bnToBuf (bn: bigint): Uint8Array {\n let hex = bn.toString(16)\n\n if (hex.length % 2 > 0) {\n hex = `0${hex}`\n }\n\n const len = hex.length / 2\n const u8 = new Uint8Array(len)\n\n let i = 0\n let j = 0\n\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16)\n i += 1\n j += 2\n }\n\n return u8\n}\n\nfunction bufToBn (u8: Uint8Array): bigint {\n const hex: string[] = []\n\n u8.forEach(function (i) {\n let h = i.toString(16)\n\n if (h.length % 2 > 0) {\n h = `0${h}`\n }\n\n hex.push(h)\n })\n\n return BigInt('0x' + hex.join(''))\n}\n\nconst SALT_LENGTH = 16\nconst KEY_SIZE = 32\nconst ITERATIONS = 10000\n\nexport async function exportToPem (privateKey: RsaPrivateKey, password: string): Promise {\n const crypto = webcrypto.get()\n\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n })\n\n const keyBuf = keyWrapper.toBER()\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength)\n const salt = randomBytes(SALT_LENGTH)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n }\n )\n\n const iv = randomBytes(16)\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt'])\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr)\n\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n })\n\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n })\n\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n })\n\n const finalWrapperBuf = finalWrapper.toBER()\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength)\n\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n')\n}\n\nexport async function importFromPem (pem: string, password: string): Promise {\n const crypto = webcrypto.get()\n let plaintext: Uint8Array\n\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n const {\n iv,\n salt,\n iterations,\n keySize,\n cipherText\n } = findEncryptedPEMData(result)\n\n const encryptionKey = await pbkdf2Async(\n sha512,\n password,\n salt, {\n c: iterations,\n dkLen: keySize\n }\n )\n\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt'])\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText))\n\n const { result: decryptedResult } = asn1js.fromBER(decrypted)\n plaintext = findPEMData(decryptedResult)\n } else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(\n pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(),\n 'base64pad'\n )\n\n const { result } = asn1js.fromBER(key)\n\n plaintext = findPEMData(result)\n } else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS')\n }\n\n return unmarshalRsaPrivateKey(plaintext)\n}\n\nfunction findEncryptedPEMData (root: any): { cipherText: Uint8Array, iv: Uint8Array, salt: Uint8Array, iterations: number, keySize: number } {\n const encryptionAlgorithm = root.valueBlock.value[0]\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString()\n\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS')\n }\n\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0]\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString()\n\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS')\n }\n\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1]\n\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue())\n\n let iterations = ITERATIONS\n let keySize = KEY_SIZE\n\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number((pbkdf2Params.valueBlock.value[1] as asn1js.Integer).toBigInt())\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt())\n } else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS')\n }\n\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1]\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString()\n\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n } else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n } else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS')\n }\n\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue())\n\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n }\n}\n\nfunction findPEMData (seq: any): Uint8Array {\n return toUint8Array(seq.valueBlock.value[2].getValue())\n}\n\nfunction toUint8Array (buf: ArrayBuffer): Uint8Array {\n return new Uint8Array(buf, 0, buf.byteLength)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport * as crypto from './rsa.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const MAX_RSA_KEY_SIZE = 8192\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean | boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret (): Uint8Array {\n return crypto.getRandomValues(16)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): RsaPublicKey {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export (password: string, format = 'pkcs-8'): Promise> {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password)\n } else if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array): Promise {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array): RsaPublicKey {\n const jwk = crypto.utils.pkixToJwk(bytes)\n\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey): Promise {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.unmarshalPrivateKey(jwk)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number): Promise {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE')\n }\n\n const keys = await crypto.generateKey(bits)\n\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n","import { CodeError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { isPromise } from '../util.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign (key: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.sign(p.digest, key).toDERRawBytes()\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean | Promise {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n })\n }\n\n try {\n return secp.verify(sig, p.digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array): void {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array): void {\n try {\n secp.ProjectivePoint.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n","import { CodeError } from '@libp2p/interface'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { isPromise } from '../util.js'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\nimport * as crypto from './secp256k1.js'\nimport type { Multibase } from 'multiformats'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const p = sha256.digest(this.bytes)\n let bytes: Uint8Array\n\n if (isPromise(p)) {\n ({ bytes } = await p)\n } else {\n bytes = p.bytes\n }\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Secp256k1PublicKey {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n hash (): Uint8Array | Promise {\n const p = sha256.digest(this.bytes)\n\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes)\n }\n\n return p.bytes\n }\n\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const privateKeyBytes = crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport * as Ed25519 from './ed25519-class.js'\nimport generateEphemeralKeyPair from './ephemeral-keys.js'\nimport { importer } from './importer.js'\nimport { keyStretcher } from './key-stretcher.js'\nimport * as keysPBM from './keys.js'\nimport * as RSA from './rsa-class.js'\nimport { importFromPem } from './rsa-utils.js'\nimport * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js'\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js'\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js'\nexport type { JWKKeyPair } from './interface.js'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string): CodeError> {\n const supported = Object.keys(supportedKeys).join(' / ')\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE')\n}\n\nfunction typeToKey (type: string): typeof RSA | typeof Ed25519 | typeof Secp256k1 {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise {\n return typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE')\n }\n\n return Ed25519.generateKeyPairFromSeed(seed)\n}\n\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown')\n }\n}\n\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise {\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data)\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data)\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data)\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA')\n }\n}\n\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey (encryptedKey: string, password: string): Promise {\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT')\n }\n\n return importFromPem(encryptedKey, password)\n}\n","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { CodeError } from '@libp2p/interface'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, peerIdSymbol, type PeerId } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder)\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid')\n }\n\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n","import { unmarshalPrivateKey, unmarshalPublicKey } from \"@libp2p/crypto/keys\";\nimport { supportedKeys } from \"@libp2p/crypto/keys\";\nimport type { PeerId } from \"@libp2p/interface\";\nimport { peerIdFromKeys } from \"@libp2p/peer-id\";\n\nexport function createPeerIdFromPublicKey(\n publicKey: Uint8Array\n): Promise {\n const _publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(publicKey);\n return peerIdFromKeys(_publicKey.bytes, undefined);\n}\n\nexport function getPublicKeyFromPeerId(peerId: PeerId): Uint8Array {\n if (peerId.type !== \"secp256k1\") {\n throw new Error(\"Unsupported peer id type\");\n }\n\n return unmarshalPublicKey(peerId.publicKey).marshal();\n}\n\n// Only used in tests\nexport async function getPrivateKeyFromPeerId(\n peerId: PeerId\n): Promise {\n if (peerId.type !== \"secp256k1\") {\n throw new Error(\"Unsupported peer id type\");\n }\n if (!peerId.privateKey) {\n throw new Error(\"Private key not present on peer id\");\n }\n\n const privateKey = await unmarshalPrivateKey(peerId.privateKey);\n return privateKey.marshal();\n}\n","import { multiaddr } from \"@multiformats/multiaddr\";\nimport type { Multiaddr } from \"@multiformats/multiaddr\";\n\nimport { MULTIADDR_LENGTH_SIZE } from \"./constants.js\";\n\nexport function decodeMultiaddrs(bytes: Uint8Array): Multiaddr[] {\n const multiaddrs = [];\n\n let index = 0;\n\n while (index < bytes.length) {\n const sizeDataView = new DataView(\n bytes.buffer,\n index,\n MULTIADDR_LENGTH_SIZE\n );\n const size = sizeDataView.getUint16(0);\n index += MULTIADDR_LENGTH_SIZE;\n\n const multiaddrBytes = bytes.slice(index, index + size);\n index += size;\n\n multiaddrs.push(multiaddr(multiaddrBytes));\n }\n return multiaddrs;\n}\n\nexport function encodeMultiaddrs(multiaddrs: Multiaddr[]): Uint8Array {\n const totalLength = multiaddrs.reduce(\n (acc, ma) => acc + MULTIADDR_LENGTH_SIZE + ma.bytes.length,\n 0\n );\n const bytes = new Uint8Array(totalLength);\n const dataView = new DataView(bytes.buffer);\n\n let index = 0;\n multiaddrs.forEach((multiaddr) => {\n if (multiaddr.getPeerId())\n throw new Error(\"`multiaddr` field MUST not contain peer id\");\n\n // Prepend the size of the next entry\n dataView.setUint16(index, multiaddr.bytes.length);\n index += MULTIADDR_LENGTH_SIZE;\n\n bytes.set(multiaddr.bytes, index);\n index += multiaddr.bytes.length;\n });\n\n return bytes;\n}\n","import type { Waku2 } from \"@waku/interfaces\";\n\nexport function encodeWaku2(protocols: Waku2): number {\n let byte = 0;\n\n if (protocols.lightPush) byte += 1;\n byte = byte << 1;\n if (protocols.filter) byte += 1;\n byte = byte << 1;\n if (protocols.store) byte += 1;\n byte = byte << 1;\n if (protocols.relay) byte += 1;\n\n return byte;\n}\n\nexport function decodeWaku2(byte: number): Waku2 {\n const waku2 = {\n relay: false,\n store: false,\n filter: false,\n lightPush: false\n };\n\n if (byte % 2) waku2.relay = true;\n byte = byte >> 1;\n if (byte % 2) waku2.store = true;\n byte = byte >> 1;\n if (byte % 2) waku2.filter = true;\n byte = byte >> 1;\n if (byte % 2) waku2.lightPush = true;\n\n return waku2;\n}\n","import type { Multiaddr } from \"@multiformats/multiaddr\";\nimport {\n convertToBytes,\n convertToString\n} from \"@multiformats/multiaddr/convert\";\nimport type {\n ENRKey,\n ENRValue,\n SequenceNumber,\n ShardInfo,\n Waku2\n} from \"@waku/interfaces\";\nimport { decodeRelayShard } from \"@waku/utils\";\nimport { bytesToUtf8 } from \"@waku/utils/bytes\";\n\nimport { ERR_INVALID_ID } from \"./constants.js\";\nimport { decodeMultiaddrs, encodeMultiaddrs } from \"./multiaddrs_codec.js\";\nimport { decodeWaku2, encodeWaku2 } from \"./waku2_codec.js\";\n\nexport class RawEnr extends Map {\n public seq: SequenceNumber;\n public signature?: Uint8Array;\n\n protected constructor(\n kvs: Record = {},\n seq: SequenceNumber = BigInt(1),\n signature?: Uint8Array\n ) {\n super(Object.entries(kvs));\n this.seq = seq;\n this.signature = signature;\n }\n\n set(k: ENRKey, v: ENRValue): this {\n this.signature = undefined;\n this.seq++;\n return super.set(k, v);\n }\n\n get id(): string {\n const id = this.get(\"id\");\n if (!id) throw new Error(\"id not found.\");\n return bytesToUtf8(id);\n }\n\n get publicKey(): Uint8Array | undefined {\n switch (this.id) {\n case \"v4\":\n return this.get(\"secp256k1\");\n default:\n throw new Error(ERR_INVALID_ID);\n }\n }\n\n get rs(): ShardInfo | undefined {\n const rs = this.get(\"rs\");\n if (!rs) return undefined;\n return decodeRelayShard(rs);\n }\n\n get rsv(): ShardInfo | undefined {\n const rsv = this.get(\"rsv\");\n if (!rsv) return undefined;\n return decodeRelayShard(rsv);\n }\n\n get ip(): string | undefined {\n return getStringValue(this, \"ip\", \"ip4\");\n }\n\n set ip(ip: string | undefined) {\n setStringValue(this, \"ip\", \"ip4\", ip);\n }\n\n get tcp(): number | undefined {\n return getNumberAsStringValue(this, \"tcp\", \"tcp\");\n }\n\n set tcp(port: number | undefined) {\n setNumberAsStringValue(this, \"tcp\", \"tcp\", port);\n }\n\n get udp(): number | undefined {\n return getNumberAsStringValue(this, \"udp\", \"udp\");\n }\n\n set udp(port: number | undefined) {\n setNumberAsStringValue(this, \"udp\", \"udp\", port);\n }\n\n get ip6(): string | undefined {\n return getStringValue(this, \"ip6\", \"ip6\");\n }\n\n set ip6(ip: string | undefined) {\n setStringValue(this, \"ip6\", \"ip6\", ip);\n }\n\n get tcp6(): number | undefined {\n return getNumberAsStringValue(this, \"tcp6\", \"tcp\");\n }\n\n set tcp6(port: number | undefined) {\n setNumberAsStringValue(this, \"tcp6\", \"tcp\", port);\n }\n\n get udp6(): number | undefined {\n return getNumberAsStringValue(this, \"udp6\", \"udp\");\n }\n\n set udp6(port: number | undefined) {\n setNumberAsStringValue(this, \"udp6\", \"udp\", port);\n }\n\n /**\n * Get the `multiaddrs` field from ENR.\n *\n * This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.\n * These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host\n * address (e.g. `dns4`, `dnsaddr`, etc)..\n *\n * If the peer information only contains information that can be represented with the ENR pre-defined keys\n * (ip, tcp, etc) then the usage of { @link ENR.getLocationMultiaddr } should be preferred.\n *\n * The multiaddresses stored in this field are expected to be location multiaddresses, ie, peer id less.\n */\n get multiaddrs(): Multiaddr[] | undefined {\n const raw = this.get(\"multiaddrs\");\n\n if (raw) return decodeMultiaddrs(raw);\n\n return;\n }\n\n /**\n * Set the `multiaddrs` field on the ENR.\n *\n * This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.\n * These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host\n * address (e.g. `dns4`, `dnsaddr`, etc)..\n *\n * If the peer information only contains information that can be represented with the ENR pre-defined keys\n * (ip, tcp, etc) then the usage of { @link ENR.setLocationMultiaddr } should be preferred.\n * The multiaddresses stored in this field must be location multiaddresses,\n * ie, without a peer id.\n */\n set multiaddrs(multiaddrs: Multiaddr[] | undefined) {\n deleteUndefined(this, \"multiaddrs\", multiaddrs, encodeMultiaddrs);\n }\n\n /**\n * Get the `waku2` field from ENR.\n */\n get waku2(): Waku2 | undefined {\n const raw = this.get(\"waku2\");\n if (raw) return decodeWaku2(raw[0]);\n\n return;\n }\n\n /**\n * Set the `waku2` field on the ENR.\n */\n set waku2(waku2: Waku2 | undefined) {\n deleteUndefined(\n this,\n \"waku2\",\n waku2,\n (w) => new Uint8Array([encodeWaku2(w)])\n );\n }\n}\n\nfunction getStringValue(\n map: Map,\n key: ENRKey,\n proto: string\n): string | undefined {\n const raw = map.get(key);\n if (!raw) return;\n return convertToString(proto, raw);\n}\n\nfunction getNumberAsStringValue(\n map: Map,\n key: ENRKey,\n proto: string\n): number | undefined {\n const raw = map.get(key);\n if (!raw) return;\n return Number(convertToString(proto, raw));\n}\n\nfunction setStringValue(\n map: Map,\n key: ENRKey,\n proto: string,\n value: string | undefined\n): void {\n deleteUndefined(map, key, value, convertToBytes.bind({}, proto));\n}\n\nfunction setNumberAsStringValue(\n map: Map,\n key: ENRKey,\n proto: string,\n value: number | undefined\n): void {\n setStringValue(map, key, proto, value?.toString(10));\n}\n\nfunction deleteUndefined(\n map: Map,\n key: K,\n value: V | undefined,\n transform: (v: V) => W\n): void {\n if (value !== undefined) {\n map.set(key, transform(value));\n } else {\n map.delete(key);\n }\n}\n","import * as secp from \"@noble/secp256k1\";\nimport type { NodeId } from \"@waku/interfaces\";\nimport { bytesToHex } from \"@waku/utils/bytes\";\n\nimport { keccak256 } from \"./crypto.js\";\nexport async function sign(\n privKey: Uint8Array,\n msg: Uint8Array\n): Promise {\n return secp.sign(keccak256(msg), privKey, {\n der: false\n });\n}\n\nexport function nodeId(pubKey: Uint8Array): NodeId {\n const publicKey = secp.Point.fromHex(pubKey);\n const uncompressedPubkey = publicKey.toRawBytes(false);\n\n return bytesToHex(keccak256(uncompressedPubkey.slice(1)));\n}\n","import type { PeerId, PeerInfo } from \"@libp2p/interface\";\nimport type { Multiaddr } from \"@multiformats/multiaddr\";\nimport type {\n ENRKey,\n ENRValue,\n IEnr,\n NodeId,\n SequenceNumber,\n ShardInfo\n} from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\n\nimport { ERR_INVALID_ID } from \"./constants.js\";\nimport { keccak256, verifySignature } from \"./crypto.js\";\nimport { locationMultiaddrFromEnrFields } from \"./get_multiaddr.js\";\nimport { createPeerIdFromPublicKey } from \"./peer_id.js\";\nimport { RawEnr } from \"./raw_enr.js\";\nimport * as v4 from \"./v4.js\";\n\nconst log = new Logger(\"enr\");\n\nexport enum TransportProtocol {\n TCP = \"tcp\",\n UDP = \"udp\"\n}\nexport enum TransportProtocolPerIpVersion {\n TCP4 = \"tcp4\",\n UDP4 = \"udp4\",\n TCP6 = \"tcp6\",\n UDP6 = \"udp6\"\n}\n\nexport class ENR extends RawEnr implements IEnr {\n public static readonly RECORD_PREFIX = \"enr:\";\n public peerId?: PeerId;\n\n static async create(\n kvs: Record = {},\n seq: SequenceNumber = BigInt(1),\n signature?: Uint8Array\n ): Promise {\n const enr = new ENR(kvs, seq, signature);\n try {\n const publicKey = enr.publicKey;\n if (publicKey) {\n enr.peerId = await createPeerIdFromPublicKey(publicKey);\n }\n } catch (e) {\n log.error(\"Could not calculate peer id for ENR\", e);\n }\n\n return enr;\n }\n\n get nodeId(): NodeId | undefined {\n switch (this.id) {\n case \"v4\":\n return this.publicKey ? v4.nodeId(this.publicKey) : undefined;\n default:\n throw new Error(ERR_INVALID_ID);\n }\n }\n getLocationMultiaddr: (\n protocol: TransportProtocol | TransportProtocolPerIpVersion\n ) => Multiaddr | undefined = locationMultiaddrFromEnrFields.bind({}, this);\n\n get shardInfo(): ShardInfo | undefined {\n if (this.rs && this.rsv) {\n log.warn(\"ENR contains both `rs` and `rsv` fields.\");\n }\n return this.rs || this.rsv;\n }\n\n setLocationMultiaddr(multiaddr: Multiaddr): void {\n const protoNames = multiaddr.protoNames();\n if (\n protoNames.length !== 2 &&\n protoNames[1] !== \"udp\" &&\n protoNames[1] !== \"tcp\"\n ) {\n throw new Error(\"Invalid multiaddr\");\n }\n const tuples = multiaddr.tuples();\n if (!tuples[0][1] || !tuples[1][1]) {\n throw new Error(\"Invalid multiaddr\");\n }\n\n // IPv4\n if (tuples[0][0] === 4) {\n this.set(\"ip\", tuples[0][1]);\n this.set(protoNames[1], tuples[1][1]);\n } else {\n this.set(\"ip6\", tuples[0][1]);\n this.set(protoNames[1] + \"6\", tuples[1][1]);\n }\n }\n\n getAllLocationMultiaddrs(): Multiaddr[] {\n const multiaddrs = [];\n\n for (const protocol of Object.values(TransportProtocolPerIpVersion)) {\n const ma = this.getLocationMultiaddr(\n protocol as TransportProtocolPerIpVersion\n );\n if (ma) multiaddrs.push(ma);\n }\n\n const _multiaddrs = this.multiaddrs ?? [];\n\n return multiaddrs.concat(_multiaddrs).map((ma) => {\n if (this.peerId) {\n return ma.encapsulate(`/p2p/${this.peerId.toString()}`);\n }\n return ma;\n });\n }\n\n get peerInfo(): PeerInfo | undefined {\n const id = this.peerId;\n if (!id) return;\n return {\n id,\n multiaddrs: this.getAllLocationMultiaddrs()\n };\n }\n\n /**\n * Returns the full multiaddr from the ENR fields matching the provided\n * `protocol` parameter.\n * To return full multiaddrs from the `multiaddrs` ENR field,\n * use { @link ENR.getFullMultiaddrs }.\n *\n * @param protocol\n */\n getFullMultiaddr(\n protocol: TransportProtocol | TransportProtocolPerIpVersion\n ): Multiaddr | undefined {\n if (this.peerId) {\n const locationMultiaddr = this.getLocationMultiaddr(protocol);\n if (locationMultiaddr) {\n return locationMultiaddr.encapsulate(`/p2p/${this.peerId.toString()}`);\n }\n }\n return;\n }\n\n /**\n * Returns the full multiaddrs from the `multiaddrs` ENR field.\n */\n getFullMultiaddrs(): Multiaddr[] {\n if (this.peerId && this.multiaddrs) {\n const peerId = this.peerId;\n return this.multiaddrs.map((ma) => {\n return ma.encapsulate(`/p2p/${peerId.toString()}`);\n });\n }\n return [];\n }\n\n verify(data: Uint8Array, signature: Uint8Array): boolean {\n if (!this.get(\"id\") || this.id !== \"v4\") {\n throw new Error(ERR_INVALID_ID);\n }\n if (!this.publicKey) {\n throw new Error(\"Failed to verify ENR: No public key\");\n }\n return verifySignature(signature, keccak256(data), this.publicKey);\n }\n\n async sign(data: Uint8Array, privateKey: Uint8Array): Promise {\n switch (this.id) {\n case \"v4\":\n this.signature = await v4.sign(privateKey, data);\n break;\n default:\n throw new Error(ERR_INVALID_ID);\n }\n return this.signature;\n }\n}\n","\"use strict\";\n\nlet _permanentCensorErrors = false;\nlet _censorErrors = false;\n\nconst LogLevels: { [ name: string ]: number } = { debug: 1, \"default\": 2, info: 2, warning: 3, error: 4, off: 5 };\nlet _logLevel = LogLevels[\"default\"];\n\nimport { version } from \"./_version\";\n\nlet _globalLogger: Logger = null;\n\nfunction _checkNormalize(): string {\n try {\n const missing: Array = [ ];\n\n // Make sure all forms of normalization are supported\n [\"NFD\", \"NFC\", \"NFKD\", \"NFKC\"].forEach((form) => {\n try {\n if (\"test\".normalize(form) !== \"test\") {\n throw new Error(\"bad normalize\");\n };\n } catch(error) {\n missing.push(form);\n }\n });\n\n if (missing.length) {\n throw new Error(\"missing \" + missing.join(\", \"));\n }\n\n if (String.fromCharCode(0xe9).normalize(\"NFD\") !== String.fromCharCode(0x65, 0x0301)) {\n throw new Error(\"broken implementation\")\n }\n } catch (error) {\n return error.message;\n }\n\n return null;\n}\n\nconst _normalizeError = _checkNormalize();\n\nexport enum LogLevel {\n DEBUG = \"DEBUG\",\n INFO = \"INFO\",\n WARNING = \"WARNING\",\n ERROR = \"ERROR\",\n OFF = \"OFF\"\n}\n\n\nexport enum ErrorCode {\n\n ///////////////////\n // Generic Errors\n\n // Unknown Error\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n\n // Not Implemented\n NOT_IMPLEMENTED = \"NOT_IMPLEMENTED\",\n\n // Unsupported Operation\n // - operation\n UNSUPPORTED_OPERATION = \"UNSUPPORTED_OPERATION\",\n\n // Network Error (i.e. Ethereum Network, such as an invalid chain ID)\n // - event (\"noNetwork\" is not re-thrown in provider.ready; otherwise thrown)\n NETWORK_ERROR = \"NETWORK_ERROR\",\n\n // Some sort of bad response from the server\n SERVER_ERROR = \"SERVER_ERROR\",\n\n // Timeout\n TIMEOUT = \"TIMEOUT\",\n\n ///////////////////\n // Operational Errors\n\n // Buffer Overrun\n BUFFER_OVERRUN = \"BUFFER_OVERRUN\",\n\n // Numeric Fault\n // - operation: the operation being executed\n // - fault: the reason this faulted\n NUMERIC_FAULT = \"NUMERIC_FAULT\",\n\n\n ///////////////////\n // Argument Errors\n\n // Missing new operator to an object\n // - name: The name of the class\n MISSING_NEW = \"MISSING_NEW\",\n\n // Invalid argument (e.g. value is incompatible with type) to a function:\n // - argument: The argument name that was invalid\n // - value: The value of the argument\n INVALID_ARGUMENT = \"INVALID_ARGUMENT\",\n\n // Missing argument to a function:\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n MISSING_ARGUMENT = \"MISSING_ARGUMENT\",\n\n // Too many arguments\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n UNEXPECTED_ARGUMENT = \"UNEXPECTED_ARGUMENT\",\n\n\n ///////////////////\n // Blockchain Errors\n\n // Call exception\n // - transaction: the transaction\n // - address?: the contract address\n // - args?: The arguments passed into the function\n // - method?: The Solidity method signature\n // - errorSignature?: The EIP848 error signature\n // - errorArgs?: The EIP848 error parameters\n // - reason: The reason (only for EIP848 \"Error(string)\")\n CALL_EXCEPTION = \"CALL_EXCEPTION\",\n\n // Insufficient funds (< value + gasLimit * gasPrice)\n // - transaction: the transaction attempted\n INSUFFICIENT_FUNDS = \"INSUFFICIENT_FUNDS\",\n\n // Nonce has already been used\n // - transaction: the transaction attempted\n NONCE_EXPIRED = \"NONCE_EXPIRED\",\n\n // The replacement fee for the transaction is too low\n // - transaction: the transaction attempted\n REPLACEMENT_UNDERPRICED = \"REPLACEMENT_UNDERPRICED\",\n\n // The gas limit could not be estimated\n // - transaction: the transaction passed to estimateGas\n UNPREDICTABLE_GAS_LIMIT = \"UNPREDICTABLE_GAS_LIMIT\",\n\n // The transaction was replaced by one with a higher gas price\n // - reason: \"cancelled\", \"replaced\" or \"repriced\"\n // - cancelled: true if reason == \"cancelled\" or reason == \"replaced\")\n // - hash: original transaction hash\n // - replacement: the full TransactionsResponse for the replacement\n // - receipt: the receipt of the replacement\n TRANSACTION_REPLACED = \"TRANSACTION_REPLACED\",\n\n\n ///////////////////\n // Interaction Errors\n\n // The user rejected the action, such as signing a message or sending\n // a transaction\n ACTION_REJECTED = \"ACTION_REJECTED\",\n};\n\nconst HEX = \"0123456789abcdef\";\n\nexport class Logger {\n readonly version: string;\n\n static errors = ErrorCode;\n\n static levels = LogLevel;\n\n constructor(version: string) {\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n value: version,\n writable: false\n });\n }\n\n _log(logLevel: LogLevel, args: Array): void {\n const level = logLevel.toLowerCase();\n if (LogLevels[level] == null) {\n this.throwArgumentError(\"invalid log level name\", \"logLevel\", logLevel);\n }\n if (_logLevel > LogLevels[level]) { return; }\n console.log.apply(console, args);\n }\n\n debug(...args: Array): void {\n this._log(Logger.levels.DEBUG, args);\n }\n\n info(...args: Array): void {\n this._log(Logger.levels.INFO, args);\n }\n\n warn(...args: Array): void {\n this._log(Logger.levels.WARNING, args);\n }\n\n makeError(message: string, code?: ErrorCode, params?: any): Error {\n // Errors are being censored\n if (_censorErrors) {\n return this.makeError(\"censored error\", code, { });\n }\n\n if (!code) { code = Logger.errors.UNKNOWN_ERROR; }\n if (!params) { params = {}; }\n\n const messageDetails: Array = [];\n Object.keys(params).forEach((key) => {\n const value = params[key];\n try {\n if (value instanceof Uint8Array) {\n let hex = \"\";\n for (let i = 0; i < value.length; i++) {\n hex += HEX[value[i] >> 4];\n hex += HEX[value[i] & 0x0f];\n }\n messageDetails.push(key + \"=Uint8Array(0x\" + hex + \")\");\n } else {\n messageDetails.push(key + \"=\" + JSON.stringify(value));\n }\n } catch (error) {\n messageDetails.push(key + \"=\" + JSON.stringify(params[key].toString()));\n }\n });\n messageDetails.push(`code=${ code }`);\n messageDetails.push(`version=${ this.version }`);\n\n const reason = message;\n\n let url = \"\";\n\n switch (code) {\n case ErrorCode.NUMERIC_FAULT: {\n url = \"NUMERIC_FAULT\";\n const fault = message;\n\n switch (fault) {\n case \"overflow\": case \"underflow\": case \"division-by-zero\":\n url += \"-\" + fault;\n break;\n case \"negative-power\": case \"negative-width\":\n url += \"-unsupported\";\n break;\n case \"unbound-bitwise-result\":\n url += \"-unbound-result\";\n break;\n }\n break;\n }\n case ErrorCode.CALL_EXCEPTION:\n case ErrorCode.INSUFFICIENT_FUNDS:\n case ErrorCode.MISSING_NEW:\n case ErrorCode.NONCE_EXPIRED:\n case ErrorCode.REPLACEMENT_UNDERPRICED:\n case ErrorCode.TRANSACTION_REPLACED:\n case ErrorCode.UNPREDICTABLE_GAS_LIMIT:\n url = code;\n break;\n }\n\n if (url) {\n message += \" [ See: https:/\\/links.ethers.org/v5-errors-\" + url + \" ]\";\n }\n\n if (messageDetails.length) {\n message += \" (\" + messageDetails.join(\", \") + \")\";\n }\n\n // @TODO: Any??\n const error: any = new Error(message);\n error.reason = reason;\n error.code = code\n\n Object.keys(params).forEach(function(key) {\n error[key] = params[key];\n });\n\n return error;\n }\n\n throwError(message: string, code?: ErrorCode, params?: any): never {\n throw this.makeError(message, code, params);\n }\n\n throwArgumentError(message: string, name: string, value: any): never {\n return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {\n argument: name,\n value: value\n });\n }\n\n assert(condition: any, message: string, code?: ErrorCode, params?: any): void {\n if (!!condition) { return; }\n this.throwError(message, code, params);\n }\n\n assertArgument(condition: any, message: string, name: string, value: any): void {\n if (!!condition) { return; }\n this.throwArgumentError(message, name, value);\n }\n\n checkNormalize(message?: string): void {\n if (message == null) { message = \"platform missing String.prototype.normalize\"; }\n if (_normalizeError) {\n this.throwError(\"platform missing String.prototype.normalize\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"String.prototype.normalize\", form: _normalizeError\n });\n }\n }\n\n checkSafeUint53(value: number, message?: string): void {\n if (typeof(value) !== \"number\") { return; }\n\n if (message == null) { message = \"value not safe\"; }\n\n if (value < 0 || value >= 0x1fffffffffffff) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"out-of-safe-range\",\n value: value\n });\n }\n\n if (value % 1) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"non-integer\",\n value: value\n });\n }\n }\n\n checkArgumentCount(count: number, expectedCount: number, message?: string): void {\n if (message) {\n message = \": \" + message;\n } else {\n message = \"\";\n }\n\n if (count < expectedCount) {\n this.throwError(\"missing argument\" + message, Logger.errors.MISSING_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n\n if (count > expectedCount) {\n this.throwError(\"too many arguments\" + message, Logger.errors.UNEXPECTED_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n }\n\n checkNew(target: any, kind: any): void {\n if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n\n checkAbstract(target: any, kind: any): void {\n if (target === kind) {\n this.throwError(\n \"cannot instantiate abstract class \" + JSON.stringify(kind.name) + \" directly; use a sub-class\",\n Logger.errors.UNSUPPORTED_OPERATION,\n { name: target.name, operation: \"new\" }\n );\n } else if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n\n static globalLogger(): Logger {\n if (!_globalLogger) { _globalLogger = new Logger(version); }\n return _globalLogger;\n }\n\n static setCensorship(censorship: boolean, permanent?: boolean): void {\n if (!censorship && permanent) {\n this.globalLogger().throwError(\"cannot permanently disable censorship\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n\n if (_permanentCensorErrors) {\n if (!censorship) { return; }\n this.globalLogger().throwError(\"error censorship permanent\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n\n _censorErrors = !!censorship;\n _permanentCensorErrors = !!permanent;\n }\n\n static setLogLevel(logLevel: LogLevel): void {\n const level = LogLevels[logLevel.toLowerCase()];\n if (level == null) {\n Logger.globalLogger().warn(\"invalid log level - \" + logLevel);\n return;\n }\n _logLevel = level;\n }\n\n static from(version: string): Logger {\n return new Logger(version);\n }\n}\n","export const version = \"logger/5.7.0\";\n","export const version = \"bytes/5.7.0\";\n","\"use strict\";\n\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\n\n///////////////////////////////\n// Exported Types\n\nexport type Bytes = ArrayLike;\n\nexport type BytesLike = Bytes | string;\n\nexport type DataOptions = {\n allowMissingPrefix?: boolean;\n hexPad?: \"left\" | \"right\" | null;\n};\n\nexport interface Hexable {\n toHexString(): string;\n}\n\n\n/*\nexport interface HexString {\n length: number;\n substring: (start: number, end?: number) => string;\n\n [index: number]: string;\n}\n*/\n\nexport type SignatureLike = {\n r: string;\n s?: string;\n _vs?: string,\n recoveryParam?: number;\n v?: number;\n} | BytesLike;\n\nexport interface Signature {\n r: string;\n\n s: string;\n _vs: string,\n\n recoveryParam: number;\n v: number;\n\n yParityAndS: string\n compact: string;\n}\n\n///////////////////////////////\n\n\nfunction isHexable(value: any): value is Hexable {\n return !!(value.toHexString);\n}\n\nfunction addSlice(array: Uint8Array): Uint8Array {\n if (array.slice) { return array; }\n\n array.slice = function() {\n const args = Array.prototype.slice.call(arguments);\n return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));\n }\n\n return array;\n}\n\nexport function isBytesLike(value: any): value is BytesLike {\n return ((isHexString(value) && !(value.length % 2)) || isBytes(value));\n}\n\nfunction isInteger(value: number) {\n return (typeof(value) === \"number\" && value == value && (value % 1) === 0);\n}\n\nexport function isBytes(value: any): value is Bytes {\n if (value == null) { return false; }\n\n if (value.constructor === Uint8Array) { return true; }\n if (typeof(value) === \"string\") { return false; }\n if (!isInteger(value.length) || value.length < 0) { return false; }\n\n for (let i = 0; i < value.length; i++) {\n const v = value[i];\n if (!isInteger(v) || v < 0 || v >= 256) { return false; }\n }\n return true;\n}\n\n\nexport function arrayify(value: BytesLike | Hexable | number, options?: DataOptions): Uint8Array {\n if (!options) { options = { }; }\n\n if (typeof(value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid arrayify value\");\n\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value = parseInt(String(value / 256));\n }\n if (result.length === 0) { result.push(0); }\n\n return addSlice(new Uint8Array(result));\n }\n\n if (options.allowMissingPrefix && typeof(value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n\n if (isHexable(value)) { value = value.toHexString(); }\n\n if (isHexString(value)) {\n let hex = (value).substring(2);\n if (hex.length % 2) {\n if (options.hexPad === \"left\") {\n hex = \"0\" + hex;\n } else if (options.hexPad === \"right\") {\n hex += \"0\";\n } else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n\n const result = [];\n for (let i = 0; i < hex.length; i += 2) {\n result.push(parseInt(hex.substring(i, i + 2), 16));\n }\n\n return addSlice(new Uint8Array(result));\n }\n\n if (isBytes(value)) {\n return addSlice(new Uint8Array(value));\n }\n\n return logger.throwArgumentError(\"invalid arrayify value\", \"value\", value);\n}\n\nexport function concat(items: ReadonlyArray): Uint8Array {\n const objects = items.map(item => arrayify(item));\n const length = objects.reduce((accum, item) => (accum + item.length), 0);\n\n const result = new Uint8Array(length);\n\n objects.reduce((offset, object) => {\n result.set(object, offset);\n return offset + object.length;\n }, 0);\n\n return addSlice(result);\n}\n\nexport function stripZeros(value: BytesLike): Uint8Array {\n let result: Uint8Array = arrayify(value);\n\n if (result.length === 0) { return result; }\n\n // Find the first non-zero entry\n let start = 0;\n while (start < result.length && result[start] === 0) { start++ }\n\n // If we started with zeros, strip them\n if (start) {\n result = result.slice(start);\n }\n\n return result;\n}\n\nexport function zeroPad(value: BytesLike, length: number): Uint8Array {\n value = arrayify(value);\n\n if (value.length > length) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[0]);\n }\n\n const result = new Uint8Array(length);\n result.set(value, length - value.length);\n return addSlice(result);\n}\n\n\nexport function isHexString(value: any, length?: number): boolean {\n if (typeof(value) !== \"string\" || !value.match(/^0x[0-9A-Fa-f]*$/)) {\n return false\n }\n if (length && value.length !== 2 + 2 * length) { return false; }\n return true;\n}\n\nconst HexCharacters: string = \"0123456789abcdef\";\n\nexport function hexlify(value: BytesLike | Hexable | number | bigint, options?: DataOptions): string {\n if (!options) { options = { }; }\n\n if (typeof(value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid hexlify value\");\n\n let hex = \"\";\n while (value) {\n hex = HexCharacters[value & 0xf] + hex;\n value = Math.floor(value / 16);\n }\n\n if (hex.length) {\n if (hex.length % 2) { hex = \"0\" + hex; }\n return \"0x\" + hex;\n }\n\n return \"0x00\";\n }\n\n if (typeof(value) === \"bigint\") {\n value = value.toString(16);\n if (value.length % 2) { return (\"0x0\" + value); }\n return \"0x\" + value;\n }\n\n if (options.allowMissingPrefix && typeof(value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n\n if (isHexable(value)) { return value.toHexString(); }\n\n if (isHexString(value)) {\n if ((value).length % 2) {\n if (options.hexPad === \"left\") {\n value = \"0x0\" + (value).substring(2);\n } else if (options.hexPad === \"right\") {\n value += \"0\";\n } else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n return (value).toLowerCase();\n }\n\n if (isBytes(value)) {\n let result = \"0x\";\n for (let i = 0; i < value.length; i++) {\n let v = value[i];\n result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];\n }\n return result;\n }\n\n return logger.throwArgumentError(\"invalid hexlify value\", \"value\", value);\n}\n\n/*\nfunction unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {\n if (typeof(value) === \"string\" && value.length % 2 && value.substring(0, 2) === \"0x\") {\n return \"0x0\" + value.substring(2);\n }\n return value;\n}\n*/\nexport function hexDataLength(data: BytesLike) {\n if (typeof(data) !== \"string\") {\n data = hexlify(data);\n } else if (!isHexString(data) || (data.length % 2)) {\n return null;\n }\n\n return (data.length - 2) / 2;\n}\n\nexport function hexDataSlice(data: BytesLike, offset: number, endOffset?: number): string {\n if (typeof(data) !== \"string\") {\n data = hexlify(data);\n } else if (!isHexString(data) || (data.length % 2)) {\n logger.throwArgumentError(\"invalid hexData\", \"value\", data );\n }\n\n offset = 2 + 2 * offset;\n\n if (endOffset != null) {\n return \"0x\" + data.substring(offset, 2 + 2 * endOffset);\n }\n\n return \"0x\" + data.substring(offset);\n}\n\nexport function hexConcat(items: ReadonlyArray): string {\n let result = \"0x\";\n items.forEach((item) => {\n result += hexlify(item).substring(2);\n });\n return result;\n}\n\nexport function hexValue(value: BytesLike | Hexable | number | bigint): string {\n const trimmed = hexStripZeros(hexlify(value, { hexPad: \"left\" }));\n if (trimmed === \"0x\") { return \"0x0\"; }\n return trimmed;\n}\n\nexport function hexStripZeros(value: BytesLike): string {\n if (typeof(value) !== \"string\") { value = hexlify(value); }\n\n if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n value = value.substring(2);\n let offset = 0;\n while (offset < value.length && value[offset] === \"0\") { offset++; }\n return \"0x\" + value.substring(offset);\n}\n\nexport function hexZeroPad(value: BytesLike, length: number): string {\n if (typeof(value) !== \"string\") {\n value = hexlify(value);\n } else if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n\n if (value.length > 2 * length + 2) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[1]);\n }\n\n while (value.length < 2 * length + 2) {\n value = \"0x0\" + value.substring(2);\n }\n\n return value;\n}\n\nexport function splitSignature(signature: SignatureLike): Signature {\n\n const result = {\n r: \"0x\",\n s: \"0x\",\n _vs: \"0x\",\n recoveryParam: 0,\n v: 0,\n yParityAndS: \"0x\",\n compact: \"0x\"\n };\n\n if (isBytesLike(signature)) {\n let bytes: Uint8Array = arrayify(signature);\n\n // Get the r, s and v\n if (bytes.length === 64) {\n // EIP-2098; pull the v from the top bit of s and clear it\n result.v = 27 + (bytes[32] >> 7);\n bytes[32] &= 0x7f;\n\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n\n } else if (bytes.length === 65) {\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n result.v = bytes[64];\n } else {\n\n logger.throwArgumentError(\"invalid signature string\", \"signature\", signature);\n }\n\n\n // Allow a recid to be used as the v\n if (result.v < 27) {\n if (result.v === 0 || result.v === 1) {\n result.v += 27;\n } else {\n logger.throwArgumentError(\"signature invalid v byte\", \"signature\", signature);\n }\n }\n\n // Compute recoveryParam from v\n result.recoveryParam = 1 - (result.v % 2);\n\n // Compute _vs from recoveryParam and s\n if (result.recoveryParam) { bytes[32] |= 0x80; }\n result._vs = hexlify(bytes.slice(32, 64))\n\n } else {\n result.r = signature.r;\n result.s = signature.s;\n result.v = signature.v;\n result.recoveryParam = signature.recoveryParam;\n result._vs = signature._vs;\n\n // If the _vs is available, use it to populate missing s, v and recoveryParam\n // and verify non-missing s, v and recoveryParam\n if (result._vs != null) {\n const vs = zeroPad(arrayify(result._vs), 32);\n result._vs = hexlify(vs);\n\n // Set or check the recid\n const recoveryParam = ((vs[0] >= 128) ? 1: 0);\n if (result.recoveryParam == null) {\n result.recoveryParam = recoveryParam;\n } else if (result.recoveryParam !== recoveryParam) {\n logger.throwArgumentError(\"signature recoveryParam mismatch _vs\", \"signature\", signature);\n }\n\n // Set or check the s\n vs[0] &= 0x7f;\n const s = hexlify(vs);\n if (result.s == null) {\n result.s = s;\n } else if (result.s !== s) {\n logger.throwArgumentError(\"signature v mismatch _vs\", \"signature\", signature);\n }\n }\n\n // Use recid and v to populate each other\n if (result.recoveryParam == null) {\n if (result.v == null) {\n logger.throwArgumentError(\"signature missing v and recoveryParam\", \"signature\", signature);\n } else if (result.v === 0 || result.v === 1) {\n result.recoveryParam = result.v;\n } else {\n result.recoveryParam = 1 - (result.v % 2);\n }\n } else {\n if (result.v == null) {\n result.v = 27 + result.recoveryParam;\n } else {\n const recId = (result.v === 0 || result.v === 1) ? result.v :(1 - (result.v % 2));\n if (result.recoveryParam !== recId) {\n logger.throwArgumentError(\"signature recoveryParam mismatch v\", \"signature\", signature);\n }\n }\n }\n\n if (result.r == null || !isHexString(result.r)) {\n logger.throwArgumentError(\"signature missing or invalid r\", \"signature\", signature);\n } else {\n result.r = hexZeroPad(result.r, 32);\n }\n\n if (result.s == null || !isHexString(result.s)) {\n logger.throwArgumentError(\"signature missing or invalid s\", \"signature\", signature);\n } else {\n result.s = hexZeroPad(result.s, 32);\n }\n\n const vs = arrayify(result.s);\n if (vs[0] >= 128) {\n logger.throwArgumentError(\"signature s out of range\", \"signature\", signature);\n }\n if (result.recoveryParam) { vs[0] |= 0x80; }\n const _vs = hexlify(vs);\n\n if (result._vs) {\n if (!isHexString(result._vs)) {\n logger.throwArgumentError(\"signature invalid _vs\", \"signature\", signature);\n }\n result._vs = hexZeroPad(result._vs, 32);\n }\n\n // Set or check the _vs\n if (result._vs == null) {\n result._vs = _vs;\n } else if (result._vs !== _vs) {\n logger.throwArgumentError(\"signature _vs mismatch v and s\", \"signature\", signature);\n }\n }\n\n result.yParityAndS = result._vs;\n result.compact = result.r + result.yParityAndS.substring(2);\n\n return result;\n}\n\nexport function joinSignature(signature: SignatureLike): string {\n signature = splitSignature(signature);\n\n return hexlify(concat([\n signature.r,\n signature.s,\n (signature.recoveryParam ? \"0x1c\": \"0x1b\")\n ]));\n}\n\n","export const version = \"rlp/5.7.0\";\n","\"use strict\";\n\n//See: https://github.com/ethereum/wiki/wiki/RLP\n\nimport { arrayify, BytesLike, hexlify, isBytesLike } from \"@ethersproject/bytes\";\n\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\n\nfunction arrayifyInteger(value: number): Array {\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value >>= 8;\n }\n return result;\n}\n\nfunction unarrayifyInteger(data: Uint8Array, offset: number, length: number): number {\n let result = 0;\n for (let i = 0; i < length; i++) {\n result = (result * 256) + data[offset + i];\n }\n return result;\n}\n\nfunction _encode(object: Array | string): Array {\n if (Array.isArray(object)) {\n let payload: Array = [];\n object.forEach(function(child) {\n payload = payload.concat(_encode(child));\n });\n\n if (payload.length <= 55) {\n payload.unshift(0xc0 + payload.length)\n return payload;\n }\n\n const length = arrayifyInteger(payload.length);\n length.unshift(0xf7 + length.length);\n\n return length.concat(payload);\n\n }\n\n if (!isBytesLike(object)) {\n logger.throwArgumentError(\"RLP object must be BytesLike\", \"object\", object);\n }\n\n const data: Array = Array.prototype.slice.call(arrayify(object));\n\n if (data.length === 1 && data[0] <= 0x7f) {\n return data;\n\n } else if (data.length <= 55) {\n data.unshift(0x80 + data.length);\n return data;\n }\n\n const length = arrayifyInteger(data.length);\n length.unshift(0xb7 + length.length);\n\n return length.concat(data);\n}\n\nexport function encode(object: any): string {\n return hexlify(_encode(object));\n}\n\ntype Decoded = {\n result: any;\n consumed: number;\n};\n\nfunction _decodeChildren(data: Uint8Array, offset: number, childOffset: number, length: number): Decoded {\n const result = [];\n\n while (childOffset < offset + 1 + length) {\n const decoded = _decode(data, childOffset);\n\n result.push(decoded.result);\n\n childOffset += decoded.consumed;\n if (childOffset > offset + 1 + length) {\n logger.throwError(\"child data too short\", Logger.errors.BUFFER_OVERRUN, { });\n }\n }\n\n return {consumed: (1 + length), result: result};\n}\n\n// returns { consumed: number, result: Object }\nfunction _decode(data: Uint8Array, offset: number): { consumed: number, result: any } {\n if (data.length === 0) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, { });\n }\n\n // Array with extra length prefix\n if (data[offset] >= 0xf8) {\n const lengthLength = data[offset] - 0xf7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data short segment too short\", Logger.errors.BUFFER_OVERRUN, { });\n }\n\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data long segment too short\", Logger.errors.BUFFER_OVERRUN, { });\n }\n\n return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);\n\n } else if (data[offset] >= 0xc0) {\n const length = data[offset] - 0xc0;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, { });\n }\n\n return _decodeChildren(data, offset, offset + 1, length);\n\n } else if (data[offset] >= 0xb8) {\n const lengthLength = data[offset] - 0xb7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, { });\n }\n\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, { });\n }\n\n const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));\n return { consumed: (1 + lengthLength + length), result: result }\n\n } else if (data[offset] >= 0x80) {\n const length = data[offset] - 0x80;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, { });\n }\n\n const result = hexlify(data.slice(offset + 1, offset + 1 + length));\n return { consumed: (1 + length), result: result }\n }\n return { consumed: 1, result: hexlify(data[offset]) };\n}\n\nexport function decode(data: BytesLike): any {\n const bytes = arrayify(data);\n const decoded = _decode(bytes, 0);\n if (decoded.consumed !== bytes.length) {\n logger.throwArgumentError(\"invalid rlp data\", \"data\", data);\n }\n return decoded.result;\n}\n\n","import * as RLP from \"@ethersproject/rlp\";\nimport type { ENRKey, ENRValue } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport { bytesToHex, bytesToUtf8, hexToBytes } from \"@waku/utils/bytes\";\nimport { fromString } from \"uint8arrays/from-string\";\n\nimport { ENR } from \"./enr.js\";\n\nconst log = new Logger(\"enr:decoder\");\n\nexport class EnrDecoder {\n static fromString(encoded: string): Promise {\n if (!encoded.startsWith(ENR.RECORD_PREFIX)) {\n throw new Error(\n `\"string encoded ENR must start with '${ENR.RECORD_PREFIX}'`\n );\n }\n return EnrDecoder.fromRLP(fromString(encoded.slice(4), \"base64url\"));\n }\n\n static fromRLP(encoded: Uint8Array): Promise {\n const decoded = RLP.decode(encoded).map(hexToBytes);\n return fromValues(decoded);\n }\n}\n\nasync function fromValues(values: Uint8Array[]): Promise {\n const { signature, seq, kvs } = checkValues(values);\n\n const obj: Record = {};\n for (let i = 0; i < kvs.length; i += 2) {\n try {\n obj[bytesToUtf8(kvs[i])] = kvs[i + 1];\n } catch (e) {\n log.error(\"Failed to decode ENR key to UTF-8, skipping it\", kvs[i], e);\n }\n }\n const _seq = decodeSeq(seq);\n\n const enr = await ENR.create(obj, _seq, signature);\n checkSignature(seq, kvs, enr, signature);\n return enr;\n}\n\nfunction decodeSeq(seq: Uint8Array): bigint {\n // If seq is an empty array, translate as value 0\n if (!seq.length) return BigInt(0);\n\n return BigInt(\"0x\" + bytesToHex(seq));\n}\n\nfunction checkValues(values: Uint8Array[]): {\n signature: Uint8Array;\n seq: Uint8Array;\n kvs: Uint8Array[];\n} {\n if (!Array.isArray(values)) {\n throw new Error(\"Decoded ENR must be an array\");\n }\n if (values.length % 2 !== 0) {\n throw new Error(\"Decoded ENR must have an even number of elements\");\n }\n const [signature, seq, ...kvs] = values;\n if (!signature || Array.isArray(signature)) {\n throw new Error(\"Decoded ENR invalid signature: must be a byte array\");\n }\n if (!seq || Array.isArray(seq)) {\n throw new Error(\n \"Decoded ENR invalid sequence number: must be a byte array\"\n );\n }\n\n return { signature, seq, kvs };\n}\n\nfunction checkSignature(\n seq: Uint8Array,\n kvs: Uint8Array[],\n enr: ENR,\n signature: Uint8Array\n): void {\n const rlpEncodedBytes = hexToBytes(RLP.encode([seq, ...kvs]));\n if (!enr.verify(rlpEncodedBytes, signature)) {\n throw new Error(\"Unable to verify ENR signature\");\n }\n}\n","const v4Regex = /^(\\d{1,3}\\.){3,3}\\d{1,3}$/\nconst v4Size = 4\nconst v6Regex = /^(::)?(((\\d{1,3}\\.){3}(\\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i\nconst v6Size = 16\n\nexport const v4 = {\n name: 'v4',\n size: v4Size,\n isFormat: ip => v4Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n buff = buff || new Uint8Array(offset + v4Size)\n const max = ip.length\n let n = 0\n for (let i = 0; i < max;) {\n const c = ip.charCodeAt(i++)\n if (c === 46) { // \".\"\n buff[offset++] = n\n n = 0\n } else {\n n = n * 10 + (c - 48)\n }\n }\n buff[offset] = n\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n return `${buff[offset++]}.${buff[offset++]}.${buff[offset++]}.${buff[offset]}`\n }\n}\n\nexport const v6 = {\n name: 'v6',\n size: v6Size,\n isFormat: ip => ip.length > 0 && v6Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n let end = offset + v6Size\n let fill = -1\n let hexN = 0\n let decN = 0\n let prevColon = true\n let useDec = false\n buff = buff || new Uint8Array(offset + v6Size)\n // Note: This algorithm needs to check if the offset\n // could exceed the buffer boundaries as it supports\n // non-standard compliant encodings that may go beyond\n // the boundary limits. if (offset < end) checks should\n // not be necessary...\n for (let i = 0; i < ip.length; i++) {\n let c = ip.charCodeAt(i)\n if (c === 58) { // :\n if (prevColon) {\n if (fill !== -1) {\n // Not Standard! (standard doesn't allow multiple ::)\n // We need to treat\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (offset < end) {\n // :: in the middle\n fill = offset\n }\n } else {\n // : ends the previous number\n if (useDec === true) {\n // Non-standard! (ipv4 should be at end only)\n // A ipv4 address should not be found anywhere else but at\n // the end. This codec also support putting characters\n // after the ipv4 address..\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n hexN = 0\n decN = 0\n }\n prevColon = true\n useDec = false\n } else if (c === 46) { // . indicates IPV4 notation\n if (offset < end) buff[offset] = decN\n offset++\n decN = 0\n hexN = 0\n prevColon = false\n useDec = true\n } else {\n prevColon = false\n if (c >= 97) {\n c -= 87 // a-f ... 97~102 -87 => 10~15\n } else if (c >= 65) {\n c -= 55 // A-F ... 65~70 -55 => 10~15\n } else {\n c -= 48 // 0-9 ... starting from charCode 48\n decN = decN * 10 + c\n }\n // We don't know yet if its a dec or hex number\n hexN = (hexN << 4) + c\n }\n }\n if (prevColon === false) {\n // Commiting last number\n if (useDec === true) {\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n } else if (fill === 0) {\n // Not Standard! (standard doesn't allow multiple ::)\n // This means that a : was found at the start AND end which means the\n // end needs to be treated as 0 entry...\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (fill !== -1) {\n // Non-standard! (standard doens't allow multiple ::)\n // Here we find that there has been a :: somewhere in the middle\n // and the end. To treat the end with priority we need to move all\n // written data two bytes to the right.\n offset += 2\n for (let i = Math.min(offset - 1, end - 1); i >= fill + 2; i--) {\n buff[i] = buff[i - 2]\n }\n buff[fill] = 0\n buff[fill + 1] = 0\n fill = offset\n }\n if (fill !== offset && fill !== -1) {\n // Move the written numbers to the end while filling the everything\n // \"fill\" to the bytes with zeros.\n if (offset > end - 2) {\n // Non Standard support, when the cursor exceeds bounds.\n offset = end - 2\n }\n while (end > fill) {\n buff[--end] = offset < end && offset > fill ? buff[--offset] : 0\n }\n } else {\n // Fill the rest with zeros\n while (offset < end) {\n buff[offset++] = 0\n }\n }\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n let result = ''\n for (let i = 0; i < v6Size; i += 2) {\n if (i !== 0) {\n result += ':'\n }\n result += (buff[offset + i] << 8 | buff[offset + i + 1]).toString(16)\n }\n return result\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n}\n\nexport const name = 'ip'\nexport function sizeOf (ip) {\n if (v4.isFormat(ip)) return v4.size\n if (v6.isFormat(ip)) return v6.size\n throw Error(`Invalid ip address: ${ip}`)\n}\n\nexport function familyOf (string) {\n return sizeOf(string) === v4.size ? 1 : 2\n}\n\nexport function encode (ip, buff, offset) {\n offset = ~~offset\n const size = sizeOf(ip)\n if (typeof buff === 'function') {\n buff = buff(offset + size)\n }\n if (size === v4.size) {\n return v4.encode(ip, buff, offset)\n }\n return v6.encode(ip, buff, offset)\n}\n\nexport function decode (buff, offset, length) {\n offset = ~~offset\n length = length || (buff.length - offset)\n if (length === v4.size) {\n return v4.decode(buff, offset, length)\n }\n if (length === v6.size) {\n return v6.decode(buff, offset, length)\n }\n throw Error(`Invalid buffer size needs to be ${v4.size} for v4 or ${v6.size} for v6.`)\n}\n","export function toString (type) {\n switch (type) {\n case 1: return 'A'\n case 10: return 'NULL'\n case 28: return 'AAAA'\n case 18: return 'AFSDB'\n case 42: return 'APL'\n case 257: return 'CAA'\n case 60: return 'CDNSKEY'\n case 59: return 'CDS'\n case 37: return 'CERT'\n case 5: return 'CNAME'\n case 49: return 'DHCID'\n case 32769: return 'DLV'\n case 39: return 'DNAME'\n case 48: return 'DNSKEY'\n case 43: return 'DS'\n case 55: return 'HIP'\n case 13: return 'HINFO'\n case 45: return 'IPSECKEY'\n case 25: return 'KEY'\n case 36: return 'KX'\n case 29: return 'LOC'\n case 15: return 'MX'\n case 35: return 'NAPTR'\n case 2: return 'NS'\n case 47: return 'NSEC'\n case 50: return 'NSEC3'\n case 51: return 'NSEC3PARAM'\n case 12: return 'PTR'\n case 46: return 'RRSIG'\n case 17: return 'RP'\n case 24: return 'SIG'\n case 6: return 'SOA'\n case 99: return 'SPF'\n case 33: return 'SRV'\n case 44: return 'SSHFP'\n case 32768: return 'TA'\n case 249: return 'TKEY'\n case 52: return 'TLSA'\n case 250: return 'TSIG'\n case 16: return 'TXT'\n case 252: return 'AXFR'\n case 251: return 'IXFR'\n case 41: return 'OPT'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + type\n}\n\nexport function toType (name) {\n switch (name.toUpperCase()) {\n case 'A': return 1\n case 'NULL': return 10\n case 'AAAA': return 28\n case 'AFSDB': return 18\n case 'APL': return 42\n case 'CAA': return 257\n case 'CDNSKEY': return 60\n case 'CDS': return 59\n case 'CERT': return 37\n case 'CNAME': return 5\n case 'DHCID': return 49\n case 'DLV': return 32769\n case 'DNAME': return 39\n case 'DNSKEY': return 48\n case 'DS': return 43\n case 'HIP': return 55\n case 'HINFO': return 13\n case 'IPSECKEY': return 45\n case 'KEY': return 25\n case 'KX': return 36\n case 'LOC': return 29\n case 'MX': return 15\n case 'NAPTR': return 35\n case 'NS': return 2\n case 'NSEC': return 47\n case 'NSEC3': return 50\n case 'NSEC3PARAM': return 51\n case 'PTR': return 12\n case 'RRSIG': return 46\n case 'RP': return 17\n case 'SIG': return 24\n case 'SOA': return 6\n case 'SPF': return 99\n case 'SRV': return 33\n case 'SSHFP': return 44\n case 'TA': return 32768\n case 'TKEY': return 249\n case 'TLSA': return 52\n case 'TSIG': return 250\n case 'TXT': return 16\n case 'AXFR': return 252\n case 'IXFR': return 251\n case 'OPT': return 41\n case 'ANY': return 255\n case '*': return 255\n }\n if (name.toUpperCase().startsWith('UNKNOWN_')) return parseInt(name.slice(8))\n return 0\n}\n","/*\n * Traditional DNS header RCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml\n */\n\nexport function toString (rcode) {\n switch (rcode) {\n case 0: return 'NOERROR'\n case 1: return 'FORMERR'\n case 2: return 'SERVFAIL'\n case 3: return 'NXDOMAIN'\n case 4: return 'NOTIMP'\n case 5: return 'REFUSED'\n case 6: return 'YXDOMAIN'\n case 7: return 'YXRRSET'\n case 8: return 'NXRRSET'\n case 9: return 'NOTAUTH'\n case 10: return 'NOTZONE'\n case 11: return 'RCODE_11'\n case 12: return 'RCODE_12'\n case 13: return 'RCODE_13'\n case 14: return 'RCODE_14'\n case 15: return 'RCODE_15'\n }\n return 'RCODE_' + rcode\n}\n\nexport function toRcode (code) {\n switch (code.toUpperCase()) {\n case 'NOERROR': return 0\n case 'FORMERR': return 1\n case 'SERVFAIL': return 2\n case 'NXDOMAIN': return 3\n case 'NOTIMP': return 4\n case 'REFUSED': return 5\n case 'YXDOMAIN': return 6\n case 'YXRRSET': return 7\n case 'NXRRSET': return 8\n case 'NOTAUTH': return 9\n case 'NOTZONE': return 10\n case 'RCODE_11': return 11\n case 'RCODE_12': return 12\n case 'RCODE_13': return 13\n case 'RCODE_14': return 14\n case 'RCODE_15': return 15\n }\n return 0\n}\n","/*\n * Traditional DNS header OPCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-5\n */\n\nexport function toString (opcode) {\n switch (opcode) {\n case 0: return 'QUERY'\n case 1: return 'IQUERY'\n case 2: return 'STATUS'\n case 3: return 'OPCODE_3'\n case 4: return 'NOTIFY'\n case 5: return 'UPDATE'\n case 6: return 'OPCODE_6'\n case 7: return 'OPCODE_7'\n case 8: return 'OPCODE_8'\n case 9: return 'OPCODE_9'\n case 10: return 'OPCODE_10'\n case 11: return 'OPCODE_11'\n case 12: return 'OPCODE_12'\n case 13: return 'OPCODE_13'\n case 14: return 'OPCODE_14'\n case 15: return 'OPCODE_15'\n }\n return 'OPCODE_' + opcode\n}\n\nexport function toOpcode (code) {\n switch (code.toUpperCase()) {\n case 'QUERY': return 0\n case 'IQUERY': return 1\n case 'STATUS': return 2\n case 'OPCODE_3': return 3\n case 'NOTIFY': return 4\n case 'UPDATE': return 5\n case 'OPCODE_6': return 6\n case 'OPCODE_7': return 7\n case 'OPCODE_8': return 8\n case 'OPCODE_9': return 9\n case 'OPCODE_10': return 10\n case 'OPCODE_11': return 11\n case 'OPCODE_12': return 12\n case 'OPCODE_13': return 13\n case 'OPCODE_14': return 14\n case 'OPCODE_15': return 15\n }\n return 0\n}\n","export function toString (klass) {\n switch (klass) {\n case 1: return 'IN'\n case 2: return 'CS'\n case 3: return 'CH'\n case 4: return 'HS'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + klass\n}\n\nexport function toClass (name) {\n switch (name.toUpperCase()) {\n case 'IN': return 1\n case 'CS': return 2\n case 'CH': return 3\n case 'HS': return 4\n case 'ANY': return 255\n }\n return 0\n}\n","export function toString (type) {\n switch (type) {\n // list at\n // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-11\n case 1: return 'LLQ'\n case 2: return 'UL'\n case 3: return 'NSID'\n case 5: return 'DAU'\n case 6: return 'DHU'\n case 7: return 'N3U'\n case 8: return 'CLIENT_SUBNET'\n case 9: return 'EXPIRE'\n case 10: return 'COOKIE'\n case 11: return 'TCP_KEEPALIVE'\n case 12: return 'PADDING'\n case 13: return 'CHAIN'\n case 14: return 'KEY_TAG'\n case 26946: return 'DEVICEID'\n }\n if (type < 0) {\n return null\n }\n return `OPTION_${type}`\n}\n\nexport function toCode (name) {\n if (typeof name === 'number') {\n return name\n }\n if (!name) {\n return -1\n }\n switch (name.toUpperCase()) {\n case 'OPTION_0': return 0\n case 'LLQ': return 1\n case 'UL': return 2\n case 'NSID': return 3\n case 'OPTION_4': return 4\n case 'DAU': return 5\n case 'DHU': return 6\n case 'N3U': return 7\n case 'CLIENT_SUBNET': return 8\n case 'EXPIRE': return 9\n case 'COOKIE': return 10\n case 'TCP_KEEPALIVE': return 11\n case 'PADDING': return 12\n case 'CHAIN': return 13\n case 'KEY_TAG': return 14\n case 'DEVICEID': return 26946\n case 'OPTION_65535': return 65535\n }\n const m = name.match(/_(\\d+)$/)\n if (m) {\n return parseInt(m[1], 10)\n }\n return -1\n}\n","const SURROGATE_A = 0b1101100000000000\nconst SURROGATE_B = 0b1101110000000000\n\nexport const name = 'utf8'\n\nexport function encodingLength (str) {\n let len = 0\n const strLen = str.length\n for (let i = 0; i < strLen; i += 1) {\n const code = str.charCodeAt(i)\n if (code <= 0x7F) {\n len += 1\n } else if (code <= 0x07FF) {\n len += 2\n } else if ((code & 0xF800) !== SURROGATE_A) {\n len += 3\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n len += 3\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n len += 3\n } else {\n i = next\n len += 4\n }\n }\n }\n }\n return len\n}\n\nexport function encode (str, buf, offset) {\n const strLen = str.length\n if (offset === undefined || offset === null) {\n offset = 0\n }\n if (buf === undefined) {\n buf = new Uint8Array(encodingLength(str) + offset)\n }\n let off = offset\n for (let i = 0; i < strLen; i += 1) {\n let code = str.charCodeAt(i)\n if (code <= 0x7F) {\n buf[off++] = code\n } else if (code <= 0x07FF) {\n buf[off++] = 0b11000000 | ((code & 0b11111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b00000111111)\n } else if ((code & 0xF800) !== SURROGATE_A) {\n buf[off++] = 0b11100000 | ((code & 0b1111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b0000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b0000000000111111)\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n // Incorrectly started surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n // Incorrect surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n i = next\n code = 0b000010000000000000000 |\n ((code & 0b1111111111) << 10) |\n (nextCode & 0b1111111111)\n buf[off++] = 0b11110000 | ((code & 0b111000000000000000000) >> 18)\n buf[off++] = 0b10000000 | ((code & 0b000111111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b000000000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b000000000000000111111)\n }\n }\n }\n }\n encode.bytes = off - offset\n return buf\n}\nencode.bytes = 0\n\nexport function decode (buf, start, end) {\n let result = ''\n if (start === undefined || start === null) {\n start = 0\n }\n if (end === undefined || end === null) {\n end = buf.length\n }\n for (let offset = start; offset < end;) {\n const code = buf[offset++]\n let num\n if (code <= 128) {\n num = code\n } else if (code > 191 && code < 224) {\n num = ((code & 0b11111) << 6) | (buf[offset++] & 0b111111)\n } else if (code > 239 && code < 365) {\n num = (\n ((code & 0b111) << 18) |\n ((buf[offset++] & 0b111111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n ) - 0x10000\n const numA = SURROGATE_A | ((num >> 10) & 0b1111111111)\n result += String.fromCharCode(numA)\n num = SURROGATE_B | (num & 0b1111111111)\n } else {\n num = ((code & 0b1111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n }\n result += String.fromCharCode(num)\n }\n decode.bytes = end - start\n return result\n}\ndecode.bytes = 0\n","import * as utf8 from 'utf8-codec'\n\nexport const isU8Arr = input => input instanceof Uint8Array\n\nexport function bytelength (input) {\n return typeof input === 'string' ? utf8.encodingLength(input) : input.byteLength\n}\n\nexport function from (input) {\n if (input instanceof Uint8Array) {\n return input\n }\n if (Array.isArray(input)) {\n return new Uint8Array(input)\n }\n return utf8.encode(input)\n}\n\nexport function write (arr, str, start) {\n if (typeof str !== 'string') {\n throw new Error('unknown input type')\n }\n utf8.encode(str, arr, start)\n return utf8.encode.bytes\n}\n\nexport function toHex (buf, start, end) {\n let result = ''\n for (let offset = start; offset < end;) {\n const num = buf[offset++]\n const str = num.toString(16)\n result += (str.length === 1) ? '0' + str : str\n }\n return result\n}\n\nconst P_24 = Math.pow(2, 24)\nconst P_16 = Math.pow(2, 16)\nconst P_8 = Math.pow(2, 8)\nexport const readUInt32BE = (buf, offset) => buf[offset] * P_24 +\n buf[offset + 1] * P_16 +\n buf[offset + 2] * P_8 +\n buf[offset + 3]\n\nexport const readUInt16BE = (buf, offset) => (buf[offset] << 8) | buf[offset + 1]\nexport const writeUInt32BE = (buf, value, offset) => {\n value = +value\n buf[offset + 3] = value\n value = value >>> 8\n buf[offset + 2] = value\n value = value >>> 8\n buf[offset + 1] = value\n value = value >>> 8\n buf[offset] = value\n return offset + 4\n}\nexport const writeUInt16BE = (buf, value, offset) => {\n buf[offset] = value >> 8\n buf[offset + 1] = value & 0xFF\n return offset + 2\n}\n\nexport function copy (source, target, targetStart, sourceStart, sourceEnd) {\n if (targetStart < 0) {\n sourceStart -= targetStart\n targetStart = 0\n }\n\n if (sourceStart < 0) {\n sourceStart = 0\n }\n\n if (sourceEnd < 0) {\n return new Uint8Array(0)\n }\n\n if (targetStart >= target.length || sourceStart >= sourceEnd) {\n return 0\n }\n\n return _copyActual(source, target, targetStart, sourceStart, sourceEnd)\n}\n\nfunction _copyActual (source, target, targetStart, sourceStart, sourceEnd) {\n if (sourceEnd - sourceStart > target.length - targetStart) {\n sourceEnd = sourceStart + target.length - targetStart\n }\n\n let nb = sourceEnd - sourceStart\n const sourceLen = source.length - sourceStart\n if (nb > sourceLen) {\n nb = sourceLen\n }\n\n if (sourceStart !== 0 || sourceEnd < source.length) {\n source = new Uint8Array(source.buffer, source.byteOffset + sourceStart, nb)\n }\n\n target.set(source, targetStart)\n\n return nb\n}\n","import * as ip from '@leichtgewicht/ip-codec'\nimport * as types from './types.mjs'\nimport * as rcodes from './rcodes.mjs'\nimport * as opcodes from './opcodes.mjs'\nimport * as classes from './classes.mjs'\nimport * as optioncodes from './optioncodes.mjs'\nimport * as b from './buffer_utils.mjs'\nimport { decode as toUtf8 } from 'utf8-codec'\n\nconst QUERY_FLAG = 0\nconst RESPONSE_FLAG = 1 << 15\nconst FLUSH_MASK = 1 << 15\nconst NOT_FLUSH_MASK = ~FLUSH_MASK\nconst QU_MASK = 1 << 15\nconst NOT_QU_MASK = ~QU_MASK\n\nfunction codec ({ bytes = 0, encode, decode, encodingLength }) {\n encode.bytes = bytes\n decode.bytes = bytes\n return {\n encode,\n decode,\n encodingLength: encodingLength || (() => bytes)\n }\n}\n\nexport const name = codec({\n encode (str, buf, offset) {\n if (!buf) buf = new Uint8Array(name.encodingLength(str))\n if (!offset) offset = 0\n const oldOffset = offset\n\n // strip leading and trailing .\n const n = str.replace(/^\\.|\\.$/gm, '')\n if (n.length) {\n const list = n.split('.')\n\n for (let i = 0; i < list.length; i++) {\n const len = b.write(buf, list[i], offset + 1)\n buf[offset] = len\n offset += len + 1\n }\n }\n\n buf[offset++] = 0\n\n name.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const list = []\n let oldOffset = offset\n let totalLength = 0\n let consumedBytes = 0\n let jumped = false\n\n while (true) {\n if (offset >= buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const len = buf[offset++]\n consumedBytes += jumped ? 0 : 1\n\n if (len === 0) {\n break\n } else if ((len & 0xc0) === 0) {\n if (offset + len > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n totalLength += len + 1\n if (totalLength > 254) {\n throw new Error('Cannot decode name (name too long)')\n }\n list.push(toUtf8(buf, offset, offset + len))\n offset += len\n consumedBytes += jumped ? 0 : len\n } else if ((len & 0xc0) === 0xc0) {\n if (offset + 1 > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const jumpOffset = b.readUInt16BE(buf, offset - 1) - 0xc000\n if (jumpOffset >= oldOffset) {\n // Allow only pointers to prior data. RFC 1035, section 4.1.4 states:\n // \"[...] an entire domain name or a list of labels at the end of a domain name\n // is replaced with a pointer to a prior occurance (sic) of the same name.\"\n throw new Error('Cannot decode name (bad pointer)')\n }\n offset = jumpOffset\n oldOffset = jumpOffset\n consumedBytes += jumped ? 0 : 1\n jumped = true\n } else {\n throw new Error('Cannot decode name (bad label)')\n }\n }\n\n name.decode.bytes = consumedBytes\n return list.length === 0 ? '.' : list.join('.')\n },\n encodingLength (n) {\n if (n === '.' || n === '..') return 1\n return b.bytelength(n.replace(/^\\.|\\.$/gm, '')) + 2\n }\n})\n\nconst string = codec({\n encode (s, buf, offset) {\n if (!buf) buf = new Uint8Array(string.encodingLength(s))\n if (!offset) offset = 0\n\n const len = b.write(buf, s, offset + 1)\n buf[offset] = len\n string.encode.bytes = len + 1\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = buf[offset]\n const s = toUtf8(buf, offset + 1, offset + 1 + len)\n string.decode.bytes = len + 1\n return s\n },\n encodingLength (s) {\n return b.bytelength(s) + 1\n }\n})\n\nconst header = codec({\n bytes: 12,\n encode (h, buf, offset) {\n if (!buf) buf = new Uint8Array(header.encodingLength(h))\n if (!offset) offset = 0\n\n const flags = (h.flags || 0) & 32767\n const type = h.type === 'response' ? RESPONSE_FLAG : QUERY_FLAG\n\n b.writeUInt16BE(buf, h.id || 0, offset)\n b.writeUInt16BE(buf, flags | type, offset + 2)\n b.writeUInt16BE(buf, h.questions.length, offset + 4)\n b.writeUInt16BE(buf, h.answers.length, offset + 6)\n b.writeUInt16BE(buf, h.authorities.length, offset + 8)\n b.writeUInt16BE(buf, h.additionals.length, offset + 10)\n\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n if (buf.length < 12) throw new Error('Header must be 12 bytes')\n const flags = b.readUInt16BE(buf, offset + 2)\n\n return {\n id: b.readUInt16BE(buf, offset),\n type: flags & RESPONSE_FLAG ? 'response' : 'query',\n flags: flags & 32767,\n flag_qr: ((flags >> 15) & 0x1) === 1,\n opcode: opcodes.toString((flags >> 11) & 0xf),\n flag_aa: ((flags >> 10) & 0x1) === 1,\n flag_tc: ((flags >> 9) & 0x1) === 1,\n flag_rd: ((flags >> 8) & 0x1) === 1,\n flag_ra: ((flags >> 7) & 0x1) === 1,\n flag_z: ((flags >> 6) & 0x1) === 1,\n flag_ad: ((flags >> 5) & 0x1) === 1,\n flag_cd: ((flags >> 4) & 0x1) === 1,\n rcode: rcodes.toString(flags & 0xf),\n questions: new Array(b.readUInt16BE(buf, offset + 4)),\n answers: new Array(b.readUInt16BE(buf, offset + 6)),\n authorities: new Array(b.readUInt16BE(buf, offset + 8)),\n additionals: new Array(b.readUInt16BE(buf, offset + 10))\n }\n },\n encodingLength () {\n return 12\n }\n})\n\nconst runknown = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(runknown.encodingLength(data))\n if (!offset) offset = 0\n\n const dLen = data.length\n b.writeUInt16BE(buf, dLen, offset)\n b.copy(data, buf, offset + 2, 0, dLen)\n\n runknown.encode.bytes = dLen + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const data = buf.slice(offset + 2, offset + 2 + len)\n runknown.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return data.length + 2\n }\n})\n\nconst rns = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rns.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rns.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const dd = name.decode(buf, offset + 2)\n\n rns.decode.bytes = len + 2\n return dd\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsoa = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsoa.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n name.encode(data.mname, buf, offset)\n offset += name.encode.bytes\n name.encode(data.rname, buf, offset)\n offset += name.encode.bytes\n b.writeUInt32BE(buf, data.serial || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.refresh || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.retry || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.expire || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.minimum || 0, offset)\n offset += 4\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rsoa.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.rname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.serial = b.readUInt32BE(buf, offset)\n offset += 4\n data.refresh = b.readUInt32BE(buf, offset)\n offset += 4\n data.retry = b.readUInt32BE(buf, offset)\n offset += 4\n data.expire = b.readUInt32BE(buf, offset)\n offset += 4\n data.minimum = b.readUInt32BE(buf, offset)\n offset += 4\n\n rsoa.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 22 + name.encodingLength(data.mname) + name.encodingLength(data.rname)\n }\n})\n\nconst rtxt = codec({\n encode (data, buf, offset) {\n if (!Array.isArray(data)) data = [data]\n for (let i = 0; i < data.length; i++) {\n if (typeof data[i] === 'string') {\n data[i] = b.from(data[i])\n }\n if (!b.isU8Arr(data[i])) {\n throw new Error('Must be a Buffer')\n }\n }\n\n if (!buf) buf = new Uint8Array(rtxt.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n\n data.forEach(function (d) {\n buf[offset++] = d.length\n b.copy(d, buf, offset, 0, d.length)\n offset += d.length\n })\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rtxt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n let remaining = b.readUInt16BE(buf, offset)\n offset += 2\n\n const data = []\n while (remaining > 0) {\n const len = buf[offset++]\n --remaining\n if (remaining < len) {\n throw new Error('Buffer overflow')\n }\n data.push(buf.slice(offset, offset + len))\n offset += len\n remaining -= len\n }\n\n rtxt.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!Array.isArray(data)) data = [data]\n let length = 2\n data.forEach(function (buf) {\n if (typeof buf === 'string') {\n length += b.bytelength(buf) + 1\n } else {\n length += buf.length + 1\n }\n })\n return length\n }\n})\n\nconst rnull = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rnull.encodingLength(data))\n if (!offset) offset = 0\n\n if (typeof data === 'string') data = b.from(data)\n if (!data) data = new Uint8Array(0)\n\n const oldOffset = offset\n offset += 2\n\n const len = data.length\n b.copy(data, buf, offset, 0, len)\n offset += len\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rnull.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n const len = b.readUInt16BE(buf, offset)\n\n offset += 2\n\n const data = buf.slice(offset, offset + len)\n offset += len\n\n rnull.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!data) return 2\n return (b.isU8Arr(data) ? data.length : b.bytelength(data)) + 2\n }\n})\n\nconst rhinfo = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rhinfo.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n string.encode(data.cpu, buf, offset)\n offset += string.encode.bytes\n string.encode(data.os, buf, offset)\n offset += string.encode.bytes\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rhinfo.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.cpu = string.decode(buf, offset)\n offset += string.decode.bytes\n data.os = string.decode(buf, offset)\n offset += string.decode.bytes\n rhinfo.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.cpu) + string.encodingLength(data.os) + 2\n }\n})\n\nconst rptr = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rptr.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rptr.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const data = name.decode(buf, offset + 2)\n rptr.decode.bytes = name.decode.bytes + 2\n return data\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsrv = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsrv.encodingLength(data))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, data.priority || 0, offset + 2)\n b.writeUInt16BE(buf, data.weight || 0, offset + 4)\n b.writeUInt16BE(buf, data.port || 0, offset + 6)\n name.encode(data.target, buf, offset + 8)\n\n const len = name.encode.bytes + 6\n b.writeUInt16BE(buf, len, offset)\n\n rsrv.encode.bytes = len + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n\n const data = {}\n data.priority = b.readUInt16BE(buf, offset + 2)\n data.weight = b.readUInt16BE(buf, offset + 4)\n data.port = b.readUInt16BE(buf, offset + 6)\n data.target = name.decode(buf, offset + 8)\n\n rsrv.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return 8 + name.encodingLength(data.target)\n }\n})\n\nconst rcaa = codec({\n encode (data, buf, offset) {\n const len = rcaa.encodingLength(data)\n\n if (!buf) buf = new Uint8Array(rcaa.encodingLength(data))\n if (!offset) offset = 0\n\n if (data.issuerCritical) {\n data.flags = rcaa.ISSUER_CRITICAL\n }\n\n b.writeUInt16BE(buf, len - 2, offset)\n offset += 2\n buf[offset] = data.flags || 0\n offset += 1\n string.encode(data.tag, buf, offset)\n offset += string.encode.bytes\n b.write(buf, data.value, offset)\n offset += b.bytelength(data.value)\n\n rcaa.encode.bytes = len\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n\n const oldOffset = offset\n const data = {}\n data.flags = buf[offset]\n offset += 1\n data.tag = string.decode(buf, offset)\n offset += string.decode.bytes\n data.value = toUtf8(buf, offset, oldOffset + len)\n\n data.issuerCritical = !!(data.flags & rcaa.ISSUER_CRITICAL)\n\n rcaa.decode.bytes = len + 2\n\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.tag) + string.encodingLength(data.value) + 2\n }\n})\n\nrcaa.ISSUER_CRITICAL = 1 << 7\n\nconst rmx = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rmx.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n b.writeUInt16BE(buf, data.preference || 0, offset)\n offset += 2\n name.encode(data.exchange, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rmx.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.preference = b.readUInt16BE(buf, offset)\n offset += 2\n data.exchange = name.decode(buf, offset)\n offset += name.decode.bytes\n\n rmx.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 4 + name.encodingLength(data.exchange)\n }\n})\n\nconst ra = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(ra.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 4, offset)\n offset += 2\n ip.v4.encode(host, buf, offset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v4.decode(buf, offset)\n return host\n },\n bytes: 6\n})\n\nconst raaaa = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(raaaa.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 16, offset)\n offset += 2\n ip.v6.encode(host, buf, offset)\n raaaa.encode.bytes = 18\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v6.decode(buf, offset)\n raaaa.decode.bytes = 18\n return host\n },\n bytes: 18\n})\n\nconst alloc = size => new Uint8Array(size)\n\nconst roption = codec({\n encode (option, buf, offset) {\n if (!buf) buf = new Uint8Array(roption.encodingLength(option))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const code = optioncodes.toCode(option.code)\n b.writeUInt16BE(buf, code, offset)\n offset += 2\n if (option.data) {\n b.writeUInt16BE(buf, option.data.length, offset)\n offset += 2\n b.copy(option.data, buf, offset)\n offset += option.data.length\n } else {\n switch (code) {\n // case 3: NSID. No encode makes sense.\n // case 5,6,7: Not implementable\n case 8: // ECS\n {\n // note: do IP math before calling\n const spl = option.sourcePrefixLength || 0\n const fam = option.family || ip.familyOf(option.ip, alloc)\n const ipBuf = ip.encode(option.ip, alloc)\n const ipLen = Math.ceil(spl / 8)\n b.writeUInt16BE(buf, ipLen + 4, offset)\n offset += 2\n b.writeUInt16BE(buf, fam, offset)\n offset += 2\n buf[offset++] = spl\n buf[offset++] = option.scopePrefixLength || 0\n\n b.copy(ipBuf, buf, offset, 0, ipLen)\n offset += ipLen\n }\n break\n // case 9: EXPIRE (experimental)\n // case 10: COOKIE. No encode makes sense.\n case 11: // KEEP-ALIVE\n if (option.timeout) {\n b.writeUInt16BE(buf, 2, offset)\n offset += 2\n b.writeUInt16BE(buf, option.timeout, offset)\n offset += 2\n } else {\n b.writeUInt16BE(buf, 0, offset)\n offset += 2\n }\n break\n case 12: // PADDING\n {\n const len = option.length || 0\n b.writeUInt16BE(buf, len, offset)\n offset += 2\n buf.fill(0, offset, offset + len)\n offset += len\n }\n break\n // case 13: CHAIN. Experimental.\n case 14: // KEY-TAG\n {\n const tagsLen = option.tags.length * 2\n b.writeUInt16BE(buf, tagsLen, offset)\n offset += 2\n for (const tag of option.tags) {\n b.writeUInt16BE(buf, tag, offset)\n offset += 2\n }\n }\n break\n default:\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n }\n\n roption.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const option = {}\n option.code = b.readUInt16BE(buf, offset)\n option.type = optioncodes.toString(option.code)\n offset += 2\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n option.data = buf.slice(offset, offset + len)\n switch (option.code) {\n // case 3: NSID. No decode makes sense.\n case 8: // ECS\n option.family = b.readUInt16BE(buf, offset)\n offset += 2\n option.sourcePrefixLength = buf[offset++]\n option.scopePrefixLength = buf[offset++]\n {\n const padded = new Uint8Array((option.family === 1) ? 4 : 16)\n b.copy(buf, padded, 0, offset, offset + len - 4)\n option.ip = ip.decode(padded)\n }\n break\n // case 12: Padding. No decode makes sense.\n case 11: // KEEP-ALIVE\n if (len > 0) {\n option.timeout = b.readUInt16BE(buf, offset)\n offset += 2\n }\n break\n case 14:\n option.tags = []\n for (let i = 0; i < len; i += 2) {\n option.tags.push(b.readUInt16BE(buf, offset))\n offset += 2\n }\n // don't worry about default. caller will use data if desired\n }\n\n roption.decode.bytes = len + 4\n return option\n },\n encodingLength (option) {\n if (option.data) {\n return option.data.length + 4\n }\n const code = optioncodes.toCode(option.code)\n switch (code) {\n case 8: // ECS\n {\n const spl = option.sourcePrefixLength || 0\n return Math.ceil(spl / 8) + 8\n }\n case 11: // KEEP-ALIVE\n return (typeof option.timeout === 'number') ? 6 : 4\n case 12: // PADDING\n return option.length + 4\n case 14: // KEY-TAG\n return 4 + (option.tags.length * 2)\n }\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n})\n\nconst ropt = codec({\n encode (options, buf, offset) {\n if (!buf) buf = new Uint8Array(ropt.encodingLength(options))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const rdlen = encodingLengthList(options, roption)\n b.writeUInt16BE(buf, rdlen, offset)\n offset = encodeList(options, roption, buf, offset + 2)\n\n ropt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const options = []\n let rdlen = b.readUInt16BE(buf, offset)\n offset += 2\n let o = 0\n while (rdlen > 0) {\n options[o++] = roption.decode(buf, offset)\n offset += roption.decode.bytes\n rdlen -= roption.decode.bytes\n }\n ropt.decode.bytes = offset - oldOffset\n return options\n },\n encodingLength (options) {\n return 2 + encodingLengthList(options || [], roption)\n }\n})\n\nconst rdnskey = codec({\n encode (key, buf, offset) {\n if (!buf) buf = new Uint8Array(rdnskey.encodingLength(key))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const keydata = key.key\n if (!b.isU8Arr(keydata)) {\n throw new Error('Key must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, key.flags, offset)\n offset += 2\n buf[offset] = rdnskey.PROTOCOL_DNSSEC\n offset += 1\n buf[offset] = key.algorithm\n offset += 1\n b.copy(keydata, buf, offset, 0, keydata.length)\n offset += keydata.length\n\n rdnskey.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rdnskey.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const key = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n key.flags = b.readUInt16BE(buf, offset)\n offset += 2\n if (buf[offset] !== rdnskey.PROTOCOL_DNSSEC) {\n throw new Error('Protocol must be 3')\n }\n offset += 1\n key.algorithm = buf[offset]\n offset += 1\n key.key = buf.slice(offset, oldOffset + length + 2)\n offset += key.key.length\n rdnskey.decode.bytes = offset - oldOffset\n return key\n },\n encodingLength (key) {\n return 6 + b.bytelength(key.key)\n }\n})\n\nrdnskey.PROTOCOL_DNSSEC = 3\nrdnskey.ZONE_KEY = 0x80\nrdnskey.SECURE_ENTRYPOINT = 0x8000\n\nconst rrrsig = codec({\n encode (sig, buf, offset) {\n if (!buf) buf = new Uint8Array(rrrsig.encodingLength(sig))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const signature = sig.signature\n if (!b.isU8Arr(signature)) {\n throw new Error('Signature must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, types.toType(sig.typeCovered), offset)\n offset += 2\n buf[offset] = sig.algorithm\n offset += 1\n buf[offset] = sig.labels\n offset += 1\n b.writeUInt32BE(buf, sig.originalTTL, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.expiration, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.inception, offset)\n offset += 4\n b.writeUInt16BE(buf, sig.keyTag, offset)\n offset += 2\n name.encode(sig.signersName, buf, offset)\n offset += name.encode.bytes\n b.copy(signature, buf, offset, 0, signature.length)\n offset += signature.length\n\n rrrsig.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrrsig.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const sig = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n sig.typeCovered = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n sig.algorithm = buf[offset]\n offset += 1\n sig.labels = buf[offset]\n offset += 1\n sig.originalTTL = b.readUInt32BE(buf, offset)\n offset += 4\n sig.expiration = b.readUInt32BE(buf, offset)\n offset += 4\n sig.inception = b.readUInt32BE(buf, offset)\n offset += 4\n sig.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n sig.signersName = name.decode(buf, offset)\n offset += name.decode.bytes\n sig.signature = buf.slice(offset, oldOffset + length + 2)\n offset += sig.signature.length\n rrrsig.decode.bytes = offset - oldOffset\n return sig\n },\n encodingLength (sig) {\n return 20 +\n name.encodingLength(sig.signersName) +\n b.bytelength(sig.signature)\n }\n})\nconst rrp = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rrp.encodingLength(data))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(data.mbox || '.', buf, offset)\n offset += name.encode.bytes\n name.encode(data.txt || '.', buf, offset)\n offset += name.encode.bytes\n rrp.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrp.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mbox = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n data.txt = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n rrp.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 2 + name.encodingLength(data.mbox || '.') + name.encodingLength(data.txt || '.')\n }\n})\n\nconst typebitmap = codec({\n encode (typelist, buf, offset) {\n if (!buf) buf = new Uint8Array(typebitmap.encodingLength(typelist))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typesByWindow = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n if (typesByWindow[typeid >> 8] === undefined) {\n typesByWindow[typeid >> 8] = []\n }\n typesByWindow[typeid >> 8][(typeid >> 3) & 0x1F] |= 1 << (7 - (typeid & 0x7))\n }\n\n for (let i = 0; i < typesByWindow.length; i++) {\n if (typesByWindow[i] !== undefined) {\n const windowBuf = b.from(typesByWindow[i])\n buf[offset] = i\n offset += 1\n buf[offset] = windowBuf.length\n offset += 1\n b.copy(windowBuf, buf, offset, 0, windowBuf.length)\n offset += windowBuf.length\n }\n }\n\n typebitmap.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset, length) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typelist = []\n while (offset - oldOffset < length) {\n const window = buf[offset]\n offset += 1\n const windowLength = buf[offset]\n offset += 1\n for (let i = 0; i < windowLength; i++) {\n const b = buf[offset + i]\n for (let j = 0; j < 8; j++) {\n if (b & (1 << (7 - j))) {\n const typeid = types.toString((window << 8) | (i << 3) | j)\n typelist.push(typeid)\n }\n }\n }\n offset += windowLength\n }\n\n typebitmap.decode.bytes = offset - oldOffset\n return typelist\n },\n encodingLength (typelist) {\n const extents = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n extents[typeid >> 8] = Math.max(extents[typeid >> 8] || 0, typeid & 0xFF)\n }\n\n let len = 0\n for (let i = 0; i < extents.length; i++) {\n if (extents[i] !== undefined) {\n len += 2 + Math.ceil((extents[i] + 1) / 8)\n }\n }\n\n return len\n }\n})\n\nconst rnsec = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(record.nextDomain, buf, offset)\n offset += name.encode.bytes\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.nextDomain = name.decode(buf, offset)\n offset += name.decode.bytes\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 2 +\n name.encodingLength(record.nextDomain) +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rnsec3 = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec3.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const salt = record.salt\n if (!b.isU8Arr(salt)) {\n throw new Error('salt must be a Buffer')\n }\n\n const nextDomain = record.nextDomain\n if (!b.isU8Arr(nextDomain)) {\n throw new Error('nextDomain must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n buf[offset] = record.algorithm\n offset += 1\n buf[offset] = record.flags\n offset += 1\n b.writeUInt16BE(buf, record.iterations, offset)\n offset += 2\n buf[offset] = salt.length\n offset += 1\n b.copy(salt, buf, offset, 0, salt.length)\n offset += salt.length\n buf[offset] = nextDomain.length\n offset += 1\n b.copy(nextDomain, buf, offset, 0, nextDomain.length)\n offset += nextDomain.length\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec3.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec3.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.algorithm = buf[offset]\n offset += 1\n record.flags = buf[offset]\n offset += 1\n record.iterations = b.readUInt16BE(buf, offset)\n offset += 2\n const saltLength = buf[offset]\n offset += 1\n record.salt = buf.slice(offset, offset + saltLength)\n offset += saltLength\n const hashLength = buf[offset]\n offset += 1\n record.nextDomain = buf.slice(offset, offset + hashLength)\n offset += hashLength\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec3.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 8 +\n record.salt.length +\n record.nextDomain.length +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rds = codec({\n encode (digest, buf, offset) {\n if (!buf) buf = new Uint8Array(rds.encodingLength(digest))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digestdata = digest.digest\n if (!b.isU8Arr(digestdata)) {\n throw new Error('Digest must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, digest.keyTag, offset)\n offset += 2\n buf[offset] = digest.algorithm\n offset += 1\n buf[offset] = digest.digestType\n offset += 1\n b.copy(digestdata, buf, offset, 0, digestdata.length)\n offset += digestdata.length\n\n rds.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rds.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digest = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n digest.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n digest.algorithm = buf[offset]\n offset += 1\n digest.digestType = buf[offset]\n offset += 1\n digest.digest = buf.slice(offset, oldOffset + length + 2)\n offset += digest.digest.length\n rds.decode.bytes = offset - oldOffset\n return digest\n },\n encodingLength (digest) {\n return 6 + b.bytelength(digest.digest)\n }\n})\n\nfunction renc (type) {\n switch (type.toUpperCase()) {\n case 'A': return ra\n case 'PTR': return rptr\n case 'CNAME': return rptr\n case 'DNAME': return rptr\n case 'TXT': return rtxt\n case 'NULL': return rnull\n case 'AAAA': return raaaa\n case 'SRV': return rsrv\n case 'HINFO': return rhinfo\n case 'CAA': return rcaa\n case 'NS': return rns\n case 'SOA': return rsoa\n case 'MX': return rmx\n case 'OPT': return ropt\n case 'DNSKEY': return rdnskey\n case 'RRSIG': return rrrsig\n case 'RP': return rrp\n case 'NSEC': return rnsec\n case 'NSEC3': return rnsec3\n case 'DS': return rds\n }\n return runknown\n}\n\nexport const answer = codec({\n encode (a, buf, offset) {\n if (!buf) buf = new Uint8Array(answer.encodingLength(a))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(a.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(a.type), offset)\n\n if (a.type.toUpperCase() === 'OPT') {\n if (a.name !== '.') {\n throw new Error('OPT name must be root.')\n }\n b.writeUInt16BE(buf, a.udpPayloadSize || 4096, offset + 2)\n buf[offset + 4] = a.extendedRcode || 0\n buf[offset + 5] = a.ednsVersion || 0\n b.writeUInt16BE(buf, a.flags || 0, offset + 6)\n\n offset += 8\n ropt.encode(a.options || [], buf, offset)\n offset += ropt.encode.bytes\n } else {\n let klass = classes.toClass(a.class === undefined ? 'IN' : a.class)\n if (a.flush) klass |= FLUSH_MASK // the 1st bit of the class is the flush bit\n b.writeUInt16BE(buf, klass, offset + 2)\n b.writeUInt32BE(buf, a.ttl || 0, offset + 4)\n\n offset += 8\n const enc = renc(a.type)\n enc.encode(a.data, buf, offset)\n offset += enc.encode.bytes\n }\n\n answer.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const a = {}\n const oldOffset = offset\n\n a.name = name.decode(buf, offset)\n offset += name.decode.bytes\n a.type = types.toString(b.readUInt16BE(buf, offset))\n if (a.type === 'OPT') {\n a.udpPayloadSize = b.readUInt16BE(buf, offset + 2)\n a.extendedRcode = buf[offset + 4]\n a.ednsVersion = buf[offset + 5]\n a.flags = b.readUInt16BE(buf, offset + 6)\n a.flag_do = ((a.flags >> 15) & 0x1) === 1\n a.options = ropt.decode(buf, offset + 8)\n offset += 8 + ropt.decode.bytes\n } else {\n const klass = b.readUInt16BE(buf, offset + 2)\n a.ttl = b.readUInt32BE(buf, offset + 4)\n\n a.class = classes.toString(klass & NOT_FLUSH_MASK)\n a.flush = !!(klass & FLUSH_MASK)\n\n const enc = renc(a.type)\n a.data = enc.decode(buf, offset + 8)\n offset += 8 + enc.decode.bytes\n }\n\n answer.decode.bytes = offset - oldOffset\n return a\n },\n encodingLength (a) {\n const data = (a.data !== null && a.data !== undefined) ? a.data : a.options\n return name.encodingLength(a.name) + 8 + renc(a.type).encodingLength(data)\n }\n})\n\nexport const question = codec({\n encode (q, buf, offset) {\n if (!buf) buf = new Uint8Array(question.encodingLength(q))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(q.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(q.type), offset)\n offset += 2\n\n b.writeUInt16BE(buf, classes.toClass(q.class === undefined ? 'IN' : q.class), offset)\n offset += 2\n\n question.encode.bytes = offset - oldOffset\n return q\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const q = {}\n\n q.name = name.decode(buf, offset)\n offset += name.decode.bytes\n\n q.type = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n q.class = classes.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n const qu = !!(q.class & QU_MASK)\n if (qu) q.class &= NOT_QU_MASK\n\n question.decode.bytes = offset - oldOffset\n return q\n },\n encodingLength (q) {\n return name.encodingLength(q.name) + 4\n }\n})\n\nexport {\n rsoa as soa,\n rtxt as txt,\n rnull as null,\n runknown as unknown,\n rns as ns,\n rhinfo as hinfo,\n rptr as ptr,\n rptr as cname,\n rptr as dname,\n rsrv as srv,\n rcaa as caa,\n rmx as mx,\n ra as a,\n raaaa as aaaa,\n roption as option,\n ropt as opt,\n rdnskey as dnskey,\n rrrsig as rrsig,\n rrp as rp,\n rnsec as nsec,\n rnsec3 as nsec3,\n rds as ds,\n renc as enc\n}\n\nexport const AUTHORITATIVE_ANSWER = 1 << 10\nexport const TRUNCATED_RESPONSE = 1 << 9\nexport const RECURSION_DESIRED = 1 << 8\nexport const RECURSION_AVAILABLE = 1 << 7\nexport const AUTHENTIC_DATA = 1 << 5\nexport const CHECKING_DISABLED = 1 << 4\nexport const DNSSEC_OK = 1 << 15\n\nexport const packet = {\n encode: function (result, buf, offset) {\n const allocing = !buf\n\n if (allocing) buf = new Uint8Array(encodingLength(result))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n if (!result.questions) result.questions = []\n if (!result.answers) result.answers = []\n if (!result.authorities) result.authorities = []\n if (!result.additionals) result.additionals = []\n\n header.encode(result, buf, offset)\n offset += header.encode.bytes\n\n offset = encodeList(result.questions, question, buf, offset)\n offset = encodeList(result.answers, answer, buf, offset)\n offset = encodeList(result.authorities, answer, buf, offset)\n offset = encodeList(result.additionals, answer, buf, offset)\n\n packet.encode.bytes = offset - oldOffset\n\n // just a quick sanity check\n if (allocing && encode.bytes !== buf.length) {\n return buf.slice(0, encode.bytes)\n }\n\n return buf\n },\n decode: function (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const result = header.decode(buf, offset)\n offset += header.decode.bytes\n\n offset = decodeList(result.questions, question, buf, offset)\n offset = decodeList(result.answers, answer, buf, offset)\n offset = decodeList(result.authorities, answer, buf, offset)\n offset = decodeList(result.additionals, answer, buf, offset)\n\n packet.decode.bytes = offset - oldOffset\n\n return result\n },\n encodingLength: function (result) {\n return header.encodingLength(result) +\n encodingLengthList(result.questions || [], question) +\n encodingLengthList(result.answers || [], answer) +\n encodingLengthList(result.authorities || [], answer) +\n encodingLengthList(result.additionals || [], answer)\n }\n}\npacket.encode.bytes = 0\npacket.decode.bytes = 0\n\nfunction sanitizeSingle (input, type) {\n if (input.questions) {\n throw new Error('Only one .question object expected instead of a .questions array!')\n }\n const sanitized = Object.assign({\n type\n }, input)\n if (sanitized.question) {\n sanitized.questions = [sanitized.question]\n delete sanitized.question\n }\n return sanitized\n}\n\nexport const query = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'query'), buf, offset)\n query.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n query.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'query'))\n }\n}\nquery.encode.bytes = 0\nquery.decode.bytes = 0\n\nexport const response = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'response'), buf, offset)\n response.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n response.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'response'))\n }\n}\nresponse.encode.bytes = 0\nresponse.decode.bytes = 0\n\nexport const encode = packet.encode\nexport const decode = packet.decode\nexport const encodingLength = packet.encodingLength\n\nexport function streamEncode (result) {\n const buf = encode(result)\n const combine = new Uint8Array(2 + buf.byteLength)\n b.writeUInt16BE(combine, buf.byteLength)\n b.copy(buf, combine, 2, 0, buf.length)\n streamEncode.bytes = combine.byteLength\n return combine\n}\nstreamEncode.bytes = 0\n\nexport function streamDecode (sbuf) {\n const len = b.readUInt16BE(sbuf, 0)\n if (sbuf.byteLength < len + 2) {\n // not enough data\n return null\n }\n const result = decode(sbuf.slice(2))\n streamDecode.bytes = decode.bytes\n return result\n}\nstreamDecode.bytes = 0\n\nexport function encodingLengthList (list, enc) {\n let len = 0\n for (let i = 0; i < list.length; i++) len += enc.encodingLength(list[i])\n return len\n}\n\nexport function encodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n enc.encode(list[i], buf, offset)\n offset += enc.encode.bytes\n }\n return offset\n}\n\nexport function decodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n list[i] = enc.decode(buf, offset)\n offset += enc.decode.bytes\n }\n return offset\n}\n","export const PREFERS_PADDING = 1\nexport const PREFERS_NO_PADDING = 2\n\nexport function make (name, charset, padding, paddingMode) {\n if (charset.length !== 64) {\n throw new Error(`Charset needs to be 64 characters long! (${charset.length})`)\n }\n const byCharCode = new Uint8Array(256)\n const byNum = new Uint8Array(64)\n for (let i = 0; i < 64; i += 1) {\n const code = charset.charCodeAt(i)\n if (code > 255) {\n throw new Error(`Character #${i} in charset [code=${code}, char=${charset.charAt(i)}] is too high! (max=255)`)\n }\n if (byCharCode[code] !== 0) {\n throw new Error(`Character [code=${code}, char=${charset.charAt(i)}] is more than once in the charset!`)\n }\n byCharCode[code] = i\n byNum[i] = code\n }\n const padCode = padding.charCodeAt(0)\n const codec = {\n name,\n encodingLength (str) {\n const strLen = str.length\n const len = strLen * 0.75 | 0\n if (str.charCodeAt(strLen - 1) === padCode) {\n if (str.charCodeAt(strLen - 2) === padCode) {\n return len - 2\n }\n return len - 1\n }\n return len\n },\n encode (str, buffer, offset) {\n if (buffer === null || buffer === undefined) {\n buffer = new Uint8Array(codec.encodingLength(str))\n }\n if (offset === null || offset === undefined) {\n offset = 0\n }\n\n let strLen = str.length\n if (str.charCodeAt(strLen - 1) === padCode) {\n if (str.charCodeAt(strLen - 2) === padCode) {\n strLen -= 2\n } else {\n strLen -= 1\n }\n }\n\n const padding = strLen % 4\n const safeLen = strLen - padding\n\n let off = offset\n let i = 0\n while (i < safeLen) {\n const code =\n (byCharCode[str.charCodeAt(i)] << 18) |\n (byCharCode[str.charCodeAt(i + 1)] << 12) |\n (byCharCode[str.charCodeAt(i + 2)] << 6) |\n byCharCode[str.charCodeAt(i + 3)]\n buffer[off++] = code >> 16\n buffer[off++] = code >> 8\n buffer[off++] = code\n i += 4\n }\n\n if (padding === 3) {\n const code =\n (byCharCode[str.charCodeAt(i)] << 10) |\n (byCharCode[str.charCodeAt(i + 1)] << 4) |\n (byCharCode[str.charCodeAt(i + 2)] >> 2)\n buffer[off++] = code >> 8\n buffer[off++] = code\n } else if (padding === 2) {\n buffer[off++] = (byCharCode[str.charCodeAt(i)] << 2) |\n (byCharCode[str.charCodeAt(i + 1)] >> 4)\n }\n\n codec.encode.bytes = off - offset\n return buffer\n },\n decode (buffer, start, end) {\n if (start === null || start === undefined) {\n start = 0\n }\n if (end === null || end === undefined) {\n end = buffer.length\n }\n\n const length = end - start\n const pad = length % 3\n const safeEnd = start + length - pad\n const codes = []\n for (let off = start; off < safeEnd; off += 3) {\n const num = (buffer[off] << 16) | ((buffer[off + 1] << 8)) | buffer[off + 2]\n codes.push(\n byNum[num >> 18 & 0x3F],\n byNum[num >> 12 & 0x3F],\n byNum[num >> 6 & 0x3F],\n byNum[num & 0x3F]\n )\n }\n\n if (pad === 2) {\n const num = (buffer[end - 2] << 8) + buffer[end - 1]\n codes.push(\n byNum[num >> 10],\n byNum[(num >> 4) & 0x3F],\n byNum[(num << 2) & 0x3F]\n )\n if (paddingMode === PREFERS_PADDING) {\n codes.push(padCode)\n }\n } else if (pad === 1) {\n const num = buffer[end - 1]\n codes.push(\n byNum[num >> 2],\n byNum[(num << 4) & 0x3F]\n )\n if (paddingMode === PREFERS_PADDING) {\n codes.push(padCode, padCode)\n }\n }\n\n codec.decode.bytes = length\n return String.fromCharCode.apply(String, codes)\n }\n }\n return codec\n}\n\nexport const base64 = make('base64', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', '=', PREFERS_PADDING)\n// https://datatracker.ietf.org/doc/html/rfc4648#section-5\nexport const base64URL = make('base64-url', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', '=', PREFERS_NO_PADDING)\n","let AbortError = typeof global !== 'undefined' ? global.AbortError : typeof window !== 'undefined' ? window.AbortError : null\nif (!AbortError) {\n AbortError = class AbortError extends Error {\n constructor (message = 'Request aborted.') {\n super(message)\n }\n }\n}\nAbortError.prototype.name = 'AbortError'\nAbortError.prototype.code = 'ABORT_ERR'\n\nconst URL = (typeof globalThis !== 'undefined' && globalThis.URL) || require('url').URL\n\nexport { AbortError, URL }\n\nexport class HTTPStatusError extends Error {\n constructor (uri, code, method) {\n super('status=' + code + ' while requesting ' + uri + ' [' + method + ']')\n this.uri = uri\n this.status = code\n this.method = method\n }\n\n toJSON () {\n return {\n code: this.code,\n uri: this.uri,\n status: this.status,\n method: this.method,\n endpoint: this.endpoint\n }\n }\n}\nHTTPStatusError.prototype.name = 'HTTPStatusError'\nHTTPStatusError.prototype.code = 'HTTP_STATUS'\n\nexport class ResponseError extends Error {\n constructor (message, cause) {\n super(message)\n this.cause = cause\n }\n\n toJSON () {\n return {\n message: this.message,\n endpoint: this.endpoint,\n code: this.code,\n cause: reduceError(this.cause)\n }\n }\n}\nResponseError.prototype.name = 'ResponseError'\nResponseError.prototype.code = 'RESPONSE_ERR'\n\nexport class TimeoutError extends Error {\n constructor (timeout) {\n super('Timeout (t=' + timeout + ').')\n this.timeout = timeout\n }\n\n toJSON () {\n return {\n code: this.code,\n endpoint: this.endpoint,\n timeout: this.timeout\n }\n }\n}\nTimeoutError.prototype.name = 'TimeoutError'\nTimeoutError.prototype.code = 'ETIMEOUT'\n\nconst v4Regex = /^((\\d{1,3}\\.){3,3}\\d{1,3})(:(\\d{2,5}))?$/\nconst v6Regex = /^((::)?(((\\d{1,3}\\.){3}(\\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\\d{2,5}))?$/i\n\nexport function reduceError (err) {\n if (typeof err === 'string') {\n return {\n message: err\n }\n }\n try {\n const json = JSON.stringify(err)\n if (json !== '{}') {\n return JSON.parse(json)\n }\n } catch (e) {}\n const error = {\n message: String(err.message || err)\n }\n if (err.code !== undefined) {\n error.code = String(err.code)\n }\n return error\n}\n\nconst baseParts = /^(([a-z0-9]+:)\\/\\/)?([^/[\\s:]+|\\[[^\\]]+\\])?(:([^/\\s]+))?(\\/[^\\s]*)?(.*)$/\nconst httpFlags = /\\[(post|get|((ipv4|ipv6|name)=([^\\]]+)))\\]/ig\nconst updFlags = /\\[(((pk|name)=([^\\]]+)))\\]/ig\n\nexport function parseEndpoint (endpoint) {\n const parts = baseParts.exec(endpoint)\n const protocol = parts[2] || 'https:'\n const host = parts[3]\n const port = parts[5]\n const path = parts[6]\n const rest = parts[7]\n if (protocol === 'https:' || protocol === 'http:') {\n const flags = parseFlags(rest, httpFlags)\n return {\n name: flags.name,\n protocol,\n ipv4: flags.ipv4,\n ipv6: flags.ipv6,\n host,\n port,\n path,\n method: flags.post ? 'POST' : 'GET'\n }\n }\n if (protocol === 'udp:' || protocol === 'udp4:' || protocol === 'udp6:') {\n const flags = parseFlags(rest, updFlags)\n const v6Parts = /^\\[(.*)\\]$/.exec(host)\n if (v6Parts && protocol === 'udp4:') {\n throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${endpoint})`)\n }\n if (!v6Parts && protocol === 'udp6:') {\n throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${endpoint})`)\n }\n if (v6Parts) {\n return new UDP6Endpoint({ protocol: 'udp6:', ipv6: v6Parts[1], port, pk: flags.pk, name: flags.name })\n }\n return new UDP4Endpoint({ protocol: 'udp4:', ipv4: host, port, pk: flags.pk, name: flags.name })\n }\n throw new InvalidProtocolError(protocol, endpoint)\n}\n\nfunction parseFlags (rest, regex) {\n regex.lastIndex = 0\n const result = {}\n while (true) {\n const match = regex.exec(rest)\n if (!match) break\n if (match[2]) {\n result[match[3].toLowerCase()] = match[4]\n } else {\n result[match[1].toLowerCase()] = true\n }\n }\n return result\n}\n\nexport class InvalidProtocolError extends Error {\n constructor (protocol, endpoint) {\n super(`Invalid Endpoint: unsupported protocol \"${protocol}\" for endpoint: ${endpoint}, supported protocols: ${supportedProtocols.join(', ')}`)\n this.protocol = protocol\n this.endpoint = endpoint\n }\n\n toJSON () {\n return {\n code: this.code,\n endpoint: this.endpoint,\n timeout: this.timeout\n }\n }\n}\nInvalidProtocolError.prototype.name = 'InvalidProtocolError'\nInvalidProtocolError.prototype.code = 'EPROTOCOL'\n\nexport const supportedProtocols = ['http:', 'https:', 'udp4:', 'udp6:']\n\nexport class BaseEndpoint {\n constructor (opts, isHTTP) {\n this.name = opts.name || null\n this.protocol = opts.protocol\n const port = typeof opts.port === 'string' ? opts.port = parseInt(opts.port, 10) : opts.port\n if (port === undefined || port === null) {\n this.port = isHTTP\n ? (this.protocol === 'https:' ? 443 : 80)\n : (opts.pk ? 443 : 53)\n } else if (typeof port !== 'number' && !isNaN(port)) {\n throw new Error(`Invalid Endpoint: port \"${opts.port}\" needs to be a number: ${JSON.stringify(opts)}`)\n } else {\n this.port = port\n }\n }\n\n toJSON () {\n return this.toString()\n }\n}\n\nexport class UDPEndpoint extends BaseEndpoint {\n constructor (opts) {\n super(opts, false)\n this.pk = opts.pk || null\n }\n\n toString () {\n const port = this.port !== (this.pk ? 443 : 53) ? `:${this.port}` : ''\n const pk = this.pk ? ` [pk=${this.pk}]` : ''\n const name = this.name ? ` [name=${this.name}]` : ''\n return `udp://${this.ipv4 || `[${this.ipv6}]`}${port}${pk}${name}`\n }\n}\n\nexport class UDP4Endpoint extends UDPEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'udp4:' }, opts))\n if (!opts.ipv4 || typeof opts.ipv4 !== 'string') {\n throw new Error(`Invalid Endpoint: .ipv4 \"${opts.ipv4}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.ipv4 = opts.ipv4\n }\n}\n\nexport class UDP6Endpoint extends UDPEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'udp6:' }, opts))\n if (!opts.ipv6 || typeof opts.ipv6 !== 'string') {\n throw new Error(`Invalid Endpoint: .ipv6 \"${opts.ipv6}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.ipv6 = opts.ipv6\n }\n}\n\nfunction safeHost (host) {\n return v6Regex.test(host) && !v4Regex.test(host) ? `[${host}]` : host\n}\n\nexport class HTTPEndpoint extends BaseEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'https:' }, opts), true)\n if (!opts.host) {\n if (opts.ipv4) {\n opts.host = opts.ipv4\n }\n if (opts.ipv6) {\n opts.host = `[${opts.ipv6}]`\n }\n }\n if (!opts.host || typeof opts.host !== 'string') {\n throw new Error(`Invalid Endpoint: host \"${opts.path}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.host = opts.host\n this.path = opts.path || '/dns-query'\n this.method = /^post$/i.test(opts.method) ? 'POST' : 'GET'\n this.ipv4 = opts.ipv4\n this.ipv6 = opts.ipv6\n if (!this.ipv6) {\n const v6Parts = v6Regex.exec(this.host)\n if (v6Parts) {\n this.ipv6 = v6Parts[1]\n }\n }\n if (!this.ipv4) {\n if (v4Regex.test(this.host)) {\n this.ipv4 = this.host\n }\n }\n const url = `${this.protocol}//${safeHost(this.host)}:${this.port}${this.path}`\n try {\n this.url = new URL(url)\n } catch (err) {\n throw new Error(err.message + ` [${url}]`)\n }\n }\n\n toString () {\n const protocol = this.protocol === 'https:' ? '' : 'http://'\n const port = this.port !== (this.protocol === 'https:' ? 443 : 80) ? `:${this.port}` : ''\n const method = this.method !== 'GET' ? ' [post]' : ''\n const path = this.path === '/dns-query' ? '' : this.path\n const name = this.name ? ` [name=${this.name}]` : ''\n const ipv4 = this.ipv4 && this.ipv4 !== this.host ? ` [ipv4=${this.ipv4}]` : ''\n const ipv6 = this.ipv6 && this.ipv6 !== this.host ? ` [ipv6=${this.ipv6}]` : ''\n return `${protocol}${safeHost(this.host)}${port}${path}${method}${ipv4}${ipv6}${name}`\n }\n}\n\nexport function toEndpoint (input) {\n let opts\n if (typeof input === 'string') {\n opts = parseEndpoint(input)\n } else {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new Error(`Can not convert ${input} to an endpoint`)\n } else if (input instanceof BaseEndpoint) {\n return input\n }\n opts = input\n }\n if (opts.protocol === null || opts.protocol === undefined) {\n opts.protocol = 'https:'\n }\n const protocol = opts.protocol\n if (protocol === 'udp4:') {\n return new UDP4Endpoint(opts)\n }\n if (protocol === 'udp6:') {\n return new UDP6Endpoint(opts)\n }\n if (protocol === 'https:' || protocol === 'http:') {\n return new HTTPEndpoint(opts)\n }\n throw new InvalidProtocolError(protocol, JSON.stringify(opts))\n}\n","/* global XMLHttpRequest, localStorage */\nimport * as utf8Codec from 'utf8-codec'\nimport { base64URL } from '@leichtgewicht/base64-codec'\nimport {\n AbortError,\n HTTPStatusError,\n TimeoutError,\n URL\n} from './common.mjs'\nconst contentType = 'application/dns-message'\n\nfunction noop () { }\n\nexport function queryDns () {\n throw new Error('Only \"doh\" endpoints are supported in the browser')\n}\n\nexport async function loadJSON (url, cache, timeout, abortSignal) {\n const cacheKey = cache ? cache.localStoragePrefix + cache.name : null\n if (cacheKey) {\n try {\n const cached = JSON.parse(localStorage.getItem(cacheKey))\n if (cached && cached.time > cache.maxTime) {\n return cached\n }\n } catch (err) {}\n }\n const { data } = await requestRaw(url, 'GET', null, timeout, abortSignal)\n const result = {\n time: Date.now(),\n data: JSON.parse(utf8Codec.decode(data))\n }\n if (cacheKey) {\n try {\n localStorage.setItem(cacheKey, JSON.stringify(result))\n } catch (err) {\n result.time = null\n }\n }\n return result\n}\n\nfunction requestRaw (url, method, data, timeout, abortSignal) {\n return new Promise((resolve, reject) => {\n const target = new URL(url)\n if (method === 'GET' && data) {\n target.search = '?dns=' + base64URL.decode(data)\n }\n const uri = target.toString()\n const xhr = new XMLHttpRequest()\n xhr.open(method, uri, true)\n xhr.setRequestHeader('Accept', contentType)\n if (method === 'POST') {\n xhr.setRequestHeader('Content-Type', contentType)\n }\n xhr.responseType = 'arraybuffer'\n xhr.timeout = timeout\n xhr.ontimeout = ontimeout\n xhr.onreadystatechange = onreadystatechange\n xhr.onerror = onerror\n xhr.onload = onload\n if (method === 'POST') {\n xhr.send(data)\n } else {\n xhr.send()\n }\n\n if (abortSignal) {\n abortSignal.addEventListener('abort', onabort)\n }\n\n function ontimeout () {\n finish(new TimeoutError(timeout))\n try {\n xhr.abort()\n } catch (e) { }\n }\n\n function onload () {\n if (xhr.status !== 200) {\n finish(new HTTPStatusError(uri, xhr.status, method))\n } else {\n let buf\n if (typeof xhr.response === 'string') {\n buf = utf8Codec.encode(xhr.response)\n } else if (xhr.response instanceof Uint8Array) {\n buf = xhr.response\n } else if (Array.isArray(xhr.response) || xhr.response instanceof ArrayBuffer) {\n buf = new Uint8Array(xhr.response)\n } else {\n throw new Error('Unprocessable response ' + xhr.response)\n }\n finish(null, buf)\n }\n }\n\n function onreadystatechange () {\n if (xhr.readyState > 1 && xhr.status !== 200 && xhr.status !== 0) {\n finish(new HTTPStatusError(uri, xhr.status, method))\n try {\n xhr.abort()\n } catch (e) { }\n }\n }\n\n let finish = function (error, data) {\n finish = noop\n if (abortSignal) {\n abortSignal.removeEventListener('abort', onabort)\n }\n if (error) {\n resolve({\n error,\n response: xhr\n })\n } else {\n resolve({\n data,\n response: xhr\n })\n }\n }\n\n function onerror () {\n finish(xhr.status === 200 ? new Error('Inexplicable XHR Error') : new HTTPStatusError(uri, xhr.status, method))\n }\n\n function onabort () {\n finish(new AbortError())\n try {\n xhr.abort()\n } catch (e) { }\n }\n })\n}\n\nexport function request (url, method, packet, timeout, abortSignal) {\n return requestRaw(url, method, packet, timeout, abortSignal)\n}\n\nexport function processResolvers (resolvers) {\n return resolvers.filter(resolver => resolver.cors || resolver.endpoint.cors)\n}\n","import * as packet from '@leichtgewicht/dns-packet'\nimport { toRcode } from '@leichtgewicht/dns-packet/rcodes.js'\nimport { decode } from 'utf8-codec'\nimport * as lib from './lib.mjs'\nimport { resolvers as backupResolvers } from './resolvers.mjs'\nimport {\n AbortError,\n ResponseError,\n URL,\n toEndpoint\n} from './common.mjs'\n\nexport {\n TimeoutError,\n HTTPStatusError,\n AbortError,\n ResponseError,\n BaseEndpoint,\n HTTPEndpoint,\n UDP4Endpoint,\n UDP6Endpoint,\n parseEndpoint,\n toEndpoint\n} from './common.mjs'\n\nexport const DNS_RCODE_ERROR = {\n 1: 'FormErr',\n 2: 'ServFail',\n 3: 'NXDomain',\n 4: 'NotImp',\n 5: 'Refused',\n 6: 'YXDomain',\n 7: 'YXRRSet',\n 8: 'NXRRSet',\n 9: 'NotAuth',\n 10: 'NotZone',\n 11: 'DSOTYPENI'\n}\n\nexport const DNS_RCODE_MESSAGE = {\n // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n 1: 'The name server was unable to interpret the query.',\n 2: 'The name server was unable to process this query due to a problem with the name server.',\n 3: 'Non-Existent Domain.',\n 4: 'The name server does not support the requested kind of query.',\n 5: 'The name server refuses to perform the specified operation for policy reasons.',\n 6: 'Name Exists when it should not.',\n 7: 'RR Set Exists when it should not.',\n 8: 'RR Set that should exist does not.',\n 9: 'Server Not Authoritative for zone / Not Authorized.',\n 10: 'Name not contained in zone.',\n 11: 'DSO-TYPE Not Implemented.'\n}\n\nexport class DNSRcodeError extends Error {\n constructor (rcode, question) {\n super(`${(DNS_RCODE_MESSAGE[rcode] || 'Undefined error.')} (rcode=${rcode}${DNS_RCODE_ERROR[rcode] ? `, error=${DNS_RCODE_ERROR[rcode]}` : ''}, question=${JSON.stringify(question)})`)\n this.rcode = rcode\n this.code = `DNS_RCODE_${rcode}`\n this.error = DNS_RCODE_ERROR[rcode]\n this.question = question\n }\n\n toJSON () {\n return {\n code: this.code,\n error: this.error,\n question: this.question,\n endpoint: this.endpoint\n }\n }\n}\n\nexport function validateResponse (data, question) {\n const rcode = toRcode(data.rcode)\n if (rcode !== 0) {\n const err = new DNSRcodeError(rcode, question)\n err.endpoint = data.endpoint\n throw err\n }\n return data\n}\n\nfunction processResolvers (res) {\n const time = (res.time === null || res.time === undefined) ? Date.now() : res.time\n const resolvers = lib.processResolvers(res.data.map(resolver => {\n resolver.endpoint = toEndpoint(Object.assign({ name: resolver.name }, resolver.endpoint))\n return resolver\n }))\n const endpoints = resolvers.map(resolver => resolver.endpoint)\n return {\n data: {\n resolvers,\n resolverByName: resolvers.reduce((byName, resolver) => {\n byName[resolver.name] = resolver\n return byName\n }, {}),\n endpoints,\n endpointByName: endpoints.reduce((byName, endpoint) => {\n byName[endpoint.name] = endpoint\n return byName\n }, {})\n },\n time\n }\n}\n\nexport const backup = processResolvers(backupResolvers)\n\nfunction toMultiQuery (singleQuery) {\n const query = Object.assign({\n type: 'query'\n }, singleQuery)\n delete query.question\n query.questions = []\n if (singleQuery.question) {\n query.questions.push(singleQuery.question)\n }\n return query\n}\n\nfunction queryOne (endpoint, query, timeout, abortSignal) {\n if (abortSignal && abortSignal.aborted) {\n return Promise.reject(new AbortError())\n }\n if (endpoint.protocol === 'udp4:' || endpoint.protocol === 'udp6:') {\n return lib.queryDns(endpoint, query, timeout, abortSignal)\n }\n return queryDoh(endpoint, query, timeout, abortSignal)\n}\n\nfunction queryDoh (endpoint, query, timeout, abortSignal) {\n return lib.request(\n endpoint.url,\n endpoint.method,\n packet.encode(Object.assign({\n flags: packet.RECURSION_DESIRED\n }, query)),\n timeout,\n abortSignal\n ).then(\n function (res) {\n const data = res.data\n const response = res.response\n let error = res.error\n if (error === undefined) {\n if (data.length === 0) {\n error = new ResponseError('Empty.')\n } else {\n try {\n const decoded = packet.decode(data)\n decoded.response = response\n return decoded\n } catch (err) {\n error = new ResponseError('Invalid packet (cause=' + err.message + ')', err)\n }\n }\n }\n throw Object.assign(error, { response })\n }\n )\n}\n\nconst UPDATE_URL = new URL('https://martinheidegger.github.io/dns-query/resolvers.json')\n\nfunction concatUint8 (arrs) {\n const res = new Uint8Array(\n arrs.reduce((len, arr) => len + arr.length, 0)\n )\n let pos = 0\n for (const arr of arrs) {\n res.set(arr, pos)\n pos += arr.length\n }\n return res\n}\n\nexport function combineTXT (inputs) {\n return decode(concatUint8(inputs))\n}\n\nfunction isNameString (entry) {\n return /^@/.test(entry)\n}\n\nexport class Wellknown {\n constructor (opts) {\n this.opts = Object.assign({\n timeout: 5000,\n update: true,\n updateURL: UPDATE_URL,\n persist: false,\n localStoragePrefix: 'dnsquery_',\n maxAge: 300000 // 5 minutes\n }, opts)\n this._dataP = null\n }\n\n _data (force, outdated) {\n if (!force && this._dataP !== null) {\n return this._dataP.then(res => {\n if (res.time < Date.now() - this.opts.maxAge) {\n return this._data(true, res)\n }\n return res\n })\n }\n this._dataP = (!this.opts.update\n ? Promise.resolve(backup)\n : lib.loadJSON(\n this.opts.updateURL,\n this.opts.persist\n ? {\n name: 'resolvers.json',\n localStoragePrefix: this.opts.localStoragePrefix,\n maxTime: Date.now() - this.opts.maxAge\n }\n : null,\n this.opts.timeout\n )\n .then(res => processResolvers({\n data: res.data.resolvers,\n time: res.time\n }))\n .catch(() => outdated || backup)\n )\n return this._dataP\n }\n\n data () {\n return this._data(false).then(data => data.data)\n }\n\n endpoints (input) {\n if (input === null || input === undefined) {\n return this.data().then(data => data.endpoints)\n }\n if (input === 'doh') {\n input = filterDoh\n }\n if (input === 'dns') {\n input = filterDns\n }\n if (typeof input === 'function') {\n return this.data().then(data => data.endpoints.filter(input))\n }\n if (typeof input === 'string' || typeof input[Symbol.iterator] !== 'function') {\n return Promise.reject(new Error(`Endpoints (${input}) needs to be iterable (array).`))\n }\n input = Array.from(input).filter(Boolean)\n if (input.findIndex(isNameString) === -1) {\n try {\n return Promise.resolve(input.map(toEndpoint))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n return this.data().then(data =>\n input.map(entry => {\n if (isNameString(entry)) {\n const found = data.endpointByName[entry.substring(1)]\n if (!found) {\n throw new Error(`Endpoint ${entry} is not known.`)\n }\n return found\n }\n return toEndpoint(entry)\n })\n )\n }\n}\n\nexport const wellknown = new Wellknown()\n\nfunction isPromise (input) {\n if (input === null) {\n return false\n }\n if (typeof input !== 'object') {\n return false\n }\n return typeof input.then === 'function'\n}\n\nfunction toPromise (input) {\n return isPromise(input) ? input : Promise.resolve(input)\n}\n\nexport function query (q, opts) {\n opts = Object.assign({\n retries: 5,\n timeout: 30000 // 30 seconds\n }, opts)\n if (!q.question) return Promise.reject(new Error('To request data you need to specify a .question!'))\n return toPromise(opts.endpoints)\n .then(endpoints => {\n if (!Array.isArray(endpoints) || endpoints.length === 0) {\n throw new Error('No endpoints defined to lookup dns records.')\n }\n return queryN(endpoints.map(toEndpoint), toMultiQuery(q), opts)\n })\n .then(data => {\n data.question = data.questions[0]\n delete data.questions\n return data\n })\n}\n\nexport function lookupTxt (domain, opts) {\n const q = Object.assign({\n question: {\n type: 'TXT',\n name: domain\n }\n }, opts.query)\n return query(q, opts)\n .then(data => {\n validateResponse(data, q)\n return {\n entries: (data.answers || [])\n .filter(answer => answer.type === 'TXT' && answer.data)\n .map(answer => {\n return ({\n data: combineTXT(answer.data),\n ttl: answer.ttl\n })\n })\n .sort((a, b) => {\n if (a.data > b.data) return 1\n if (a.data < b.data) return -1\n return 0\n }),\n endpoint: data.endpoint\n }\n })\n}\n\nfunction queryN (endpoints, q, opts) {\n const endpoint = endpoints.length === 1\n ? endpoints[0]\n : endpoints[Math.floor(Math.random() * endpoints.length) % endpoints.length]\n return queryOne(endpoint, q, opts.timeout, opts.signal)\n .then(\n data => {\n // Add the endpoint to give a chance to identify which endpoint returned the result\n data.endpoint = endpoint.toString()\n return data\n },\n err => {\n if (err.name === 'AbortError' || opts.retries === 0) {\n err.endpoint = endpoint.toString()\n throw err\n }\n if (opts.retries > 0) {\n opts.retries -= 1\n }\n return queryN(endpoints, q, opts)\n }\n )\n}\n\nfunction filterDoh (endpoint) {\n return endpoint.protocol === 'https:' || endpoint.protocol === 'http:'\n}\n\nfunction filterDns (endpoint) {\n return endpoint.protocol === 'udp4:' || endpoint.protocol === 'udp6:'\n}\n","export const resolvers = {\n data: [\n {\n name: 'adfree.usableprivacy.net',\n endpoint: {\n protocol: 'https:',\n host: 'adfree.usableprivacy.net'\n },\n description: 'Public updns DoH service with advertising, tracker and malware filters.\\nHosted in Europe by @usableprivacy, details see: https://docs.usableprivacy.com',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n },\n filter: true\n },\n {\n name: 'adguard-dns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.adguard.com',\n ipv4: '94.140.15.15'\n },\n description: 'Remove ads and protect your computer from malware (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n },\n filter: true\n },\n {\n name: 'adguard-dns-family-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-family.adguard.com',\n ipv4: '94.140.15.16'\n },\n description: 'Adguard DNS with safesearch and adult content blocking (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n },\n filter: true\n },\n {\n name: 'adguard-dns-unfiltered-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-unfiltered.adguard.com',\n ipv4: '94.140.14.140'\n },\n description: 'AdGuard public DNS servers without filters (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n }\n },\n {\n name: 'ahadns-doh-chi',\n endpoint: {\n protocol: 'https:',\n host: 'doh.chi.ahadns.net',\n cors: true\n },\n description: 'A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Chicago, USA. By https://ahadns.com/\\nServer statistics can be seen at: https://statistics.ahadns.com/?server=chi',\n country: 'United States',\n location: {\n lat: 41.8483,\n long: -87.6517\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-in',\n endpoint: {\n protocol: 'https:',\n host: 'doh.in.ahadns.net',\n cors: true\n },\n description: 'A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Mumbai, India. By https://ahadns.com/\\nServer statistics can be seen at: https://statistics.ahadns.com/?server=in',\n country: 'India',\n location: {\n lat: 19.0748,\n long: 72.8856\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-la',\n endpoint: {\n protocol: 'https:',\n host: 'doh.la.ahadns.net',\n cors: true\n },\n description: 'A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Los Angeles, USA. By https://ahadns.com/\\nServer statistics can be seen at: https://statistics.ahadns.com/?server=la',\n country: 'United States',\n location: {\n lat: 34.0549,\n long: -118.2578\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'doh.nl.ahadns.net',\n cors: true\n },\n description: 'A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Amsterdam, Netherlands. By https://ahadns.com/\\nServer statistics can be seen at: https://statistics.ahadns.com/?server=nl',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-ny',\n endpoint: {\n protocol: 'https:',\n host: 'doh.ny.ahadns.net',\n cors: true\n },\n description: 'A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in New York. By https://ahadns.com/\\nServer statistics can be seen at: https://statistics.ahadns.com/?server=ny',\n country: 'United States',\n location: {\n lat: 40.7308,\n long: -73.9975\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-pl',\n endpoint: {\n protocol: 'https:',\n host: 'doh.pl.ahadns.net',\n cors: true\n },\n description: 'A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Poland. By https://ahadns.com/\\nServer statistics can be seen at: https://statistics.ahadns.com/?server=pl',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'alidns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.alidns.com',\n ipv4: '223.5.5.5',\n cors: true\n },\n description: 'A public DNS resolver that supports DoH/DoT in mainland China, provided by Alibaba-Cloud.\\nWarning: GFW filtering rules are applied by that resolver.\\nHomepage: https://alidns.com/',\n country: 'China',\n location: {\n lat: 34.7725,\n long: 113.7266\n },\n filter: true,\n log: true,\n cors: true\n },\n {\n name: 'ams-ads-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'dnsnl-noads.alekberg.net'\n },\n description: 'Resolver in Amsterdam. DoH protocol. Non-logging. Blocks ads, malware and trackers. DNSSEC enabled.',\n country: 'Romania',\n location: {\n lat: 45.9968,\n long: 24.997\n },\n filter: true\n },\n {\n name: 'ams-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'dnsnl.alekberg.net'\n },\n description: 'Resolver in Amsterdam. DoH protocol. Non-logging, non-filtering, DNSSEC.',\n country: 'Romania',\n location: {\n lat: 45.9968,\n long: 24.997\n }\n },\n {\n name: 'att',\n endpoint: {\n protocol: 'https:',\n host: 'dohtrial.att.net'\n },\n description: 'AT&T test DoH server.',\n log: true\n },\n {\n name: 'bcn-ads-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dnses-noads.alekberg.net'\n },\n description: 'Resolver in Spain. DoH protocol. Non-logging, remove ads and malware, DNSSEC.',\n country: 'Spain',\n location: {\n lat: 41.3891,\n long: 2.1611\n },\n filter: true\n },\n {\n name: 'bcn-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dnses.alekberg.net'\n },\n description: 'Resolver in Spain. DoH protocol. Non-logging, non-filtering, DNSSEC.',\n country: 'Spain',\n location: {\n lat: 41.3891,\n long: 2.1611\n }\n },\n {\n name: 'brahma-world',\n endpoint: {\n protocol: 'https:',\n host: 'dns.brahma.world'\n },\n description: 'DNS-over-HTTPS server. Non Logging, filters ads, trackers and malware. DNSSEC ready, QNAME Minimization, No EDNS Client-Subnet.\\nHosted in Stockholm, Sweden. (https://dns.brahma.world)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'cisco-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.opendns.com',\n ipv4: '146.112.41.2'\n },\n description: 'Remove your DNS blind spot (DoH protocol)\\nWarning: modifies your queries to include a copy of your network\\naddress when forwarding them to a selection of companies and organizations.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true,\n log: true\n },\n {\n name: 'cloudflare',\n endpoint: {\n protocol: 'https:',\n host: 'dns.cloudflare.com',\n ipv4: '1.0.0.1',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) - aka 1.1.1.1 / 1.0.0.1',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n cors: true\n },\n {\n name: 'cloudflare-family',\n endpoint: {\n protocol: 'https:',\n host: 'family.cloudflare-dns.com',\n ipv4: '1.0.0.3',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) with malware protection and parental control - aka 1.1.1.3 / 1.0.0.3',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n filter: true,\n cors: true\n },\n {\n name: 'cloudflare-ipv6',\n endpoint: {\n protocol: 'https:',\n host: '1dot1dot1dot1.cloudflare-dns.com',\n cors: true\n },\n description: 'Cloudflare DNS over IPv6 (anycast)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'cloudflare-security',\n endpoint: {\n protocol: 'https:',\n host: 'security.cloudflare-dns.com',\n ipv4: '1.0.0.2',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) with malware blocking - aka 1.1.1.2 / 1.0.0.2',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n filter: true,\n cors: true\n },\n {\n name: 'controld-block-malware',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p1'\n },\n description: 'ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\\nThis DNS blocks Malware domains.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-block-malware-ad',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p2'\n },\n description: 'ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\\nThis DNS blocks Malware, Ads & Tracking domains.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-block-malware-ad-social',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p3'\n },\n description: 'ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\\nThis DNS blocks Malware, Ads & Tracking and Social Networks domains.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-family-friendly',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/family'\n },\n description: 'ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\\nThis DNS blocks Malware, Ads & Tracking, Adult Content and Drugs domains.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-uncensored',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/uncensored'\n },\n description: 'ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\\nThis DNS unblocks censored domains from various countries.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n }\n },\n {\n name: 'controld-unfiltered',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p0'\n },\n description: 'ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\\nThis is a Unfiltered DNS, no DNS record blocking or manipulation here, if you want to block Malware, Ads & Tracking or Social Network domains, use the other ControlD DNS configs.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n }\n },\n {\n name: 'dns.digitale-gesellschaft.ch',\n endpoint: {\n protocol: 'https:',\n host: 'dns.digitale-gesellschaft.ch'\n },\n description: 'Public DoH resolver operated by the Digital Society (https://www.digitale-gesellschaft.ch).\\nHosted in Zurich, Switzerland.\\nNon-logging, non-filtering, supports DNSSEC.',\n country: 'Switzerland',\n location: {\n lat: 47.1449,\n long: 8.1551\n }\n },\n {\n name: 'dns.ryan-palmer',\n endpoint: {\n protocol: 'https:',\n host: 'dns1.ryan-palmer.com'\n },\n description: 'Non-logging, non-filtering, DNSSEC DoH Server. Hosted in the UK.',\n country: 'United Kingdom',\n location: {\n lat: 51.5164,\n long: -0.093\n }\n },\n {\n name: 'dns.sb',\n endpoint: {\n protocol: 'https:',\n host: 'doh.sb',\n ipv4: '185.222.222.222',\n cors: true\n },\n description: 'DNSSEC-enabled DoH server by https://xtom.com/\\nhttps://dns.sb/doh/',\n country: 'Unknown',\n location: {\n lat: 47,\n long: 8\n },\n cors: true\n },\n {\n name: 'dns.therifleman.name',\n endpoint: {\n protocol: 'https:',\n host: 'dns.therifleman.name'\n },\n description: 'DNS-over-HTTPS DNS forwarder from Mumbai, India. Blocks web and Android trackers and ads.\\nIP addresses are not logged, but queries are logged for 24 hours for debugging.\\nReport issues, send suggestions @ joker349 at protonmail.com.\\nAlso supports DoT (for android) @ dns.therifleman.name and plain DNS @ 172.104.206.174',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'dnsforfamily-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-doh.dnsforfamily.com'\n },\n description: '(DoH Protocol) (Now supports DNSSEC). Block adult websites, gambling websites, malwares and advertisements.\\nIt also enforces safe search in: Google, YouTube, Bing, DuckDuckGo and Yandex.\\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\\nProvided by: https://dnsforfamily.com',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true\n },\n {\n name: 'dnsforfamily-doh-no-safe-search',\n endpoint: {\n protocol: 'https:',\n host: 'dns-doh-no-safe-search.dnsforfamily.com'\n },\n description: '(DoH Protocol) (Now supports DNSSEC) Block adult websites, gambling websites, malwares and advertisements.\\nUnlike other dnsforfamily servers, this one does not enforces safe search. So Google, YouTube, Bing, DuckDuckGo and Yandex are completely accessible without any restriction.\\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\\nWarning: This server is incompatible with anonymization.\\nProvided by: https://dnsforfamily.com',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true\n },\n {\n name: 'dnsforge.de',\n endpoint: {\n protocol: 'https:',\n host: 'dnsforge.de',\n cors: true\n },\n description: 'Public DoH resolver running with Pihole for Adblocking (https://dnsforge.de).\\nNon-logging, AD-filtering, supports DNSSEC. Hosted in Germany.',\n country: 'Germany',\n location: {\n lat: 52.2998,\n long: 9.447\n },\n filter: true,\n cors: true\n },\n {\n name: 'dnshome-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.dnshome.de'\n },\n description: 'https://www.dnshome.de/ public resolver in Germany'\n },\n {\n name: 'dnspod-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.pub',\n cors: true\n },\n description: 'A public DNS resolver in mainland China provided by DNSPod (Tencent Cloud).\\nhttps://www.dnspod.cn/Products/Public.DNS?lang=en',\n filter: true,\n log: true,\n cors: true\n },\n {\n name: 'dnswarden-asia-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/adblock'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'dnswarden-asia-adultfilter-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/adultfilter'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'dnswarden-asia-uncensor-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/uncensored'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n }\n },\n {\n name: 'dnswarden-eu-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.eu.dnswarden.com'\n },\n description: 'Hosted in Germany. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Germany',\n location: {\n lat: 50.1103,\n long: 8.7147\n },\n filter: true\n },\n {\n name: 'dnswarden-us-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.us.dnswarden.com'\n },\n description: 'Hosted in USA (Dallas) . For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'United States',\n location: {\n lat: 32.7889,\n long: -96.8021\n },\n filter: true\n },\n {\n name: 'doh-ch-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-ch.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Switzerland. By https://blahdns.com/',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-adult',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/adult-filter/',\n cors: true\n },\n description: 'Blocks access to all adult, pornographic and explicit sites. It does\\nnot block proxy or VPNs, nor mixed-content sites. Sites like Reddit\\nare allowed. Google and Bing are set to the Safe Mode.\\nBy https://cleanbrowsing.org/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-family',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/family-filter/',\n cors: true\n },\n description: 'Blocks access to all adult, pornographic and explicit sites. It also\\nblocks proxy and VPN domains that are used to bypass the filters.\\nMixed content sites (like Reddit) are also blocked. Google, Bing and\\nYoutube are set to the Safe Mode.\\nBy https://cleanbrowsing.org/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-security',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/security-filter/',\n cors: true\n },\n description: 'Block access to phishing, malware and malicious domains. It does not block adult content.\\nBy https://cleanbrowsing.org/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-crypto-sx',\n endpoint: {\n protocol: 'https:',\n host: 'doh.crypto.sx',\n cors: true\n },\n description: 'DNS-over-HTTPS server. Anycast, no logs, no censorship, DNSSEC.\\nBackend hosted by Scaleway, globally cached via Cloudflare.\\nMaintained by Frank Denis.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'doh-crypto-sx-ipv6',\n endpoint: {\n protocol: 'https:',\n host: 'doh-ipv6.crypto.sx',\n cors: true\n },\n description: 'DNS-over-HTTPS server accessible over IPv6. Anycast, no logs, no censorship, DNSSEC.\\nBackend hosted by Scaleway, globally cached via Cloudflare.\\nMaintained by Frank Denis.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'doh-de-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-de.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Germany. By https://blahdns.com/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-fi-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-fi.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Finland. By https://blahdns.com/',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-ibksturm',\n endpoint: {\n protocol: 'https:',\n host: 'ibksturm.synology.me'\n },\n description: 'DoH & DoT Server, No Logging, No Filters, DNSSEC\\nRunning privately by ibksturm in Thurgau, Switzerland'\n },\n {\n name: 'doh-jp-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-jp.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Japan. By https://blahdns.com/',\n country: 'Japan',\n location: {\n lat: 35.6882,\n long: 139.7532\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh.ffmuc.net',\n endpoint: {\n protocol: 'https:',\n host: 'doh.ffmuc.net'\n },\n description: 'An open (non-logging, non-filtering, non-censoring) DoH resolver operated by Freifunk Munich with nodes in DE.\\nhttps://ffmuc.net/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n }\n },\n {\n name: 'doh.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiarap.org'\n },\n description: 'Non-Logging DNS-over-HTTPS server, cached via Cloudflare.\\nFilters out ads, trackers and malware, NO ECS, supports DNSSEC.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'google',\n endpoint: {\n protocol: 'https:',\n host: 'dns.google',\n ipv4: '8.8.8.8',\n cors: true\n },\n description: 'Google DNS (anycast)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n log: true,\n cors: true\n },\n {\n name: 'hdns',\n endpoint: {\n protocol: 'https:',\n host: 'query.hdns.io',\n cors: true\n },\n description: 'HDNS is a public DNS resolver that supports Handshake domains.\\nhttps://www.hdns.io',\n country: 'United States',\n location: {\n lat: 37.7771,\n long: -122.406\n },\n cors: true\n },\n {\n name: 'he',\n endpoint: {\n protocol: 'https:',\n host: 'ordns.he.net'\n },\n description: 'Hurricane Electric DoH server (anycast)\\nUnknown logging policy.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n log: true\n },\n {\n name: 'id-gmail-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiar.app'\n },\n description: 'Non-Logging DNS-over-HTTPS server located in Singapore.\\nFilters out ads, trackers and malware, supports DNSSEC, provided by id-gmail.',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'iij',\n endpoint: {\n protocol: 'https:',\n host: 'public.dns.iij.jp'\n },\n description: 'DoH server operated by Internet Initiative Japan in Tokyo.\\nhttps://www.iij.ad.jp/',\n country: 'Japan',\n location: {\n lat: 35.69,\n long: 139.69\n },\n log: true\n },\n {\n name: 'iqdns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'a.passcloud.xyz'\n },\n description: 'Non-logging DoH service runned by V2EX.com user johnsonwil.\\nReturns \"no such domain\" for anti-Chinese government websites. Supports DNSSEC.\\nFor more information: https://www.v2ex.com/t/785666',\n filter: true\n },\n {\n name: 'jp.tiar.app-doh',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiar.app'\n },\n description: 'Non-Logging, Non-Filtering DNS-over-HTTPS server in Japan.\\nNo ECS, Support DNSSEC',\n country: 'Japan',\n location: {\n lat: 35.6882,\n long: 139.7532\n }\n },\n {\n name: 'jp.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiarap.org'\n },\n description: 'DNS-over-HTTPS Server. Non-Logging, Non-Filtering, No ECS, Support DNSSEC.\\nCached via Cloudflare.'\n },\n {\n name: 'libredns',\n endpoint: {\n protocol: 'https:',\n host: 'doh.libredns.gr'\n },\n description: 'DoH server in Germany. No logging, but no DNS padding and no DNSSEC support.\\nhttps://libredns.gr/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n }\n },\n {\n name: 'nextdns',\n endpoint: {\n protocol: 'https:',\n host: 'anycsast.dns.nextdns.io'\n },\n description: 'NextDNS is a cloud-based private DNS service that gives you full control\\nover what is allowed and what is blocked on the Internet.\\nDNSSEC, Anycast, Non-logging, NoFilters\\nhttps://www.nextdns.io/',\n country: 'Netherlands',\n location: {\n lat: 52.3891,\n long: 4.6563\n }\n },\n {\n name: 'nextdns-ultralow',\n endpoint: {\n protocol: 'https:',\n host: 'dns.nextdns.io',\n path: '/dnscrypt-proxy'\n },\n description: 'NextDNS is a cloud-based private DNS service that gives you full control\\nover what is allowed and what is blocked on the Internet.\\nhttps://www.nextdns.io/\\nTo select the server location, the \"-ultralow\" variant relies on bootstrap servers\\ninstead of anycast.'\n },\n {\n name: 'njalla-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.njal.la',\n cors: true\n },\n description: 'Non-logging DoH server in Sweden operated by Njalla.\\nhttps://dns.njal.la/',\n country: 'Sweden',\n location: {\n lat: 59.3247,\n long: 18.056\n },\n cors: true\n },\n {\n name: 'odoh-cloudflare',\n endpoint: {\n protocol: 'https:',\n host: 'odoh.cloudflare-dns.com',\n cors: true\n },\n description: 'Cloudflare ODoH server.\\nhttps://cloudflare.com',\n cors: true\n },\n {\n name: 'odoh-crypto-sx',\n endpoint: {\n protocol: 'https:',\n host: 'odoh.crypto.sx',\n cors: true\n },\n description: 'ODoH target server. Anycast, no logs.\\nBackend hosted by Scaleway. Maintained by Frank Denis.',\n cors: true\n },\n {\n name: 'odoh-id-gmail',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiar.app',\n path: '/odoh'\n },\n description: 'ODoH target server. Based in Singapore, no logs.\\nFilter ads, trackers and malware.',\n filter: true\n },\n {\n name: 'odoh-jp.tiar.app',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiar.app',\n path: '/odoh'\n },\n description: 'ODoH target server. no logs.'\n },\n {\n name: 'odoh-jp.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiarap.org',\n path: '/odoh'\n },\n description: 'ODoH target server via Cloudflare, no logs.'\n },\n {\n name: 'odoh-resolver4.dns.openinternet.io',\n endpoint: {\n protocol: 'https:',\n host: 'resolver4.dns.openinternet.io'\n },\n description: \"ODoH target server. no logs, no filter, DNSSEC.\\nRunning on dedicated hardware colocated at Sonic.net in Santa Rosa, CA in the United States.\\nUses Sonic's recusrive DNS servers as upstream resolvers (but is not affiliated with Sonic\\nin any way). Provided by https://openinternet.io\"\n },\n {\n name: 'odoh-tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiarap.org',\n path: '/odoh'\n },\n description: 'ODoH target server via Cloudflare, no logs.\\nFilter ads, trackers and malware.',\n filter: true\n },\n {\n name: 'publicarray-au2-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh-2.seby.io',\n cors: true\n },\n description: 'DNSSEC • OpenNIC • Non-logging • Uncensored - hosted on ovh.com.au\\nMaintained by publicarray - https://dns.seby.io',\n country: 'Australia',\n location: {\n lat: -33.8591,\n long: 151.2002\n },\n cors: true\n },\n {\n name: 'puredns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'puredns.org',\n ipv4: '146.190.6.13',\n cors: true\n },\n description: 'Public uncensored DNS resolver in Singapore - https://puredns.org\\n** Only available in Indonesia and Singapore **',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'quad101',\n endpoint: {\n protocol: 'https:',\n host: 'dns.twnic.tw',\n cors: true\n },\n description: 'DNSSEC-aware public resolver by the Taiwan Network Information Center (TWNIC)\\nhttps://101.101.101.101/index_en.html',\n cors: true\n },\n {\n name: 'quad9-doh-ip4-port443-filter-ecs-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns11.quad9.net',\n ipv4: '149.112.112.11'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter/ecs 9.9.9.11 - 149.112.112.11',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'quad9-doh-ip4-port443-filter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns.quad9.net',\n ipv4: '149.112.112.112'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter 9.9.9.9 - 149.112.112.9 - 149.112.112.112',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'quad9-doh-ip4-port443-nofilter-ecs-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns12.quad9.net',\n ipv4: '9.9.9.12'\n },\n description: 'Quad9 (anycast) no-dnssec/no-log/no-filter/ecs 9.9.9.12 - 149.112.112.12',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n }\n },\n {\n name: 'quad9-doh-ip4-port443-nofilter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns10.quad9.net',\n ipv4: '149.112.112.10'\n },\n description: 'Quad9 (anycast) no-dnssec/no-log/no-filter 9.9.9.10 - 149.112.112.10',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n }\n },\n {\n name: 'quad9-doh-ip6-port5053-filter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns9.quad9.net'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter 2620:fe::fe - 2620:fe::9 - 2620:fe::fe:9',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'safesurfer-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.safesurfer.io'\n },\n description: 'Family safety focused blocklist for over 2 million adult sites, as well as phishing and malware and more.\\nFree to use, paid for customizing blocking for more categories+sites and viewing usage at my.safesurfer.io. Logs taken for viewing\\nusage, data never sold - https://safesurfer.io',\n filter: true,\n log: true\n },\n {\n name: 'sth-ads-doh-se',\n endpoint: {\n protocol: 'https:',\n host: 'dnsse-noads.alekberg.net'\n },\n description: 'Resolver in Stockholm, Sweden. DoH server. Non-logging, remove ads and malware, DNSSEC.',\n country: 'Bulgaria',\n location: {\n lat: 42.696,\n long: 23.332\n },\n filter: true\n },\n {\n name: 'sth-doh-se',\n endpoint: {\n protocol: 'https:',\n host: 'dnsse.alekberg.net'\n },\n description: 'Resolver in Stockholm, Sweden. DoH server. Non-logging, non-filtering, DNSSEC.',\n country: 'Bulgaria',\n location: {\n lat: 42.696,\n long: 23.332\n }\n },\n {\n name: 'switch',\n endpoint: {\n protocol: 'https:',\n host: 'dns.switch.ch'\n },\n description: 'Public DoH service provided by SWITCH in Switzerland\\nhttps://www.switch.ch\\nProvides protection against malware, but does not block ads.',\n filter: true\n },\n {\n name: 'uncensoreddns-dk-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'unicast.uncensoreddns.org'\n },\n description: 'Also known as censurfridns.\\nDoH, no logs, no filter, DNSSEC, unicast hosted in Denmark - https://blog.uncensoreddns.org',\n country: 'Denmark',\n location: {\n lat: 55.7123,\n long: 12.0564\n }\n },\n {\n name: 'uncensoreddns-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'anycast.uncensoreddns.org'\n },\n description: 'Also known as censurfridns.\\nDoH, no logs, no filter, DNSSEC, anycast - https://blog.uncensoreddns.org',\n country: 'Denmark',\n location: {\n lat: 55.7123,\n long: 12.0564\n }\n },\n {\n name: 'v.dnscrypt.uk-doh-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'v.dnscrypt.uk'\n },\n description: 'DoH, no logs, uncensored, DNSSEC. Hosted in London UK on Digital Ocean\\nhttps://www.dnscrypt.uk',\n country: 'United Kingdom',\n location: {\n lat: 51.4964,\n long: -0.1224\n }\n }\n ],\n time: 1654187067783\n}\n","import type { DnsClient } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport { bytesToUtf8 } from \"@waku/utils/bytes\";\nimport { Endpoint, query, wellknown } from \"dns-query\";\n\nconst log = new Logger(\"dns-over-https\");\n\nexport class DnsOverHttps implements DnsClient {\n /**\n * Create new Dns-Over-Http DNS client.\n *\n * @param endpoints The endpoints for Dns-Over-Https queries;\n * Defaults to using dns-query's API..\n * @param retries Retries if a given endpoint fails.\n *\n * @throws {code: string} If DNS query fails.\n */\n public static async create(\n endpoints?: Endpoint[],\n retries?: number\n ): Promise {\n const _endpoints = endpoints ?? (await wellknown.endpoints(\"doh\"));\n\n return new DnsOverHttps(_endpoints, retries);\n }\n\n private constructor(\n private endpoints: Endpoint[],\n private retries: number = 3\n ) {}\n\n /**\n * Resolves a TXT record\n *\n * @param domain The domain name\n *\n * @throws if the query fails\n */\n async resolveTXT(domain: string): Promise {\n let answers;\n try {\n const res = await query(\n {\n question: { type: \"TXT\", name: domain }\n },\n {\n endpoints: this.endpoints,\n retries: this.retries\n }\n );\n answers = res.answers;\n } catch (error) {\n log.error(\"query failed: \", error);\n throw new Error(\"DNS query failed\");\n }\n\n if (!answers) throw new Error(`Could not resolve ${domain}`);\n\n const data = answers.map((a) => a.data) as\n | Array\n | Array>;\n\n const result: string[] = [];\n\n data.forEach((d) => {\n if (typeof d === \"string\") {\n result.push(d);\n } else if (Array.isArray(d)) {\n d.forEach((sd) => {\n if (typeof sd === \"string\") {\n result.push(sd);\n } else {\n result.push(bytesToUtf8(sd));\n }\n });\n } else {\n result.push(bytesToUtf8(d));\n }\n });\n\n return result;\n }\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0) as number] = i; return p }, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0) as number]\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import { coerce } from '../bytes.js'\nimport type { ArrayBufferView, ByteView } from './interface.js'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView {\n return coerce(node)\n}\n\nexport function decode (data: ByteView | ArrayBufferView): Uint8Array {\n return coerce(data)\n}\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID (input: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create (version: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 (code: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode (bytes: API.ByteView>): CID {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst (bytes: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes (initialBytes: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n","import { ENR } from \"@waku/enr\";\nimport { keccak256, verifySignature } from \"@waku/enr\";\nimport { utf8ToBytes } from \"@waku/utils/bytes\";\nimport base32 from \"hi-base32\";\nimport { fromString } from \"uint8arrays/from-string\";\n\nexport type ENRRootValues = {\n eRoot: string;\n lRoot: string;\n seq: number;\n signature: string;\n};\n\nexport type ENRTreeValues = {\n publicKey: string;\n domain: string;\n};\n\nexport class ENRTree {\n public static readonly RECORD_PREFIX = ENR.RECORD_PREFIX;\n public static readonly TREE_PREFIX = \"enrtree:\";\n public static readonly BRANCH_PREFIX = \"enrtree-branch:\";\n public static readonly ROOT_PREFIX = \"enrtree-root:\";\n\n /**\n * Extracts the branch subdomain referenced by a DNS tree root string after verifying\n * the root record signature with its base32 compressed public key.\n */\n static parseAndVerifyRoot(root: string, publicKey: string): string {\n if (!root.startsWith(this.ROOT_PREFIX))\n throw new Error(\n `ENRTree root entry must start with '${this.ROOT_PREFIX}'`\n );\n\n const rootValues = ENRTree.parseRootValues(root);\n const decodedPublicKey = base32.decode.asBytes(publicKey);\n\n // The signature is a 65-byte secp256k1 over the keccak256 hash\n // of the record content, excluding the `sig=` part, encoded as URL-safe base64 string\n // (Trailing recovery bit must be trimmed to pass `ecdsaVerify` method)\n const signedComponent = root.split(\" sig\")[0];\n\n const signedComponentBuffer = utf8ToBytes(signedComponent);\n const signatureBuffer = fromString(rootValues.signature, \"base64url\").slice(\n 0,\n 64\n );\n\n const isVerified = verifySignature(\n signatureBuffer,\n keccak256(signedComponentBuffer),\n new Uint8Array(decodedPublicKey)\n );\n\n if (!isVerified) throw new Error(\"Unable to verify ENRTree root signature\");\n\n return rootValues.eRoot;\n }\n\n static parseRootValues(txt: string): ENRRootValues {\n const matches = txt.match(\n /^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\\d+) sig=([^ ]+)$/\n );\n\n if (!Array.isArray(matches))\n throw new Error(\"Could not parse ENRTree root entry\");\n\n matches.shift(); // The first entry is the full match\n const [eRoot, lRoot, seq, signature] = matches;\n\n if (!eRoot)\n throw new Error(\"Could not parse 'e' value from ENRTree root entry\");\n if (!lRoot)\n throw new Error(\"Could not parse 'l' value from ENRTree root entry\");\n\n if (!seq)\n throw new Error(\"Could not parse 'seq' value from ENRTree root entry\");\n if (!signature)\n throw new Error(\"Could not parse 'sig' value from ENRTree root entry\");\n\n return { eRoot, lRoot, seq: Number(seq), signature };\n }\n\n /**\n * Returns the public key and top level domain of an ENR tree entry.\n * The domain is the starting point for traversing a set of linked DNS TXT records\n * and the public key is used to verify the root entry record\n */\n static parseTree(tree: string): ENRTreeValues {\n if (!tree.startsWith(this.TREE_PREFIX))\n throw new Error(\n `ENRTree tree entry must start with '${this.TREE_PREFIX}'`\n );\n\n const matches = tree.match(/^enrtree:\\/\\/([^@]+)@(.+)$/);\n\n if (!Array.isArray(matches))\n throw new Error(\"Could not parse ENRTree tree entry\");\n\n matches.shift(); // The first entry is the full match\n const [publicKey, domain] = matches;\n\n if (!publicKey)\n throw new Error(\"Could not parse public key from ENRTree tree entry\");\n if (!domain)\n throw new Error(\"Could not parse domain from ENRTree tree entry\");\n\n return { publicKey, domain };\n }\n\n /**\n * Returns subdomains listed in an ENR branch entry. These in turn lead to\n * either further branch entries or ENR records.\n */\n static parseBranch(branch: string): string[] {\n if (!branch.startsWith(this.BRANCH_PREFIX))\n throw new Error(\n `ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`\n );\n\n return branch.split(this.BRANCH_PREFIX)[1].split(\",\");\n }\n}\n","import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n","import type { IEnr, NodeCapabilityCount, Waku2 } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\n\nconst log = new Logger(\"discovery:fetch_nodes\");\n\n/**\n * Fetch nodes using passed [[getNode]] until all wanted capabilities are\n * fulfilled or the number of [[getNode]] call exceeds the sum of\n * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].\n */\nexport async function fetchNodesUntilCapabilitiesFulfilled(\n wantedNodeCapabilityCount: Partial,\n errorTolerance: number,\n getNode: () => Promise\n): Promise {\n const wanted = {\n relay: wantedNodeCapabilityCount.relay ?? 0,\n store: wantedNodeCapabilityCount.store ?? 0,\n filter: wantedNodeCapabilityCount.filter ?? 0,\n lightPush: wantedNodeCapabilityCount.lightPush ?? 0\n };\n\n const maxSearches =\n wanted.relay + wanted.store + wanted.filter + wanted.lightPush;\n\n const actual = {\n relay: 0,\n store: 0,\n filter: 0,\n lightPush: 0\n };\n\n let totalSearches = 0;\n const peers: IEnr[] = [];\n\n while (\n !isSatisfied(wanted, actual) &&\n totalSearches < maxSearches + errorTolerance\n ) {\n const peer = await getNode();\n if (peer && isNewPeer(peer, peers)) {\n // ENRs without a waku2 key are ignored.\n if (peer.waku2) {\n if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {\n addCapabilities(peer.waku2, actual);\n peers.push(peer);\n }\n }\n log.info(\n `got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`\n );\n }\n\n totalSearches++;\n }\n return peers;\n}\n\n/**\n * Fetch nodes using passed [[getNode]] until all wanted capabilities are\n * fulfilled or the number of [[getNode]] call exceeds the sum of\n * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].\n */\nexport async function* yieldNodesUntilCapabilitiesFulfilled(\n wantedNodeCapabilityCount: Partial,\n errorTolerance: number,\n getNode: () => Promise\n): AsyncGenerator {\n const wanted = {\n relay: wantedNodeCapabilityCount.relay ?? 0,\n store: wantedNodeCapabilityCount.store ?? 0,\n filter: wantedNodeCapabilityCount.filter ?? 0,\n lightPush: wantedNodeCapabilityCount.lightPush ?? 0\n };\n\n const maxSearches =\n wanted.relay + wanted.store + wanted.filter + wanted.lightPush;\n\n const actual = {\n relay: 0,\n store: 0,\n filter: 0,\n lightPush: 0\n };\n\n let totalSearches = 0;\n const peerNodeIds = new Set();\n\n while (\n !isSatisfied(wanted, actual) &&\n totalSearches < maxSearches + errorTolerance\n ) {\n const peer = await getNode();\n if (peer && peer.nodeId && !peerNodeIds.has(peer.nodeId)) {\n peerNodeIds.add(peer.nodeId);\n // ENRs without a waku2 key are ignored.\n if (peer.waku2) {\n if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {\n addCapabilities(peer.waku2, actual);\n yield peer;\n }\n }\n log.info(\n `got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`\n );\n }\n totalSearches++;\n }\n}\n\nfunction isSatisfied(\n wanted: NodeCapabilityCount,\n actual: NodeCapabilityCount\n): boolean {\n return (\n actual.relay >= wanted.relay &&\n actual.store >= wanted.store &&\n actual.filter >= wanted.filter &&\n actual.lightPush >= wanted.lightPush\n );\n}\n\nfunction isNewPeer(peer: IEnr, peers: IEnr[]): boolean {\n if (!peer.nodeId) return false;\n\n for (const existingPeer of peers) {\n if (peer.nodeId === existingPeer.nodeId) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction addCapabilities(node: Waku2, total: NodeCapabilityCount): void {\n if (node.relay) total.relay += 1;\n if (node.store) total.store += 1;\n if (node.filter) total.filter += 1;\n if (node.lightPush) total.lightPush += 1;\n}\n\n/**\n * Checks if the proposed ENR [[node]] helps satisfy the [[wanted]] capabilities,\n * considering the [[actual]] capabilities of nodes retrieved so far..\n *\n * @throws If the function is called when the wanted capabilities are already fulfilled.\n */\nfunction helpsSatisfyCapabilities(\n node: Waku2,\n wanted: NodeCapabilityCount,\n actual: NodeCapabilityCount\n): boolean {\n if (isSatisfied(wanted, actual)) {\n throw \"Internal Error: Waku2 wanted capabilities are already fulfilled\";\n }\n\n const missing = missingCapabilities(wanted, actual);\n\n return (\n (missing.relay && node.relay) ||\n (missing.store && node.store) ||\n (missing.filter && node.filter) ||\n (missing.lightPush && node.lightPush)\n );\n}\n\n/**\n * Return a [[Waku2]] Object for which capabilities are set to true if they are\n * [[wanted]] yet missing from [[actual]].\n */\nfunction missingCapabilities(\n wanted: NodeCapabilityCount,\n actual: NodeCapabilityCount\n): Waku2 {\n return {\n relay: actual.relay < wanted.relay,\n store: actual.store < wanted.store,\n filter: actual.filter < wanted.filter,\n lightPush: actual.lightPush < wanted.lightPush\n };\n}\n","import { ENR, EnrDecoder } from \"@waku/enr\";\nimport type {\n DnsClient,\n IEnr,\n NodeCapabilityCount,\n SearchContext\n} from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\n\nimport { DnsOverHttps } from \"./dns_over_https.js\";\nimport { ENRTree } from \"./enrtree.js\";\nimport {\n fetchNodesUntilCapabilitiesFulfilled,\n yieldNodesUntilCapabilitiesFulfilled\n} from \"./fetch_nodes.js\";\n\nconst log = new Logger(\"discovery:dns\");\n\nexport class DnsNodeDiscovery {\n private readonly dns: DnsClient;\n private readonly _DNSTreeCache: { [key: string]: string };\n private readonly _errorTolerance: number = 10;\n\n public static async dnsOverHttp(\n dnsClient?: DnsClient\n ): Promise {\n if (!dnsClient) {\n dnsClient = await DnsOverHttps.create();\n }\n return new DnsNodeDiscovery(dnsClient);\n }\n\n /**\n * Returns a list of verified peers listed in an EIP-1459 DNS tree. Method may\n * return fewer peers than requested if @link wantedNodeCapabilityCount requires\n * larger quantity of peers than available or the number of errors/duplicate\n * peers encountered by randomized search exceeds the sum of the fields of\n * @link wantedNodeCapabilityCount plus the @link _errorTolerance factor.\n */\n async getPeers(\n enrTreeUrls: string[],\n wantedNodeCapabilityCount: Partial\n ): Promise {\n const networkIndex = Math.floor(Math.random() * enrTreeUrls.length);\n const { publicKey, domain } = ENRTree.parseTree(enrTreeUrls[networkIndex]);\n const context: SearchContext = {\n domain,\n publicKey,\n visits: {}\n };\n\n const peers = await fetchNodesUntilCapabilitiesFulfilled(\n wantedNodeCapabilityCount,\n this._errorTolerance,\n () => this._search(domain, context)\n );\n log.info(\n \"retrieved peers: \",\n peers.map((peer) => {\n return {\n id: peer.peerId?.toString(),\n multiaddrs: peer.multiaddrs?.map((ma) => ma.toString())\n };\n })\n );\n return peers;\n }\n\n public constructor(dns: DnsClient) {\n this._DNSTreeCache = {};\n this.dns = dns;\n }\n\n /**\n * {@inheritDoc getPeers}\n */\n async *getNextPeer(\n enrTreeUrls: string[],\n wantedNodeCapabilityCount: Partial\n ): AsyncGenerator {\n const networkIndex = Math.floor(Math.random() * enrTreeUrls.length);\n const { publicKey, domain } = ENRTree.parseTree(enrTreeUrls[networkIndex]);\n const context: SearchContext = {\n domain,\n publicKey,\n visits: {}\n };\n\n for await (const peer of yieldNodesUntilCapabilitiesFulfilled(\n wantedNodeCapabilityCount,\n this._errorTolerance,\n () => this._search(domain, context)\n )) {\n yield peer;\n }\n }\n\n /**\n * Runs a recursive, randomized descent of the DNS tree to retrieve a single\n * ENR record as an ENR. Returns null if parsing or DNS resolution fails.\n */\n private async _search(\n subdomain: string,\n context: SearchContext\n ): Promise {\n try {\n const entry = await this._getTXTRecord(subdomain, context);\n context.visits[subdomain] = true;\n\n let next: string;\n let branches: string[];\n\n const entryType = getEntryType(entry);\n try {\n switch (entryType) {\n case ENRTree.ROOT_PREFIX:\n next = ENRTree.parseAndVerifyRoot(entry, context.publicKey);\n return await this._search(next, context);\n case ENRTree.BRANCH_PREFIX:\n branches = ENRTree.parseBranch(entry);\n next = selectRandomPath(branches, context);\n return await this._search(next, context);\n case ENRTree.RECORD_PREFIX:\n return EnrDecoder.fromString(entry);\n default:\n return null;\n }\n } catch (error) {\n log.error(\n `Failed to search DNS tree ${entryType} at subdomain ${subdomain}: ${error}`\n );\n return null;\n }\n } catch (error) {\n log.error(\n `Failed to retrieve TXT record at subdomain ${subdomain}: ${error}`\n );\n return null;\n }\n }\n\n /**\n * Retrieves the TXT record stored at a location from either\n * this DNS tree cache or via DNS query.\n *\n * @throws if the TXT Record contains non-UTF-8 values.\n */\n private async _getTXTRecord(\n subdomain: string,\n context: SearchContext\n ): Promise {\n if (this._DNSTreeCache[subdomain]) {\n return this._DNSTreeCache[subdomain];\n }\n\n // Location is either the top level tree entry host or a subdomain of it.\n const location =\n subdomain !== context.domain\n ? `${subdomain}.${context.domain}`\n : context.domain;\n\n const response = await this.dns.resolveTXT(location);\n\n if (!response.length)\n throw new Error(\"Received empty result array while fetching TXT record\");\n if (!response[0].length) throw new Error(\"Received empty TXT record\");\n\n // Branch entries can be an array of strings of comma delimited subdomains, with\n // some subdomain strings split across the array elements\n const result = response.join(\"\");\n\n this._DNSTreeCache[subdomain] = result;\n return result;\n }\n}\n\nfunction getEntryType(entry: string): string {\n if (entry.startsWith(ENRTree.ROOT_PREFIX)) return ENRTree.ROOT_PREFIX;\n if (entry.startsWith(ENRTree.BRANCH_PREFIX)) return ENRTree.BRANCH_PREFIX;\n if (entry.startsWith(ENRTree.RECORD_PREFIX)) return ENRTree.RECORD_PREFIX;\n\n return \"\";\n}\n\n/**\n * Returns a randomly selected subdomain string from the list provided by a branch\n * entry record.\n *\n * The client must track subdomains which are already resolved to avoid\n * going into an infinite loop b/c branch entries can contain\n * circular references. It’s in the client’s best interest to traverse the\n * tree in random order.\n */\nfunction selectRandomPath(branches: string[], context: SearchContext): string {\n // Identify domains already visited in this traversal of the DNS tree.\n // Then filter against them to prevent cycles.\n const circularRefs: { [key: number]: boolean } = {};\n for (const [idx, subdomain] of branches.entries()) {\n if (context.visits[subdomain]) {\n circularRefs[idx] = true;\n }\n }\n // If all possible paths are circular...\n if (Object.keys(circularRefs).length === branches.length) {\n throw new Error(\"Unresolvable circular path detected\");\n }\n\n // Randomly select a viable path\n let index;\n do {\n index = Math.floor(Math.random() * branches.length);\n } while (circularRefs[index]);\n\n return branches[index];\n}\n","import {\n CustomEvent,\n PeerDiscovery,\n PeerDiscoveryEvents,\n TypedEventEmitter\n} from \"@libp2p/interface\";\nimport { peerDiscoverySymbol as symbol } from \"@libp2p/interface\";\nimport type { PeerInfo } from \"@libp2p/interface\";\nimport type {\n DnsDiscOptions,\n DnsDiscoveryComponents,\n IEnr,\n NodeCapabilityCount\n} from \"@waku/interfaces\";\nimport { encodeRelayShard, Logger } from \"@waku/utils\";\n\nimport {\n DEFAULT_BOOTSTRAP_TAG_NAME,\n DEFAULT_BOOTSTRAP_TAG_TTL,\n DEFAULT_BOOTSTRAP_TAG_VALUE,\n DEFAULT_NODE_REQUIREMENTS\n} from \"./constants.js\";\nimport { DnsNodeDiscovery } from \"./dns.js\";\n\nconst log = new Logger(\"peer-discovery-dns\");\n\n/**\n * Parse options and expose function to return bootstrap peer addresses.\n */\nexport class PeerDiscoveryDns\n extends TypedEventEmitter\n implements PeerDiscovery\n{\n private nextPeer: (() => AsyncGenerator) | undefined;\n private _started: boolean;\n private _components: DnsDiscoveryComponents;\n private _options: DnsDiscOptions;\n\n constructor(components: DnsDiscoveryComponents, options: DnsDiscOptions) {\n super();\n this._started = false;\n this._components = components;\n this._options = options;\n\n const { enrUrls } = options;\n log.info(\"Use following EIP-1459 ENR Tree URLs: \", enrUrls);\n }\n\n /**\n * Start discovery process\n */\n async start(): Promise {\n log.info(\"Starting peer discovery via dns\");\n\n this._started = true;\n\n if (this.nextPeer === undefined) {\n let { enrUrls } = this._options;\n if (!Array.isArray(enrUrls)) enrUrls = [enrUrls];\n\n const { wantedNodeCapabilityCount } = this._options;\n const dns = await DnsNodeDiscovery.dnsOverHttp();\n\n this.nextPeer = dns.getNextPeer.bind(\n dns,\n enrUrls,\n wantedNodeCapabilityCount\n );\n }\n\n for await (const peerEnr of this.nextPeer()) {\n if (!this._started) {\n return;\n }\n\n const { peerInfo, shardInfo } = peerEnr;\n\n if (!peerInfo) {\n continue;\n }\n\n const tagsToUpdate = {\n [DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._options.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._options.tagTTL ?? DEFAULT_BOOTSTRAP_TAG_TTL\n }\n };\n\n let isPeerChanged = false;\n const isPeerExists = await this._components.peerStore.has(peerInfo.id);\n\n if (isPeerExists) {\n const peer = await this._components.peerStore.get(peerInfo.id);\n const hasBootstrapTag = peer.tags.has(DEFAULT_BOOTSTRAP_TAG_NAME);\n\n if (!hasBootstrapTag) {\n isPeerChanged = true;\n await this._components.peerStore.merge(peerInfo.id, {\n tags: tagsToUpdate\n });\n }\n } else {\n isPeerChanged = true;\n await this._components.peerStore.save(peerInfo.id, {\n tags: tagsToUpdate,\n ...(shardInfo && {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n })\n });\n }\n\n if (isPeerChanged) {\n this.dispatchEvent(\n new CustomEvent(\"peer\", { detail: peerInfo })\n );\n }\n }\n }\n\n /**\n * Stop emitting events\n */\n stop(): void {\n this._started = false;\n }\n\n get [symbol](): true {\n return true;\n }\n\n get [Symbol.toStringTag](): string {\n return \"@waku/bootstrap\";\n }\n}\n\nexport function wakuDnsDiscovery(\n enrUrls: string[],\n wantedNodeCapabilityCount: Partial = DEFAULT_NODE_REQUIREMENTS\n): (components: DnsDiscoveryComponents) => PeerDiscoveryDns {\n return (components: DnsDiscoveryComponents) =>\n new PeerDiscoveryDns(components, { enrUrls, wantedNodeCapabilityCount });\n}\n","import { proto_peer_exchange as proto } from \"@waku/proto\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\n\n/**\n * PeerExchangeRPC represents a message conforming to the Waku Peer Exchange protocol\n */\nexport class PeerExchangeRPC {\n public constructor(public proto: proto.PeerExchangeRPC) {}\n\n static createRequest(params: proto.PeerExchangeQuery): PeerExchangeRPC {\n const { numPeers } = params;\n return new PeerExchangeRPC({\n query: {\n numPeers: numPeers\n },\n response: undefined\n });\n }\n\n /**\n * Encode the current PeerExchangeRPC request to bytes\n * @returns Uint8Array\n */\n encode(): Uint8Array {\n return proto.PeerExchangeRPC.encode(this.proto);\n }\n\n /**\n * Decode the current PeerExchangeRPC request to bytes\n * @returns Uint8Array\n */\n static decode(bytes: Uint8ArrayList): PeerExchangeRPC {\n const res = proto.PeerExchangeRPC.decode(bytes);\n return new PeerExchangeRPC(res);\n }\n\n get query(): proto.PeerExchangeQuery | undefined {\n return this.proto.query;\n }\n\n get response(): proto.PeerExchangeResponse | undefined {\n return this.proto.response;\n }\n}\n","import { BaseProtocol } from \"@waku/core/lib/base_protocol\";\nimport { EnrDecoder } from \"@waku/enr\";\nimport {\n IPeerExchange,\n Libp2pComponents,\n PeerExchangeQueryParams,\n PeerExchangeResult,\n ProtocolError,\n PubsubTopic\n} from \"@waku/interfaces\";\nimport { isDefined } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\n\nimport { PeerExchangeRPC } from \"./rpc.js\";\n\nexport const PeerExchangeCodec = \"/vac/waku/peer-exchange/2.0.0-alpha1\";\n\nconst log = new Logger(\"peer-exchange\");\n\n/**\n * Implementation of the Peer Exchange protocol (https://rfc.vac.dev/spec/34/)\n */\nexport class WakuPeerExchange extends BaseProtocol implements IPeerExchange {\n /**\n * @param components - libp2p components\n */\n constructor(components: Libp2pComponents, pubsubTopics: PubsubTopic[]) {\n super(PeerExchangeCodec, components, log, pubsubTopics);\n }\n\n /**\n * Make a peer exchange query to a peer\n */\n async query(params: PeerExchangeQueryParams): Promise {\n const { numPeers } = params;\n const rpcQuery = PeerExchangeRPC.createRequest({\n numPeers: BigInt(numPeers)\n });\n\n const peer = await this.peerStore.get(params.peerId);\n if (!peer) {\n return {\n peerInfos: null,\n error: ProtocolError.NO_PEER_AVAILABLE\n };\n }\n\n const stream = await this.getStream(peer);\n\n const res = await pipe(\n [rpcQuery.encode()],\n lp.encode,\n stream,\n lp.decode,\n async (source) => await all(source)\n );\n\n try {\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n\n const { response } = PeerExchangeRPC.decode(bytes);\n if (!response) {\n log.error(\n \"PeerExchangeRPC message did not contains a `response` field\"\n );\n return {\n peerInfos: null,\n error: ProtocolError.EMPTY_PAYLOAD\n };\n }\n\n const peerInfos = await Promise.all(\n response.peerInfos\n .map((peerInfo) => peerInfo.enr)\n .filter(isDefined)\n .map(async (enr) => {\n return { ENR: await EnrDecoder.fromRLP(enr) };\n })\n );\n\n return {\n peerInfos,\n error: null\n };\n } catch (err) {\n log.error(\"Failed to decode push reply\", err);\n return {\n peerInfos: null,\n error: ProtocolError.DECODE_FAILED\n };\n }\n }\n}\n\n/**\n *\n * @returns A function that creates a new peer exchange protocol\n */\nexport function wakuPeerExchange(\n pubsubTopics: PubsubTopic[]\n): (components: Libp2pComponents) => WakuPeerExchange {\n return (components: Libp2pComponents) =>\n new WakuPeerExchange(components, pubsubTopics);\n}\n","import { CustomEvent, TypedEventEmitter } from \"@libp2p/interface\";\nimport { peerDiscoverySymbol as symbol } from \"@libp2p/interface\";\nimport type {\n IdentifyResult,\n PeerDiscovery,\n PeerDiscoveryEvents,\n PeerId,\n PeerInfo\n} from \"@libp2p/interface\";\nimport {\n Libp2pComponents,\n PeerExchangeResult,\n PubsubTopic,\n Tags\n} from \"@waku/interfaces\";\nimport { encodeRelayShard, Logger } from \"@waku/utils\";\n\nimport { PeerExchangeCodec, WakuPeerExchange } from \"./waku_peer_exchange.js\";\n\nconst log = new Logger(\"peer-exchange-discovery\");\n\nconst DEFAULT_PEER_EXCHANGE_REQUEST_NODES = 10;\nconst DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS = 10 * 1000;\nconst DEFAULT_MAX_RETRIES = 3;\n\nexport interface Options {\n /**\n * Tag a bootstrap peer with this name before \"discovering\" it (default: 'bootstrap')\n */\n tagName?: string;\n\n /**\n * The bootstrap peer tag will have this value (default: 50)\n */\n tagValue?: number;\n\n /**\n * Cause the bootstrap peer tag to be removed after this number of ms (default: 2 minutes)\n */\n tagTTL?: number;\n /**\n * The interval between queries to a peer (default: 10 seconds)\n * The interval will increase by a factor of an incrementing number (starting at 1)\n * until it reaches the maximum attempts before backoff\n */\n queryInterval?: number;\n /**\n * The number of attempts before the queries to a peer are aborted (default: 3)\n */\n maxRetries?: number;\n}\n\nexport const DEFAULT_PEER_EXCHANGE_TAG_NAME = Tags.PEER_EXCHANGE;\nconst DEFAULT_PEER_EXCHANGE_TAG_VALUE = 50;\nconst DEFAULT_PEER_EXCHANGE_TAG_TTL = 100_000_000;\n\nexport class PeerExchangeDiscovery\n extends TypedEventEmitter\n implements PeerDiscovery\n{\n private readonly components: Libp2pComponents;\n private readonly peerExchange: WakuPeerExchange;\n private readonly options: Options;\n private isStarted: boolean;\n private queryingPeers: Set = new Set();\n private queryAttempts: Map = new Map();\n\n private readonly handleDiscoveredPeer = (\n event: CustomEvent\n ): void => {\n const { protocols, peerId } = event.detail;\n\n if (\n !protocols.includes(PeerExchangeCodec) ||\n this.queryingPeers.has(peerId.toString())\n )\n return;\n\n this.queryingPeers.add(peerId.toString());\n this.startRecurringQueries(peerId).catch((error) =>\n log.error(`Error querying peer ${error}`)\n );\n };\n\n constructor(\n components: Libp2pComponents,\n pubsubTopics: PubsubTopic[],\n options: Options = {}\n ) {\n super();\n this.components = components;\n this.peerExchange = new WakuPeerExchange(components, pubsubTopics);\n this.options = options;\n this.isStarted = false;\n }\n\n /**\n * Start emitting events\n */\n start(): void {\n if (this.isStarted) {\n return;\n }\n\n log.info(\"Starting peer exchange node discovery, discovering peers\");\n\n // might be better to use \"peer:identify\" or \"peer:update\"\n this.components.events.addEventListener(\n \"peer:identify\",\n this.handleDiscoveredPeer\n );\n }\n\n /**\n * Remove event listener\n */\n stop(): void {\n if (!this.isStarted) return;\n log.info(\"Stopping peer exchange node discovery\");\n this.isStarted = false;\n this.queryingPeers.clear();\n this.components.events.removeEventListener(\n \"peer:identify\",\n this.handleDiscoveredPeer\n );\n }\n\n get [symbol](): true {\n return true;\n }\n\n get [Symbol.toStringTag](): string {\n return \"@waku/peer-exchange\";\n }\n\n private readonly startRecurringQueries = async (\n peerId: PeerId\n ): Promise => {\n const peerIdStr = peerId.toString();\n const {\n queryInterval = DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS,\n maxRetries = DEFAULT_MAX_RETRIES\n } = this.options;\n\n log.info(\n `Querying peer: ${peerIdStr} (attempt ${\n this.queryAttempts.get(peerIdStr) ?? 1\n })`\n );\n\n await this.query(peerId);\n\n const currentAttempt = this.queryAttempts.get(peerIdStr) ?? 1;\n\n if (currentAttempt > maxRetries) {\n this.abortQueriesForPeer(peerIdStr);\n return;\n }\n\n setTimeout(() => {\n this.queryAttempts.set(peerIdStr, currentAttempt + 1);\n this.startRecurringQueries(peerId).catch((error) => {\n log.error(`Error in startRecurringQueries: ${error}`);\n });\n }, queryInterval * currentAttempt);\n };\n\n private async query(peerId: PeerId): Promise {\n const { error, peerInfos } = await this.peerExchange.query({\n numPeers: DEFAULT_PEER_EXCHANGE_REQUEST_NODES,\n peerId\n });\n\n if (error) {\n log.error(\"Peer exchange query failed\", error);\n return { error, peerInfos: null };\n }\n\n for (const _peerInfo of peerInfos) {\n const { ENR } = _peerInfo;\n if (!ENR) {\n log.warn(\"No ENR in peerInfo object, skipping\");\n continue;\n }\n\n const { peerId, peerInfo, shardInfo } = ENR;\n if (!peerId || !peerInfo) {\n continue;\n }\n\n const hasPeer = await this.components.peerStore.has(peerId);\n if (hasPeer) {\n continue;\n }\n\n // update the tags for the peer\n await this.components.peerStore.save(peerId, {\n tags: {\n [DEFAULT_PEER_EXCHANGE_TAG_NAME]: {\n value: this.options.tagValue ?? DEFAULT_PEER_EXCHANGE_TAG_VALUE,\n ttl: this.options.tagTTL ?? DEFAULT_PEER_EXCHANGE_TAG_TTL\n }\n },\n ...(shardInfo && {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n })\n });\n\n log.info(`Discovered peer: ${peerId.toString()}`);\n\n this.dispatchEvent(\n new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: peerInfo.multiaddrs\n }\n })\n );\n }\n\n return { error: null, peerInfos };\n }\n\n private abortQueriesForPeer(peerIdStr: string): void {\n log.info(`Aborting queries for peer: ${peerIdStr}`);\n this.queryingPeers.delete(peerIdStr);\n this.queryAttempts.delete(peerIdStr);\n }\n}\n\nexport function wakuPeerExchangeDiscovery(\n pubsubTopics: PubsubTopic[]\n): (components: Libp2pComponents) => PeerExchangeDiscovery {\n return (components: Libp2pComponents) =>\n new PeerExchangeDiscovery(components, pubsubTopics);\n}\n","import { TypedEventEmitter } from \"@libp2p/interface\";\nimport {\n CustomEvent,\n IdentifyResult,\n PeerDiscovery,\n PeerDiscoveryEvents,\n PeerInfo,\n Startable\n} from \"@libp2p/interface\";\nimport { createFromJSON } from \"@libp2p/peer-id-factory\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport {\n type Libp2pComponents,\n type LocalStoragePeerInfo,\n Tags\n} from \"@waku/interfaces\";\nimport { getWsMultiaddrFromMultiaddrs, Logger } from \"@waku/utils\";\n\nconst log = new Logger(\"peer-exchange-discovery\");\n\ntype LocalPeerCacheDiscoveryOptions = {\n tagName?: string;\n tagValue?: number;\n tagTTL?: number;\n};\n\nexport const DEFAULT_LOCAL_TAG_NAME = Tags.LOCAL;\nconst DEFAULT_LOCAL_TAG_VALUE = 50;\nconst DEFAULT_LOCAL_TAG_TTL = 100_000_000;\n\nexport class LocalPeerCacheDiscovery\n extends TypedEventEmitter\n implements PeerDiscovery, Startable\n{\n private isStarted: boolean;\n private peers: LocalStoragePeerInfo[] = [];\n\n constructor(\n private readonly components: Libp2pComponents,\n private readonly options?: LocalPeerCacheDiscoveryOptions\n ) {\n super();\n this.isStarted = false;\n this.peers = this.getPeersFromLocalStorage();\n }\n\n get [Symbol.toStringTag](): string {\n return \"@waku/local-peer-cache-discovery\";\n }\n\n async start(): Promise {\n if (this.isStarted) return;\n\n log.info(\"Starting Local Storage Discovery\");\n this.components.events.addEventListener(\n \"peer:identify\",\n this.handleNewPeers\n );\n\n for (const { id: idStr, address } of this.peers) {\n const peerId = await createFromJSON({ id: idStr });\n if (await this.components.peerStore.has(peerId)) continue;\n\n await this.components.peerStore.save(peerId, {\n multiaddrs: [multiaddr(address)],\n tags: {\n [this.options?.tagName ?? DEFAULT_LOCAL_TAG_NAME]: {\n value: this.options?.tagValue ?? DEFAULT_LOCAL_TAG_VALUE,\n ttl: this.options?.tagTTL ?? DEFAULT_LOCAL_TAG_TTL\n }\n }\n });\n\n this.dispatchEvent(\n new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: [multiaddr(address)]\n }\n })\n );\n }\n\n log.info(`Discovered ${this.peers.length} peers`);\n\n this.isStarted = true;\n }\n\n stop(): void | Promise {\n if (!this.isStarted) return;\n log.info(\"Stopping Local Storage Discovery\");\n this.components.events.removeEventListener(\n \"peer:identify\",\n this.handleNewPeers\n );\n this.isStarted = false;\n\n this.savePeersToLocalStorage();\n }\n\n handleNewPeers = (event: CustomEvent): void => {\n const { peerId, listenAddrs } = event.detail;\n\n const websocketMultiaddr = getWsMultiaddrFromMultiaddrs(listenAddrs);\n\n const localStoragePeers = this.getPeersFromLocalStorage();\n\n const existingPeerIndex = localStoragePeers.findIndex(\n (_peer) => _peer.id === peerId.toString()\n );\n\n if (existingPeerIndex >= 0) {\n localStoragePeers[existingPeerIndex].address =\n websocketMultiaddr.toString();\n } else {\n localStoragePeers.push({\n id: peerId.toString(),\n address: websocketMultiaddr.toString()\n });\n }\n\n this.peers = localStoragePeers;\n this.savePeersToLocalStorage();\n };\n\n private getPeersFromLocalStorage(): LocalStoragePeerInfo[] {\n try {\n const storedPeersData = localStorage.getItem(\"waku:peers\");\n if (!storedPeersData) return [];\n const peers = JSON.parse(storedPeersData);\n return peers.filter(isValidStoredPeer);\n } catch (error) {\n log.error(\"Error parsing peers from local storage:\", error);\n return [];\n }\n }\n\n private savePeersToLocalStorage(): void {\n localStorage.setItem(\"waku:peers\", JSON.stringify(this.peers));\n }\n}\n\nfunction isValidStoredPeer(peer: any): peer is LocalStoragePeerInfo {\n return (\n peer &&\n typeof peer === \"object\" &&\n typeof peer.id === \"string\" &&\n typeof peer.address === \"string\"\n );\n}\n\nexport function wakuLocalPeerCacheDiscovery(): (\n components: Libp2pComponents,\n options?: LocalPeerCacheDiscoveryOptions\n) => LocalPeerCacheDiscovery {\n return (\n components: Libp2pComponents,\n options?: LocalPeerCacheDiscoveryOptions\n ) => new LocalPeerCacheDiscovery(components, options);\n}\n","import type { Multiaddr } from \"@multiformats/multiaddr\";\nexport * from \"./is_defined.js\";\nexport * from \"./random_subset.js\";\nexport * from \"./group_by.js\";\nexport * from \"./to_async_iterator.js\";\nexport * from \"./is_size_valid.js\";\nexport * from \"./sharding.js\";\nexport * from \"./push_or_init_map.js\";\nexport * from \"./relay_shard_codec.js\";\n\nexport function removeItemFromArray(arr: unknown[], value: unknown): unknown[] {\n const index = arr.indexOf(value);\n if (index > -1) {\n arr.splice(index, 1);\n }\n return arr;\n}\n\nexport function getWsMultiaddrFromMultiaddrs(\n addresses: Multiaddr[]\n): Multiaddr {\n const wsMultiaddr = addresses.find(\n (addr) => addr.toString().includes(\"ws\") || addr.toString().includes(\"wss\")\n );\n if (!wsMultiaddr) {\n throw new Error(\"No ws multiaddr found in the given addresses\");\n }\n return wsMultiaddr;\n}\n","import React from \"react\";\nimport { createDecoder, createEncoder, waku } from \"@waku/sdk\";\n\nimport type { ContentPair } from \"./types\";\n\n/**\n * Creates Encoder / Decoder pair for a given contentTopic.\n * @param {string} contentTopic - topic to orient to\n * @param {boolean} ephemeral - makes messages ephemeral, default to false\n * @returns {Object} Encoder / Decoder pair\n */\nexport const useCreateContentPair = (\n contentTopic: string,\n ephemeral = false,\n): ContentPair => {\n const [encoder, setEncoder] = React.useState(\n createEncoder({ contentTopic, ephemeral }),\n );\n const [decoder, setDecoder] = React.useState(\n createDecoder(contentTopic),\n );\n\n React.useEffect(() => {\n setEncoder(createEncoder({ contentTopic, ephemeral }));\n setDecoder(createDecoder(contentTopic));\n }, [contentTopic, ephemeral]);\n\n return {\n encoder,\n decoder,\n };\n};\n","import React from \"react\";\n\nimport type { ContentPair, ReactChildrenProps } from \"./types\";\nimport { useCreateContentPair } from \"./useCreatContentPair\";\n\ntype ContentPairContextType = Partial;\n\nconst ContentPairContext = React.createContext({\n decoder: undefined,\n encoder: undefined,\n});\n\n/**\n * Hook to retrieve Encoder/Decoder pair from Context.\n * @example\n * const { encoder, decoder } = useContentPair();\n * @returns {Object} { encoder, decoder }\n */\nexport const useContentPair = (): ContentPairContextType =>\n React.useContext(ContentPairContext);\n\ntype ContentPairProviderProps = ReactChildrenProps & {\n contentTopic: string;\n ephemeral?: boolean;\n};\n\n/**\n * Provider for creating Encoder/Decoder pair based on contentTopic\n * @example\n * const App = (props) => (\n * \n * \n * \n * );\n * const Component = (props) => {\n * const { encoder, decoder } = useContentPair();\n * ...\n * };\n * @param {string} contentTopic - content topic for configuring the pair\n * @param {boolean} ephemeral - flag to set messages ephemeral according to RFC https://rfc.vac.dev/spec/14/\n * @returns React ContentPair Provider component\n */\nexport const ContentPairProvider: React.FunctionComponent<\n ContentPairProviderProps\n> = (props) => {\n const result = useCreateContentPair(props.contentTopic, props.ephemeral);\n\n return (\n \n {props.children}\n \n );\n};\n","import React from \"react\";\nimport type { LightNode, Waku } from \"@waku/interfaces\";\nimport { createLightNode, waitForRemotePeer } from \"@waku/sdk\";\n\nimport type {\n BootstrapNodeOptions,\n CreateNodeResult,\n CreateWakuNodeOptions,\n} from \"./types\";\n\ntype NodeFactory = (options?: T) => Promise;\n\ntype CreateNodeParams = BootstrapNodeOptions & {\n factory: NodeFactory;\n};\n\nconst useCreateNode = (\n params: CreateNodeParams,\n): CreateNodeResult => {\n const { factory, options, protocols = [] } = params;\n\n const [node, setNode] = React.useState(undefined);\n const [isLoading, setLoading] = React.useState(true);\n const [error, setError] = React.useState(undefined);\n\n React.useEffect(() => {\n let cancelled = false;\n setLoading(true);\n\n factory(options)\n .then(async (node) => {\n if (cancelled) {\n return;\n }\n\n await node.start();\n await waitForRemotePeer(node, protocols);\n\n setNode(node);\n setLoading(false);\n })\n .catch((err) => {\n setLoading(false);\n setError(`Failed at creating node: ${err?.message || \"no message\"}`);\n });\n\n return () => {\n cancelled = true;\n };\n // TODO: missing any dependencies, it will prevent consecutive update if options change\n }, []);\n\n return {\n node,\n error,\n isLoading,\n };\n};\n\n/**\n * Create Light Node helper hook.\n * @param {Object} params - optional params to configure & bootstrap node\n * @returns {CrateWakuHook} node, loading state and error\n */\nexport const useCreateLightNode = (\n params?: BootstrapNodeOptions,\n) => {\n return useCreateNode({\n ...params,\n factory: createLightNode,\n });\n};\n","import React from \"react\";\nimport type {\n IEncoder,\n ILightPushSDK,\n IMessage,\n SendResult,\n Waku,\n} from \"@waku/interfaces\";\n\ntype AbstractLightPushNode = Waku & {\n lightPush: ILightPushSDK;\n};\n\ntype UseLightPushParams = {\n encoder: undefined | IEncoder;\n node: undefined | AbstractLightPushNode;\n};\n\ntype PushFn = (message: IMessage) => Promise;\n\ntype UseLightPushResult = {\n push?: undefined | PushFn;\n};\n\n/**\n * Returns light push methods bound to node and encoder\n * @param {Object} params.node - node that implements ILightPush, hook does nothing if empty\n * @param {Object} params.encoder - encoder for processing messages, hook does nothing if empty\n * @returns {Object} methods of ILightPush such as push\n */\nexport const useLightPush = (\n params: UseLightPushParams,\n): UseLightPushResult => {\n const { node, encoder } = params;\n\n const push = React.useCallback(\n (message) => {\n return node!.lightPush.send(encoder as IEncoder, message);\n },\n [node, encoder],\n );\n\n if (!node && !encoder) {\n return {};\n }\n\n return {\n push,\n };\n};\n","import React from \"react\";\nimport type { Waku } from \"@waku/interfaces\";\n\nimport type {\n BootstrapNodeOptions,\n CreateNodeResult,\n CreateWakuNodeOptions,\n ReactChildrenProps,\n} from \"./types\";\nimport { useCreateLightNode } from \"./useCreateWaku\";\n\ntype WakuContextType = CreateNodeResult;\n\nconst WakuContext = React.createContext>({\n node: undefined,\n isLoading: false,\n error: undefined,\n});\n\n/**\n * Hook to retrieve Waku node from Context. By default generic Waku type will be used.\n * @example\n * const { node, isLoading, error } = useWaku();\n * @example\n * const { node, isLoading, error } = useWaku();\n * @example\n * const { node, isLoading, error } = useWaku();\n * @example\n * const { node, isLoading, error } = useWaku();\n * @returns WakuContext\n */\nexport const useWaku = (): WakuContextType =>\n React.useContext(WakuContext) as WakuContextType;\n\ntype ProviderProps = ReactChildrenProps & BootstrapNodeOptions;\n\n/**\n * Provider for creating Light Node based on options passed.\n * @example\n * const App = (props) => (\n * \n * \n * \n * );\n * const Component = (props) => {\n * const { node, isLoading, error } = useWaku();\n * ...\n * };\n * @param {Object} props - options to create a node and other React props\n * @param {CreateWakuNodeOptions} props.options - optional options for creating Light Node\n * @param {Protocols} props.protocols - optional protocols list to initiate node with\n * @returns React Light Node provider component\n */\nexport const LightNodeProvider: React.FunctionComponent<\n ProviderProps\n> = (props) => {\n const result = useCreateLightNode({\n options: props.options,\n protocols: props.protocols,\n });\n\n return (\n {props.children}\n );\n};\n","import { multiaddr } from \"@multiformats/multiaddr\";\nimport type { LightNode } from \"@waku/interfaces\";\n\nfunction help(): string[] {\n return [\n \"/nick : set a new nickname\",\n \"/info: some information about the node\",\n \"/connect : connect to the given peer\",\n \"/help: Display this help\",\n ];\n}\n\nfunction nick(\n nick: string | undefined,\n setNick: (nick: string) => void\n): string[] {\n if (!nick) {\n return [\"No nick provided\"];\n }\n setNick(nick);\n return [`New nick: ${nick}`];\n}\n\nfunction info(waku: LightNode | undefined): string[] {\n if (!waku) {\n return [\"Waku node is starting\"];\n }\n return [`PeerId: ${waku.libp2p.peerId.toString()}`];\n}\n\nfunction connect(\n peer: string | undefined,\n waku: LightNode | undefined\n): string[] {\n if (!waku) {\n return [\"Waku node is starting\"];\n }\n if (!peer) {\n return [\"No peer provided\"];\n }\n try {\n const peerMultiaddr = multiaddr(peer);\n const peerId = peerMultiaddr.getPeerId();\n if (!peerId) {\n return [\"Peer Id needed to dial\"];\n }\n waku\n .dial(peerMultiaddr)\n .catch((e) => console.error(`Failed to dial ${peerMultiaddr}`, e));\n return [\n `${peerId}: ${peerMultiaddr.toString()} added to address book, autodial in progress`,\n ];\n } catch (e) {\n return [\"Invalid multiaddr: \" + e];\n }\n}\n\nasync function peers(waku: LightNode | undefined): Promise {\n if (!waku) {\n return [\"Waku node is starting\"];\n }\n let response: string[] = [];\n const peers = await waku.libp2p.peerStore.all();\n\n Array.from(peers).forEach((peer) => {\n response.push(peer.id.toString() + \":\");\n let addresses = \" addresses: [\";\n peer.addresses.forEach(({ multiaddr }) => {\n addresses += \" \" + multiaddr.toString() + \",\";\n });\n addresses = addresses.replace(/,$/, \"\");\n addresses += \"]\";\n response.push(addresses);\n let protocols = \" protocols: [\";\n protocols += peer.protocols;\n protocols += \"]\";\n response.push(protocols);\n });\n if (response.length === 0) {\n response.push(\"Not connected to any peer.\");\n }\n return response;\n}\n\nfunction connections(waku: LightNode | undefined): string[] {\n if (!waku) {\n return [\"Waku node is starting\"];\n }\n let response: string[] = [];\n let strConnections = \" connections: \\n\";\n waku.libp2p.getConnections().forEach((connection) => {\n strConnections += connection.remotePeer.toString() + \", \";\n strConnections += JSON.stringify({\n direction: connection.direction,\n timeline: connection.timeline,\n multiplexer: connection.multiplexer,\n encryption: connection.encryption,\n status: connection.status,\n });\n strConnections += \"; \" + JSON.stringify(connection.streams);\n strConnections += \"\\n\";\n });\n response.push(strConnections);\n if (response.length === 0) {\n response.push(\"Not connected to any peer.\");\n }\n return response;\n}\n\nexport default async function handleCommand(\n input: string,\n waku: LightNode | undefined,\n setNick: (nick: string) => void\n): Promise<{ command: string; response: string[] }> {\n let response: string[] = [];\n const args = parseInput(input);\n const command = args.shift()!;\n switch (command) {\n case \"/help\":\n help().map((str) => response.push(str));\n break;\n case \"/nick\":\n nick(args.shift(), setNick).map((str) => response.push(str));\n break;\n case \"/info\":\n info(waku).map((str) => response.push(str));\n break;\n case \"/connect\":\n connect(args.shift(), waku).map((str) => response.push(str));\n break;\n case \"/peers\":\n (await peers(waku)).map((str) => response.push(str));\n break;\n case \"/connections\":\n connections(waku).map((str) => response.push(str));\n break;\n default:\n response.push(`Unknown Command '${command}'`);\n }\n return { command, response };\n}\n\nexport function parseInput(input: string): string[] {\n const clean = input.trim().replaceAll(/\\s\\s+/g, \" \");\n return clean.split(\" \");\n}\n","import { useEffect, useRef } from \"react\";\nimport { Message } from \"./Message\";\nimport type { ChatListProps } from \"./types\";\n\nexport default function ChatList(props: ChatListProps) {\n const renderedMessages = props.messages.array.map((message) => (\n \n {message.nick}\n \n {formatDisplayDate(message)}\n \n

{message.payloadAsUtf8}

\n
\n ));\n\n return (\n
\n {renderedMessages}\n \n
\n );\n}\n\nfunction formatDisplayDate(message: Message): string {\n return message.timestamp.toLocaleString([], {\n month: \"short\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n hour12: false,\n });\n}\n\nconst AlwaysScrollToBottom = (props: { messages: Message[] }) => {\n const elementRef = useRef(null);\n\n useEffect(() => {\n if (elementRef.current) {\n elementRef.current.scrollIntoView();\n }\n }, [props.messages]);\n\n return
;\n};\n","import { ChangeEvent, KeyboardEvent, useEffect, useState } from \"react\";\nimport { useWaku } from \"@waku/react\";\nimport { LightNode } from \"@waku/interfaces\";\nimport { MessageInputProps } from \"./types\";\n\nexport default function MessageInput(props: MessageInputProps) {\n const { hasLightPushPeers } = props;\n const { node } = useWaku();\n\n const [inputText, setInputText] = useState(\"\");\n const [isActive, setActiveButton] = useState(false);\n\n const onMessage = async () => {\n if (props.sendMessage && inputText) {\n try {\n await props.sendMessage(inputText);\n } catch (e) {\n console.error(`Failed to send message: ${e}`);\n }\n setInputText(\"\");\n }\n };\n\n const onChange = (event: ChangeEvent) => {\n event.preventDefault();\n setInputText(event.target.value);\n };\n\n const onKeyDown = async (event: KeyboardEvent) => {\n if (\n isActive &&\n event.key === \"Enter\" &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n await onMessage();\n }\n };\n\n // Enable the button if there are peers available or the user is sending a command\n useEffect(() => {\n if (inputText.startsWith(\"/\") || hasLightPushPeers) {\n setActiveButton(true);\n } else if (node) {\n setActiveButton(false);\n }\n }, [node, inputText, hasLightPushPeers]);\n\n return (\n
\n \n \n Send\n \n
\n );\n}\n","// @ts-expect-error no types\nimport ReaderClass from 'protobufjs/src/reader.js'\n// @ts-expect-error no types\nimport ReaderBufferClass from 'protobufjs/src/reader_buffer.js'\n// @ts-expect-error no types\nimport WriterClass from 'protobufjs/src/writer.js'\n// @ts-expect-error no types\nimport WriterBufferClass from 'protobufjs/src/writer_buffer.js'\n// @ts-expect-error no types\nimport util from 'protobufjs/src/util/minimal.js'\nimport type { Reader, Writer } from './index.js'\n\nfunction configure (): void {\n util._configure()\n ReaderClass._configure(ReaderBufferClass)\n WriterClass._configure(WriterBufferClass)\n}\n\n// Set up buffer utility according to the environment\nconfigure()\n\n// monkey patch the reader to add native bigint support\nconst methods = [\n 'uint64', 'int64', 'sint64', 'fixed64', 'sfixed64'\n]\n\nfunction patchReader (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (): bigint {\n return BigInt(original.call(this).toString())\n }\n }\n\n return obj\n}\n\nexport function reader (buf: Uint8Array): Reader {\n return patchReader(new ReaderClass(buf))\n}\n\nfunction patchWriter (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (val: bigint) {\n return original.call(this, val.toString())\n }\n }\n\n return obj\n}\n\nexport function writer (): Writer {\n return patchWriter(WriterClass.create())\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: T, writer: Writer, opts?: EncodeOptions): void\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from \"protons-runtime\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface ChatMessage {\n timestamp: bigint;\n nick: string;\n payload: Uint8Array;\n}\n\nexport namespace ChatMessage {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.timestamp != null) {\n writer.uint32(8);\n writer.uint64(obj.timestamp);\n } else {\n throw new Error(\n 'Protocol error: required field \"timestamp\" was not found in object'\n );\n }\n\n if (obj.nick != null) {\n writer.uint32(18);\n writer.string(obj.nick);\n } else {\n throw new Error(\n 'Protocol error: required field \"nick\" was not found in object'\n );\n }\n\n if (obj.payload != null) {\n writer.uint32(26);\n writer.bytes(obj.payload);\n } else {\n throw new Error(\n 'Protocol error: required field \"payload\" was not found in object'\n );\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {\n timestamp: 0n,\n nick: \"\",\n payload: new Uint8Array(0),\n };\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.timestamp = reader.uint64();\n break;\n case 2:\n obj.nick = reader.string();\n break;\n case 3:\n obj.payload = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n if (obj.timestamp == null) {\n throw new Error(\n 'Protocol error: value for required field \"timestamp\" was not found in protobuf'\n );\n }\n\n if (obj.nick == null) {\n throw new Error(\n 'Protocol error: value for required field \"nick\" was not found in protobuf'\n );\n }\n\n if (obj.payload == null) {\n throw new Error(\n 'Protocol error: value for required field \"payload\" was not found in protobuf'\n );\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: ChatMessage): Uint8Array => {\n return encodeMessage(obj, ChatMessage.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): ChatMessage => {\n return decodeMessage(buf, ChatMessage.codec());\n };\n}\n","import { createCodec, CODEC_TYPES, EncodeOptions } from '../codec.js'\nimport type { Codec } from '../codec.js'\nimport type { Reader, Writer } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: (obj: T, writer: Writer, opts?: EncodeOptions) => void, decode: (reader: Reader, length?: number) => T): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","import type { Codec } from './codec.js'\nimport { writer } from './utils.js'\n\nexport function encodeMessage (message: T, codec: Codec): Uint8Array {\n const w = writer()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from './codec.js'\nimport { reader } from './utils.js'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Codec): T {\n const r = reader(buf instanceof Uint8Array ? buf : buf.subarray())\n\n return codec.decode(r)\n}\n","import { utf8ToBytes, bytesToUtf8 } from \"@waku/sdk\";\nimport * as proto from \"./proto/chat_message\";\n\n/**\n * ChatMessage is used by the various show case waku apps that demonstrates\n * waku used as the network layer for chat group applications.\n *\n * This is included to help building PoC and MVPs. Apps that aim to be\n * production ready should use a more appropriate data structure.\n */\nexport class ChatMessage {\n public constructor(public proto: proto.ChatMessage) {}\n\n /**\n * Create Chat Message with a utf-8 string as payload.\n */\n static fromUtf8String(\n timestamp: Date,\n nick: string,\n text: string\n ): ChatMessage {\n const timestampNumber = BigInt(Math.floor(timestamp.valueOf() / 1000));\n const payload = utf8ToBytes(text);\n\n return new ChatMessage({\n timestamp: timestampNumber,\n nick,\n payload,\n });\n }\n\n /**\n * Decode a protobuf payload to a ChatMessage.\n * @param bytes The payload to decode.\n */\n static decode(bytes: Uint8Array): ChatMessage {\n const protoMsg = proto.ChatMessage.decode(bytes);\n return new ChatMessage(protoMsg);\n }\n\n /**\n * Encode this ChatMessage to a byte array, to be used as a protobuf payload.\n * @returns The encoded payload.\n */\n encode(): Uint8Array {\n return proto.ChatMessage.encode(this.proto);\n }\n\n get timestamp(): Date {\n return new Date(Number(BigInt(this.proto.timestamp) * BigInt(1000)));\n }\n\n get nick(): string {\n return this.proto.nick;\n }\n\n get payloadAsUtf8(): string {\n if (!this.proto.payload) {\n return \"\";\n }\n\n return bytesToUtf8(this.proto.payload);\n }\n}\n","import { IDecodedMessage } from \"@waku/interfaces\";\nimport { ChatMessage } from \"./chat_message\";\n\nexport class Message {\n public chatMessage: ChatMessage;\n // WakuMessage timestamp\n public sentTimestamp: Date | undefined;\n\n constructor(chatMessage: ChatMessage, sentTimestamp: Date | undefined) {\n this.chatMessage = chatMessage;\n this.sentTimestamp = sentTimestamp;\n }\n\n static cmp(left: Message, right: Message): boolean {\n return left.timestamp.getTime() < right.timestamp.getTime();\n }\n\n static isEqual(left: Message, right: Message): boolean {\n return (\n left.timestamp.valueOf() === right.timestamp.valueOf() &&\n left.chatMessage.nick === right.chatMessage.nick &&\n left.chatMessage.payloadAsUtf8 === right.chatMessage.payloadAsUtf8\n );\n }\n\n static fromWakuMessage(wakuMsg: IDecodedMessage): Message | undefined {\n if (wakuMsg.payload) {\n try {\n const chatMsg = ChatMessage.decode(wakuMsg.payload);\n if (chatMsg) {\n return new Message(chatMsg, wakuMsg.timestamp);\n }\n } catch (e) {\n console.error(\"Failed to decode chat message\", e);\n }\n }\n return;\n }\n\n static fromUtf8String(nick: string, text: string): Message {\n const now = new Date();\n return new Message(ChatMessage.fromUtf8String(now, nick, text), now);\n }\n\n get nick() {\n return this.chatMessage.nick;\n }\n\n get timestamp() {\n return this.chatMessage.timestamp;\n }\n\n get payloadAsUtf8() {\n return this.chatMessage.payloadAsUtf8;\n }\n}\n","export class OrderedSet {\n array: Array;\n\n constructor(\n public orderCmp: (a: T, b: T) => boolean,\n public isEqual: (a: T, b: T) => boolean\n ) {\n this.array = [];\n }\n\n push(...items: T[]): void {\n for (const item of items) {\n this.insertInOrder(this.array, item);\n }\n }\n\n insertInOrder(array: T[], item: T): T[] {\n let i = 0;\n while (i < array.length) {\n if (this.isEqual(item, array[i])) {\n continue;\n }\n if (this.orderCmp(item, array[i])) {\n break;\n }\n i++;\n }\n\n array.splice(i, 0, item);\n return array;\n }\n}\n","import type { Peer } from \"@libp2p/interface\";\nimport type { IFilter, ILightPushSDK, IStoreSDK } from \"@waku/interfaces\";\n\nexport async function handleCatch(\n promise?: Promise\n): Promise {\n if (!promise) {\n return Promise.resolve(undefined);\n }\n\n try {\n return await promise;\n } catch (_) {\n return undefined;\n }\n}\n\nexport function getPeerIdsForProtocol(\n protocol: IStoreSDK | ILightPushSDK | IFilter | undefined,\n peers: Peer[]\n) {\n if (!protocol) {\n return [];\n }\n const multicodec =\n \"multicodec\" in protocol\n ? protocol.multicodec\n : protocol.protocol.multicodec;\n return peers.filter((p) => p.protocols.includes(multicodec)).map((p) => p.id);\n}\n","import React, { useEffect, useState } from \"react\";\nimport { generate } from \"server-name-generator\";\nimport { Message } from \"./Message\";\nimport { EPeersByDiscoveryEvents, LightNode, Tags } from \"@waku/interfaces\";\nimport type { PeerId } from \"@libp2p/interface\";\n\nimport { useFilterMessages, useStoreMessages } from \"@waku/react\";\nimport type {\n UseMessagesParams,\n UseMessagesResult,\n UsePeersParams,\n UsePeersResults,\n} from \"./types\";\nimport { OrderedSet } from \"./ordered_array\";\nimport { getPeerIdsForProtocol } from \"./utils\";\n\nexport const usePersistentNick = (): [\n string,\n React.Dispatch>\n] => {\n const [nick, setNick] = useState(() => {\n const persistedNick = window.localStorage.getItem(\"nick\");\n return persistedNick !== null ? persistedNick : generate();\n });\n useEffect(() => {\n localStorage.setItem(\"nick\", nick);\n }, [nick]);\n\n return [nick, setNick];\n};\n\nexport const useMessages = (params: UseMessagesParams): UseMessagesResult => {\n const { messages: newMessages } = useFilterMessages(params);\n const { messages: storedMessages } = useStoreMessages(params);\n const [localMessages, setLocalMessages] = useState([]);\n\n const pushMessages = (msgs: Message[]) => {\n if (!msgs || !msgs.length) {\n return;\n }\n setLocalMessages((prev) => [...prev, ...msgs]);\n };\n\n const allMessages = React.useMemo((): OrderedSet => {\n const allMessages = new OrderedSet(Message.cmp, Message.isEqual);\n\n const tomorrow = new Date();\n tomorrow.setDate(tomorrow.getDate() + 1);\n\n const _msgs = [...storedMessages, ...newMessages]\n .map(Message.fromWakuMessage)\n .filter((v): v is Message => !!v)\n .filter((v) => v.payloadAsUtf8 !== \"\")\n // Filter out messages that are \"sent\" tomorrow are they are likely to be flukes\n .filter((m) => m.timestamp.valueOf() < tomorrow.valueOf());\n allMessages.push(..._msgs);\n allMessages.push(...localMessages);\n\n return allMessages;\n }, [storedMessages, newMessages, localMessages]);\n\n return [allMessages, pushMessages];\n};\n\n// can be safely ignored\n// this is for experiments on waku side around new discovery options\nexport const useNodePeers = (node: undefined | LightNode) => {\n const [discoveredBootstrapPeers, setBootstrapPeers] = useState>(\n new Set()\n );\n const [connectedBootstrapPeers, setConnectedBootstrapPeers] = useState<\n Set\n >(new Set());\n const [discoveredPeerExchangePeers, setPeerExchangePeers] = useState<\n Set\n >(new Set());\n const [connectedPeerExchangePeers, setConnectedPeerExchangePeers] = useState<\n Set\n >(new Set());\n\n useEffect(() => {\n if (!node) return;\n\n const handleDiscoveryBootstrap = async (event: CustomEvent) => {\n (async () => {\n if (!(await isPeerDialable(event.detail, node))) return;\n\n setBootstrapPeers((peers) => new Set([...peers, event.detail]));\n })().catch((error) => console.error(error));\n };\n\n const handleConnectBootstrap = (event: CustomEvent) => {\n setConnectedBootstrapPeers((peers) => new Set([...peers, event.detail]));\n };\n\n const handleDiscoveryPeerExchange = (event: CustomEvent) => {\n (async () => {\n if (!(await isPeerDialable(event.detail, node))) return;\n\n setPeerExchangePeers((peers) => new Set([...peers, event.detail]));\n })().catch((error) => console.error(error));\n };\n\n const handleConnectPeerExchange = (event: CustomEvent) => {\n setConnectedPeerExchangePeers(\n (peers) => new Set([...peers, event.detail])\n );\n };\n\n const initHookData = async () => {\n const { CONNECTED, DISCOVERED } =\n await node.connectionManager.getPeersByDiscovery();\n\n setConnectedBootstrapPeers(\n new Set(CONNECTED[Tags.BOOTSTRAP].map((p) => p.id))\n );\n setConnectedPeerExchangePeers(\n new Set(CONNECTED[Tags.PEER_EXCHANGE].map((p) => p.id))\n );\n setBootstrapPeers(new Set(DISCOVERED[Tags.BOOTSTRAP].map((p) => p.id)));\n setPeerExchangePeers(\n new Set(DISCOVERED[Tags.PEER_EXCHANGE].map((p) => p.id))\n );\n\n node.libp2p.addEventListener(\"peer:disconnect\", (evt) => {\n const peerId = evt.detail;\n setConnectedBootstrapPeers((peers) => {\n peers.delete(peerId);\n return peers;\n });\n });\n node.connectionManager.addEventListener(\n EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP,\n handleDiscoveryBootstrap\n );\n node.connectionManager.addEventListener(\n EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP,\n handleConnectBootstrap\n );\n node.connectionManager.addEventListener(\n EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE,\n handleDiscoveryPeerExchange\n );\n node.connectionManager.addEventListener(\n EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE,\n handleConnectPeerExchange\n );\n };\n\n initHookData();\n\n return () => {\n node.connectionManager.removeEventListener(\n EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP,\n handleDiscoveryBootstrap\n );\n node.connectionManager.removeEventListener(\n EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP,\n handleConnectBootstrap\n );\n node.connectionManager.removeEventListener(\n EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE,\n handleDiscoveryPeerExchange\n );\n node.connectionManager.removeEventListener(\n EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE,\n handleConnectPeerExchange\n );\n };\n }, [node]);\n\n return {\n discoveredBootstrapPeers,\n connectedBootstrapPeers,\n discoveredPeerExchangePeers,\n connectedPeerExchangePeers,\n };\n};\n\n/**\n * Hook returns map of peers for different protocols.\n * If protocol is not implemented on the node peers are undefined.\n * @example\n * const { storePeers } = usePeers({ node });\n * @param {Waku} params.node - Waku node, if not set then no peers will be returned\n * @returns {Object} map of peers, if some of the protocols is not implemented then undefined\n */\nexport const usePeers = (params: UsePeersParams): UsePeersResults => {\n const { node } = params;\n const [peers, setPeers] = React.useState({});\n\n useEffect(() => {\n if (!node) {\n return;\n }\n\n const listener = async () => {\n // find all the peers that are connected for diff protocols\n const peerIds = node.libp2p.getPeers();\n const peers = await Promise.all(\n peerIds.map((id) => node.libp2p.peerStore.get(id))\n );\n\n setPeers({\n allConnected: peers.map((p) => p.id),\n storePeers: getPeerIdsForProtocol(node.store, peers),\n filterPeers: getPeerIdsForProtocol(node.filter, peers),\n lightPushPeers: getPeerIdsForProtocol(node.lightPush, peers),\n });\n };\n\n listener(); // populate peers before event is invoked\n node.libp2p.addEventListener(\"peer:identify\", listener);\n return () => {\n node.libp2p.removeEventListener(\"peer:identify\", listener);\n };\n }, [node, setPeers]);\n\n return peers;\n};\n\n// we only support websocket connections for now\nconst isPeerDialable = async (peerId: PeerId, node: LightNode) => {\n const peer = await node.libp2p.peerStore.get(peerId);\n if (!peer) return false;\n if (peer.addresses.length === 0) return false;\n const connectableMultiaddrs = peer.addresses.filter(({ multiaddr }) =>\n isMultiaddrConnectable(multiaddr.toString())\n );\n if (connectableMultiaddrs.length === 0) return false;\n\n return true;\n};\n\nconst isMultiaddrConnectable = (multiaddr: string) => {\n return multiaddr.includes(\"wss\") || multiaddr.includes(\"/tls/ws\");\n};\n","import React from \"react\";\nimport type {\n IDecodedMessage,\n IDecoder,\n IFilter,\n Unsubscribe,\n Waku,\n} from \"@waku/interfaces\";\n\nimport type { HookState } from \"./types\";\n\ntype AbstractFilterNode = Waku & {\n filter: IFilter;\n};\n\ntype UseFilterMessagesParams = {\n node: undefined | AbstractFilterNode;\n decoder: undefined | IDecoder;\n};\n\ntype UseFilterMessagesResult = HookState & {\n messages: IDecodedMessage[];\n};\n\n/**\n * Returns messages from Filter subscription and keeps them up to date\n * @example\n * const { isLoading, error, message } = useFilterMessages({node, decoder});\n * @param {Object} node - node that implements Filter, hook does nothing if undefined\n * @param {Object} decoder - decoder to use for subscribing, hook does nothing if undefined\n * @returns {Object} hook state (isLoading, error) and messages array\n */\nexport const useFilterMessages = (\n params: UseFilterMessagesParams,\n): UseFilterMessagesResult => {\n const { node, decoder } = params;\n\n const [error, setError] = React.useState(undefined);\n const [isLoading, setLoading] = React.useState(false);\n const [messages, setMessage] = React.useState([]);\n\n const pushMessage = React.useCallback(\n (message: IDecodedMessage): void => {\n if (!message) {\n return;\n }\n\n setMessage((prev) => [...prev, message]);\n },\n [setMessage],\n );\n\n React.useEffect(() => {\n if (!node || !decoder) {\n return;\n }\n\n let unsubscribe: null | Unsubscribe = null;\n setLoading(true);\n\n (node.filter.subscribe([decoder], pushMessage) as Promise)\n .then((unsubscribeFn) => {\n setLoading(false);\n unsubscribe = unsubscribeFn;\n })\n .catch((err) => {\n setLoading(false);\n setError(\n `Failed to subscribe to filer: ${err?.message || \"no message\"}`,\n );\n });\n\n return () => {\n unsubscribe?.();\n };\n }, [node, decoder, pushMessage, setError, setLoading]);\n\n return {\n error,\n messages,\n isLoading,\n };\n};\n","import React from \"react\";\nimport type {\n IDecodedMessage,\n IDecoder,\n IStoreSDK,\n StoreQueryOptions,\n Waku,\n} from \"@waku/interfaces\";\n\nimport type { HookState } from \"./types\";\n\ntype AbstractStoreNode = Waku & {\n store: IStoreSDK;\n};\n\ntype UseStoreMessagesParams = {\n node: undefined | AbstractStoreNode;\n decoder: undefined | IDecoder;\n options: StoreQueryOptions;\n};\n\ntype UseStoreMessagesResult = HookState & {\n messages: IDecodedMessage[];\n};\n\n/**\n * Hook for retrieving messages from Store protocol based on options\n * @example\n * const { isLoading, error, messages } = useStoreMessages({node, decoder, options});\n * @param {Object} node - node that implement Store, hook does nothing if undefined\n * @param {Object} decoder - decoder to use for getting messages, hook does nothing if undefined\n * @param {StoreQueryOptions} options - options to initiate query to get messages\n * @returns {Object} hook state (isLoading, error) and messages array\n */\nexport const useStoreMessages = (\n params: UseStoreMessagesParams,\n): UseStoreMessagesResult => {\n const { node, decoder, options } = params;\n\n const [error, setError] = React.useState(undefined);\n const [isLoading, setLoading] = React.useState(false);\n const [messages, setMessage] = React.useState([]);\n\n const pushMessage = React.useCallback(\n (newMessages: IDecodedMessage[]): void => {\n if (!newMessages || !newMessages.length) {\n return;\n }\n\n setMessage((prev) => [...prev, ...newMessages]);\n },\n [setMessage],\n );\n\n React.useEffect(() => {\n if (!node || !decoder) {\n return;\n }\n\n let cancelled = false;\n setLoading(true);\n\n Promise.resolve()\n .then(async () => {\n for await (const promises of node.store.queryGenerator(\n [decoder],\n options,\n )) {\n if (cancelled) {\n return;\n }\n\n const messagesRaw = await Promise.all(promises);\n const filteredMessages = messagesRaw.filter(\n (v): v is IDecodedMessage => !!v,\n );\n\n pushMessage(filteredMessages);\n }\n\n setLoading(false);\n })\n .catch((err) => {\n setLoading(false);\n setError(\n `Failed to query messages from store: ${\n err?.message || \"no message\"\n }`,\n );\n });\n\n return () => {\n cancelled = true;\n };\n // TODO: missing dependency on options, it will prevent consecutive update if options change\n }, [node, decoder, pushMessage, setError, setLoading]);\n\n return {\n error,\n isLoading,\n messages,\n };\n};\n","import type { LightNode } from \"@waku/interfaces\";\nimport ChatList from \"./ChatList\";\nimport MessageInput from \"./MessageInput\";\nimport { useWaku, useContentPair, useLightPush } from \"@waku/react\";\nimport { ChatMessage } from \"./chat_message\";\nimport { useNodePeers, usePeers } from \"./hooks\";\nimport type { RoomProps } from \"./types\";\n\nexport default function Room(props: RoomProps) {\n const { node } = useWaku();\n const { encoder } = useContentPair();\n const { push: onPush } = useLightPush({ node, encoder });\n\n const {\n connectedBootstrapPeers,\n connectedPeerExchangePeers,\n discoveredBootstrapPeers,\n discoveredPeerExchangePeers,\n } = useNodePeers(node);\n const { allConnected, storePeers, filterPeers, lightPushPeers } = usePeers({\n node,\n });\n\n const onSend = async (text: string) => {\n if (!onPush || !text) {\n return;\n }\n\n if (text.startsWith(\"/\")) {\n props.commandHandler(text);\n } else {\n const timestamp = new Date();\n const chatMessage = ChatMessage.fromUtf8String(\n timestamp,\n props.nick,\n text\n );\n const payload = chatMessage.encode();\n\n await onPush({ payload, timestamp });\n }\n };\n\n const allConnectedLength = orZero(allConnected?.length);\n const lightPushPeersLength = orZero(lightPushPeers?.length);\n const filterPeersLength = orZero(filterPeers?.length);\n const storePeersLength = orZero(storePeers?.length);\n\n return (\n
\n
\n
\n
Peers Connected: {allConnectedLength}
\n
Store: {storePeersLength}
\n
Filter: {filterPeersLength}
\n
Light Push: {lightPushPeersLength}
\n
\n
Waku v2 Web Chat
\n
\n
\n Peers Discovered:{\" \"}\n {discoveredBootstrapPeers.size + discoveredPeerExchangePeers.size}\n
\n
\n Bootstrap: {discoveredBootstrapPeers.size} Peer Exchange:{\" \"}\n {discoveredPeerExchangePeers.size}\n
\n
\n Peers Connected:{\" \"}\n {connectedBootstrapPeers.size + connectedPeerExchangePeers.size}\n
\n
\n Bootstrap: {connectedBootstrapPeers.size} Peer Exchange:{\" \"}\n {connectedPeerExchangePeers.size}\n
\n
\n
\n \n \n
\n );\n}\n\nfunction orZero(value: undefined | number): number {\n return value || 0;\n}\n","import handleCommand from \"./command\";\nimport Room from \"./Room\";\nimport { Message } from \"./Message\";\nimport { PageDirection, LightNode } from \"@waku/interfaces\";\n\nimport { useWaku, useContentPair } from \"@waku/react\";\n\nimport { useMessages, usePersistentNick } from \"./hooks\";\n\nconst startTime = new Date();\n// Only retrieve a week of history\nstartTime.setTime(Date.now() - 1000 * 60 * 60 * 24 * 7);\nconst endTime = new Date();\n\nexport default function App() {\n const { node } = useWaku();\n const { decoder } = useContentPair();\n const [messages, pushLocalMessages] = useMessages({\n node,\n decoder,\n options: {\n pageSize: 5,\n pageDirection: PageDirection.FORWARD,\n timeFilter: {\n startTime,\n endTime,\n },\n },\n });\n\n const [nick, setNick] = usePersistentNick();\n\n const onCommand = (text: string): void => {\n handleCommand(text, node, setNick).then(({ command, response }) => {\n const commandMessages = response.map((msg) => {\n return Message.fromUtf8String(command, msg);\n });\n pushLocalMessages(commandMessages);\n });\n };\n\n return (\n \n \n
\n );\n}\n","import React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport { LightNodeProvider, ContentPairProvider } from \"@waku/react\";\nimport \"./index.css\";\n\nimport App from \"./App\";\nimport { CONTENT_TOPIC } from \"./config\";\nimport { Protocols } from \"@waku/interfaces\";\n\nReactDOM.render(\n \n \n \n \n \n \n ,\n document.getElementById(\"root\")\n);\n","export const CONTENT_TOPIC = \"/toy-chat/2/huilong/proto\";\n"],"names":["module","exports","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","charAt","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","undefined","Error","test","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","factory","Float32Array","f32","f8b","Uint8Array","le","writeFloat_f32_cpy","val","buf","pos","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","writeFloat_ieee754","writeUint","sign","isNaN","round","exponent","floor","log","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","f64","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","inquire","moduleName","mod","eval","replace","Object","keys","e","alloc","size","SIZE","MAX","slab","call","utf8","len","read","write","c1","c2","formatArgs","useColors","namespace","humanize","diff","color","lastC","match","save","namespaces","storage","setItem","removeItem","error","load","r","getItem","process","DEBUG","window","type","__nwjs","navigator","userAgent","toLowerCase","document","documentElement","style","WebkitAppearance","console","firebug","exception","table","parseInt","RegExp","$1","localStorage","localstorage","destroy","warned","warn","colors","debug","require","formatters","v","JSON","stringify","message","env","createDebug","prevTime","namespacesCache","enabledCache","enableOverride","_len","_key","enabled","self","curr","Number","Date","ms","prev","coerce","unshift","format","formatter","selectColor","extend","defineProperty","enumerable","configurable","get","set","init","delimiter","newDebug","toNamespace","regexp","toString","substring","default","stack","disable","names","map","skips","enable","split","name","forEach","key","hash","abs","Denque","array","options","_capacity","capacity","_head","_tail","isArray","_fromArray","_capacityMask","_list","peekAt","peek","peekFront","peekBack","item","_growArray","pop","shift","head","_shrinkArray","tail","removeOne","k","remove","count","removed","del_count","toArray","clear","temp","arg_len","arguments_index","leng","isEmpty","_copyArray","_nextPowerOf2","fullCopy","src","dest","newList","num","nextPow2","max","assign","obj","props","value","code","TypeError","_","ErrClass","create","getPrototypeOf","event_iterator_1","EventIterator","EventQueue","constructor","pullQueue","pushQueue","eventHandlers","isPaused","isStopped","resolution","done","placeholder","highWaterMark","highWater","stop","fail","rejection","catch","then","removeCallback","Symbol","asyncIterator","next","result","lowWaterMark","lowWater","return","listen","queue","event","freeze","has","hasOwnProperty","prefix","Events","EE","context","once","addListener","emitter","listener","_events","_eventsCount","clearEvent","__proto__","eventNames","events","getOwnPropertySymbols","concat","handlers","l","ee","listenerCount","a1","a2","a3","a4","a5","removeListener","removeAllListeners","prefixed","cache","_cache","update","root","HI_BASE32_NO_NODE_JS","versions","node","global","COMMON_JS","HI_BASE32_NO_COMMON_JS","AMD","define","BASE32_ENCODE_CHAR","BASE32_DECODE_CHAR","blocks","throwInvalidUtf8","position","partial","substr","decodeAsBytes","base32Str","v1","v2","v3","v4","v5","v6","v7","v8","bytes","remain","asciiOnly","str","followingChars","toUtf8String","indexOf","input","notString","ArrayBuffer","encodeBytes","encodeAscii","encodeUtf8","asBytes","base32","electron","INPUT_ERROR","WINDOW","JS_SHA3_NO_WINDOW","WEB_WORKER","JS_SHA3_NO_NODE_JS","JS_SHA3_NO_COMMON_JS","ARRAY_BUFFER","JS_SHA3_NO_ARRAY_BUFFER","HEX_CHARS","CSHAKE_PADDING","SHIFT","RC","BITS","SHAKE_BITS","OUTPUT_TYPES","CSHAKE_BYTEPAD","isView","JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW","formatMessage","empty","cloneArray","newArray","createOutputMethod","bits","padding","outputType","Keccak","createShakeOutputMethod","outputBits","createCshakeOutputMethod","s","methods","createKmacOutputMethod","createOutputMethods","method","createMethod","algorithms","w","bytepad","Kmac","methodNames","algorithm","methodName","newMethodName","reset","finalized","block","blockCount","byteCount","outputBlocks","extraBytes","isString","lastByteIndex","f","x","right","o","encodeString","strs","paddingBytes","zeros","finalize","hex","arrayBuffer","Uint32Array","digest","h","c0","c3","c4","c5","c6","c7","c8","c9","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","b16","b17","b18","b19","b20","b21","b22","b23","b24","b25","b26","b27","b28","b29","b30","b31","b32","b33","b34","b35","b36","b37","b38","b39","b40","b41","b42","b43","b44","b45","b46","b47","b48","b49","isOptionObject","propertyIsEnumerable","object","writable","globalThis","defaultMergeOptions","concatArrays","ignoreUndefined","getEnumerableOwnPropertyKeys","symbols","symbol","clone","cloneOptionObject","mergeKeys","merged","source","config","merge","resultIndex","indices","filter","includes","option","m","d","y","plural","msAbs","isPlural","exec","parseFloat","parse","isFinite","long","fmtLong","fmtShort","Netmask","atob","chr","chr0","chrA","chra","ip2long","long2ip","ip","ref","base","dmax","net","mask","maskLong","error1","bitmask","netLong","hostmask","first","last","broadcast","contains","lastLong","forge","registerAlgorithm","mode","cipher","aes","Algorithm","startEncrypting","iv","output","_createCipher","decrypt","createEncryptionCipher","startDecrypting","createDecryptionCipher","initialize","blockSize","encrypt","inBlock","outBlock","_updateBlock","_w","_init","tmp","util","createBuffer","putByte","getInt32","encryptOp","_expandKey","modes","ecb","cbc","cfb","ofb","ctr","gcm","sbox","isbox","rcon","mix","imix","Nb","xtime","e2","e4","e8","sx","sx2","me","ime","ei","iNk","Nk","m0","m1","m2","m3","wnew","wi","sub","a","Nr","toUpperCase","createDecipher","createCipher","ByteBuffer","asn1","_checkBufferLength","remaining","available","requested","Class","UNIVERSAL","APPLICATION","CONTEXT_SPECIFIC","PRIVATE","Type","NONE","BOOLEAN","INTEGER","BITSTRING","OCTETSTRING","NULL","OID","ODESC","EXTERNAL","REAL","ENUMERATED","EMBEDDED","UTF8","ROID","SEQUENCE","SET","PRINTABLESTRING","IA5STRING","UTCTIME","GENERALIZEDTIME","BMPSTRING","tagClass","constructed","composed","bitStringContents","original","copy","excludeBitStringContents","equals","obj1","obj2","equal","includeBitStringContents","getBerValueLength","getByte","getInt","_fromDer","depth","longFormBytes","_getValueLength","strict","getBytes","decodeBitStrings","savedRead","savedRemaining","unused","used","tc","ex","getInt16","asn1Options","fromDer","parseAllBytes","toDer","useBitStringContents","putBytes","putBuffer","putInt16","lenBytes","oidToDer","oid","valueBytes","values","derToOid","utcTimeToDate","utc","date","year","MM","DD","hh","mm","ss","setUTCFullYear","setUTCHours","setTime","generalizedTimeToDate","gentime","YYYY","fff","isUTC","setFullYear","setHours","dateToUtcTime","rval","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","dateToGeneralizedTime","integerToDer","putSignedInt","integer","derToInteger","getSignedInt","validate","capture","errors","optional","captureAsn1","captureBitStringContents","captureBitStringValue","_nonLatinRegex","prettyPrint","level","indentation","indent","IA5String","subvalues","pki","oids","bytesToHex","decodeUtf8","api","_reverseAlphabets","alphabet","maxline","digits","carry","at","_encodeWithByteBuffer","regex","Buffer","from","reverse","getAlgorithm","BlockCipher","_finish","_input","_op","_decrypt","opts","compact","finish","pad","unpad","overflow","afterFinish","transformIV","ints","inc32","from64To32","_ints","_inBlock","_outBlock","putInt32","fillWithByte","truncate","_prev","_iv","_partialBlock","_partialOutput","_partialBytes","inputLength","partialBytes","_R","additionalData","_cipherLength","_tagLength","tagLength","_tag","tag","_hashBlock","_hashSubkey","componentBits","_m","generateHashTable","ivLength","_j0","ghash","_aDataLength","_s","lengths","multiply","z_i","v_i","out","lsb","tableMultiply","z","x_i","ah","multiplier","perInt","shft","generateSubHashTable","mid","half","m_i","m_j","des","_keys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","iterations","shifts","left","lefttmp","righttmp","_createKeys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","looping","endloop","loopinc","right1","right2","usePureJavaScript","hmac","_md","_ipadding","_opadding","md","keylen","blockLength","inner","getMac","dbits","jsbn","BigInteger","data","fromNumber","fromString","nbi","am3","xl","xh","am","appName","DB","DM","DV","FV","F1","F2","rr","vv","BI_RM","BI_RC","int2char","intAt","nbv","fromInt","nbits","Classic","Montgomery","mp","invDigit","mpl","mph","um","mt2","op_and","op_or","op_xor","op_andnot","lbit","cbit","NullExp","nNop","Barrett","r2","q3","ONE","dlShiftTo","mu","divide","convert","compareTo","revert","reduce","divRemTo","mulTo","multiplyTo","sqrTo","squareTo","ZERO","subTo","copyTo","u0","clamp","drShiftTo","fromRadix","mi","sh","lShiftTo","bs","cbs","bm","ds","rShiftTo","min","q","pm","pt","ts","nsh","ys","y0","yt","d1","d2","qd","isEven","exp","g","negate","toRadix","km","bitLength","modPowInt","multiplyUpperTo","multiplyLowerTo","dAddOffset","lowprimes","lplim","chunkSize","signum","cs","intValue","dMultiply","testBit","bitwiseTo","shiftLeft","isProbablePrime","nextBytes","op","changeBit","addTo","modInt","millerRabin","n1","subtract","getLowestSetBit","shiftRight","prng","random","modPow","byteValue","shortValue","toByteArray","and","or","xor","andNot","not","bitCount","setBit","clearBit","flipBit","add","remainder","divideAndRemainder","k1","g2","is1","modInverse","ac","u","gcd","_IN","id","_I_","pbe","encryptedPrivateKeyValidator","PBES2AlgorithmsValidator","pkcs12PbeParamsValidator","prfOidToMessageDigest","prfOid","prfAlgorithm","supported","prfAlgorithmToMessageDigest","sha512","encryptPrivateKeyInfo","password","saltSize","dkLen","encryptionAlgorithm","encryptedData","salt","getBytesSync","countBytes","ivLen","encOid","cipherFn","dk","pkcs5","pbkdf2","hexToBytes","createPbkdf2Params","saltBytes","generatePkcs12Key","decryptPrivateKeyInfo","encryptionOid","getCipher","encryptionParams","encrypted","encryptedPrivateKeyToPem","epki","msg","body","pem","encryptedPrivateKeyFromPem","headerType","procType","encryptRsaPrivateKey","rsaKey","legacy","wrapRsaPrivateKey","privateKeyToAsn1","opensslDeriveBytes","version","dekInfo","parameters","decryptRsaPrivateKey","rc2","privateKeyFromAsn1","iter","sha1","digestLength","passBuf","D","Slen","S","Plen","P","I","B","Inew","setAt","getCipherForPBES2","getCipherForPKCS12PBE","supportedOids","kdfOid","kdfSalt","kdfIterationCount","encIv","dIvLen","md5","digests","crypto","isNodejs","callback","pbkdf2Sync","hLen","prf","u_c","u_c1","int32ToBytes","xorBytes","outer","setImmediate","foldHeader","header","insertSpace","candidate","insert","ltrim","contentDomain","headers","encode64","rMessage","rHeader","rCRLF","decode64","lines","li","line","nl","vi","pkcs1","rsa_mgf1","seed","maskLength","encode_rsa_oaep","label","mgf1Md","mgf1","keyLength","maxLength","lHash","PS","PS_length","seedLength","dbMask","maskedDB","seedMask","decode_rsa_oaep","em","expectedLength","maskedSeed","db","lHashPrime","in_ps","prime","GCD_30_DELTA","THIRTY","generateProbablePrime","rng","Worker","primeincFindPrimeWithoutWorkers","generateRandom","numWorkers","workers","workLoad","range","workerScript","estimateCores","cores","generate","addEventListener","workerMessage","found","terminate","target","postMessage","primeincFindPrimeWithWorkers","primeincFindPrime","mrTests","getMillerRabinTests","millerRabinTests","maxBlockTime","_primeinc","deltaIdx","bits1","_crypto","plugin","time","reseeds","generated","keyBytes","pools","_reseedSync","messageLength","_seed","needed","collect","seedFileSync","_2powK","seedBytes","formatKey","formatSeed","defaultSeedFile","getRandomValues","globalScope","msCrypto","arr","entropy","QuotaExceededError","pool","generateSync","increment","nextTick","seedFile","_reseed","randomBytes","collectInt","registerWorker","worker","removeEventListener","jQuery","prng_aes","_prng_aes_output","_prng_aes_buffer","spawnPrng","sha256","_ctx","_navBytes","mousemove","clientX","clientY","keypress","charCode","createInstance","piTable","rol","word","ror","expandKey","effKeyBits","L","T","T1","T8","TM","mixRound","mashRound","_output","K","getInt16Le","R","runPlan","plan","putInt16Le","ptr","rsa","privateKeyValidator","rsaPrivateKeyValidator","rsaPublicKeyValidator","publicKeyValidator","digestInfoValidator","emsaPkcs1v15encode","oidBytes","digestInfo","digestAlgorithm","_modPow","pub","dP","dQ","qInv","xp","xq","_encodePkcs1_v1_5","bt","eb","padByte","padNum","numZeros","padBytes","_decodePkcs1_v1_5","ml","_bnToBytes","_getMillerRabinTests","_detectNodeCrypto","_detectSubtleCrypto","subtle","_detectSubtleMsCrypto","_intToUint8Array","toHex","yhex","ed","expected","xhex","createKeyPairGenerationState","state","eInt","qBits","pBits","pqState","stepKeyPairGenerationState","t2","t1","total","p1","q1","phi","privateKey","setPrivateKey","publicKey","setPublicKey","generateKeyPair","modulusLength","publicExponent","publicKeyEncoding","privateKeyEncoding","priv","privateKeyFromPem","publicKeyFromPem","generateKey","pair","exportKey","pkcs8","setRsaPublicKey","genOp","oncomplete","exportOp","onerror","keypair","generateKeyPairSync","getPrime","_generateKeyPair","scheme","schemeOptions","signature","_parseAllDigestBytes","verify","algorithmIdentifier","md2","sha224","sha384","setRsaPrivateKey","rsaEncryption","privateKeyModulus","privateKeyPublicExponent","privateKeyPrivateExponent","privateKeyPrime1","privateKeyPrime2","privateKeyExponent1","privateKeyExponent2","privateKeyCoefficient","privateKeyToRSAPrivateKey","publicKeyFromAsn1","publicKeyOid","rsaPublicKey","publicKeyModulus","publicKeyExponent","publicKeyToAsn1","publicKeyToSubjectPublicKeyInfo","publicKeyToRSAPublicKey","_initialized","_padding","fillString","_state","fullMessageLength","messageLengthSize","messageLength64","int32s","h0","h1","h2","h3","h4","encoding","_update","finalBlock","s2","_k","h5","h6","h7","s0","maj","_states","_h","messageLength128","hlen","t1_hi","t1_lo","t2_hi","t2_lo","s0_hi","s0_lo","s1_hi","ch_hi","maj_hi","maj_lo","a_hi","a_lo","b_hi","b_lo","c_hi","c_lo","d_hi","d_lo","e_hi","e_lo","f_hi","f_lo","g_hi","g_lo","h_hi","h_lo","w2","w7","w15","w16","baseN","_checkBitsParam","ByteStringBuffer","isArrayBuffer","isArrayBufferView","_constructedStringLength","browser","setTimeout","callbacks","stopPropagation","MutationObserver","now","attr","div","createElement","observe","attributes","oldSetImmediate","setAttribute","byteLength","_optimizeConstructedString","putString","putInt24","putInt24Le","putInt32Le","putInt","getInt24","getInt24Le","getInt32Le","DataBuffer","readOffset","growSize","DataView","byteOffset","writeOffset","accommodate","amount","dst","setUint8","view","binary","raw","Uint16Array","text","utf16","setInt16","setInt8","setInt32","getInt8","getUint8","s1","s3","_base64","_base64Idx","_base58","chr1","chr2","chr3","enc1","enc2","enc3","enc4","unescape","encodeURIComponent","decodeURIComponent","escape","base58","subarray","deflate","inflate","_setStorageObject","_getStorageObject","_setItem","_getItem","_removeItem","prop","_clearItems","_callStorageFunction","func","location","idx","clearItems","part","re","argi","lastIndex","formatNumber","number","decimals","dec_point","thousands_sep","toFixed","formatSize","bytesFromIP","bytesFromIPv4","bytesFromIPv6","blanks","bytesToIP","bytesToIPv4","bytesToIPv6","zeroGroups","zeroMaxGroup","group","hardwareConcurrency","Blob","blobUrl","URL","createObjectURL","st","et","sample","samples","avg","revokeObjectURL","results","overlaps","r1","overlap","propIsEnumerable","test1","getOwnPropertyNames","test2","test3","letter","shouldUseNative","to","toObject","Reader","BufferReader","LongBits","indexOutOfRange","reader","writeLength","RangeError","create_array","isBuffer","readLongVarint","readFixed32_end","readFixed64","_slice","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","nativeBuffer","skip","skipType","wireType","_configure","BufferReader_","Long","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","zero","toNumber","zzEncode","zeroHash","low","high","unsigned","toLong","Boolean","fromHash","toHash","part0","part1","part2","ifNotSet","newError","CustomError","properties","captureStackTrace","asPromise","isNode","emptyArray","emptyObject","isInteger","isObject","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","newBuffer","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","lcFirst","ProtocolError","oneOfGetter","fieldNames","fieldMap","oneOfSetter","toJSONOptions","longs","enums","json","allocUnsafe","Writer","BufferWriter","Op","noop","State","writer","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","fork","ldelim","BufferWriter_","writeStringBuffer","writeBytesBuffer","BufferSourceConverter","toArrayBuffer","toUint8Array","toView","isBufferSource","isEqual","aView","bView","buffers","Function","res","STRING_TYPE","HEX_REGEX","BASE64_REGEX","BASE64URL_REGEX","Utf8Converter","uintArray","encodedString","Utf16Converter","littleEndian","dataView","getUint16","setUint16","Convert","isHex","isBase64","isBase64Url","ToString","enc","ToUtf8String","ToBinary","ToHex","ToBase64","ToBase64Url","FromString","FromUtf8String","FromBinary","FromHex","FromBase64","FromBase64Url","btoa","formatted","formatString","base64url","Base64Padding","DEFAULT_UTF8_ENCODING","stringLength","resultView","byte","hexString","ToUtf16String","FromUtf16String","padCount","aa","ba","Set","ca","da","ea","fa","ha","ia","ja","ka","acceptsBooleans","attributeName","attributeNamespace","mustUseProperty","propertyName","sanitizeURL","removeEmptyString","oa","pa","qa","ma","na","la","removeAttribute","setAttributeNS","xlinkHref","ra","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","sa","ta","ua","wa","xa","ya","za","Aa","Ba","Ca","Da","Ea","Fa","Ga","Ha","Ia","Ja","for","E","Ma","Ka","iterator","La","Na","trim","Oa","Pa","prepareStackTrace","Reflect","construct","displayName","Qa","render","_render","Ra","$$typeof","_context","_payload","Sa","Ta","nodeName","Va","_valueTracker","getOwnPropertyDescriptor","getValue","setValue","stopTracking","Ua","Wa","checked","Xa","activeElement","Ya","defaultChecked","defaultValue","_wrapperState","initialChecked","Za","initialValue","controlled","$a","ab","bb","cb","ownerDocument","children","Children","fb","selected","defaultSelected","disabled","gb","dangerouslySetInnerHTML","hb","ib","jb","textContent","kb","html","mathml","svg","lb","mb","nb","ob","namespaceURI","innerHTML","valueOf","firstChild","removeChild","appendChild","MSApp","execUnsafeLocalFunction","pb","lastChild","nodeType","nodeValue","qb","animationIterationCount","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth","rb","sb","tb","setProperty","ub","menuitem","area","br","col","embed","hr","img","keygen","link","meta","param","track","wbr","vb","wb","is","xb","srcElement","correspondingUseElement","parentNode","yb","zb","Ab","Bb","Cb","stateNode","Db","Eb","Fb","Gb","Hb","Ib","Jb","Kb","Lb","Mb","Ob","Pb","Qb","Rb","onError","Sb","Tb","Ub","Vb","Wb","Xb","Zb","alternate","flags","$b","memoizedState","dehydrated","cc","child","sibling","current","bc","dc","ec","fc","gc","hc","ic","jc","kc","lc","mc","nc","Map","oc","pc","qc","rc","blockedOn","domEventName","eventSystemFlags","nativeEvent","targetContainers","sc","delete","pointerId","vc","wc","lanePriority","unstable_runWithPriority","priority","hydrate","containerInfo","xc","yc","zc","Ac","Bc","unstable_scheduleCallback","unstable_NormalPriority","Cc","Dc","Ec","animationend","animationiteration","animationstart","transitionend","Fc","Gc","Hc","animation","transition","Ic","Jc","Kc","Lc","Mc","Nc","Oc","Pc","Qc","unstable_now","F","Rc","Uc","pendingLanes","expiredLanes","suspendedLanes","pingedLanes","Vc","entangledLanes","entanglements","Wc","Xc","Yc","Zc","$c","eventTimes","clz32","bd","cd","dd","unstable_UserBlockingPriority","fd","gd","hd","uc","jd","kd","ld","nd","od","keyCode","pd","rd","_reactName","_targetInst","currentTarget","isDefaultPrevented","defaultPrevented","returnValue","isPropagationStopped","preventDefault","cancelBubble","persist","isPersistent","wd","xd","yd","sd","eventPhase","bubbles","cancelable","timeStamp","isTrusted","td","ud","detail","vd","Ad","screenX","screenY","pageX","pageY","ctrlKey","shiftKey","altKey","metaKey","getModifierState","zd","button","buttons","relatedTarget","fromElement","toElement","movementX","movementY","Bd","Dd","dataTransfer","Fd","Hd","animationName","elapsedTime","pseudoElement","Id","clipboardData","Jd","Ld","Md","Esc","Spacebar","Left","Up","Right","Down","Del","Win","Menu","Apps","Scroll","MozPrintableKey","Nd","Od","Alt","Control","Meta","Shift","Pd","Qd","repeat","locale","which","Rd","Td","width","height","pressure","tangentialPressure","tiltX","tiltY","twist","pointerType","isPrimary","Vd","touches","targetTouches","changedTouches","Xd","Yd","deltaX","wheelDeltaX","deltaY","wheelDeltaY","wheelDelta","deltaZ","deltaMode","Zd","$d","ae","be","documentMode","ce","de","fe","ge","he","ie","datetime","email","month","search","tel","url","week","ne","oe","pe","qe","se","te","ue","ve","we","xe","ye","ze","oninput","Ae","detachEvent","Be","Ce","attachEvent","De","Ee","Fe","He","Ie","Je","Ke","Le","nextSibling","Me","compareDocumentPosition","Ne","HTMLIFrameElement","contentWindow","href","Oe","contentEditable","Pe","Qe","Re","Se","Te","Ue","selectionStart","selectionEnd","anchorNode","defaultView","getSelection","anchorOffset","focusNode","focusOffset","Ve","We","Xe","Ye","Ze","Yb","instance","G","$e","af","bf","cf","df","passive","ef","ff","parentWindow","gf","hf","J","Q","je","char","ke","jf","kf","lf","mf","autoFocus","nf","__html","of","pf","clearTimeout","qf","rf","sf","previousSibling","tf","vf","wf","xf","yf","zf","Af","Bf","H","Cf","M","N","Df","Ef","contextTypes","__reactInternalMemoizedUnmaskedChildContext","__reactInternalMemoizedMaskedChildContext","Ff","childContextTypes","Gf","Hf","If","getChildContext","Jf","__reactInternalMemoizedMergedChildContext","Kf","Lf","Mf","Nf","Of","Pf","unstable_cancelCallback","Qf","unstable_shouldYield","Rf","unstable_requestPaint","Sf","Tf","unstable_getCurrentPriorityLevel","Uf","unstable_ImmediatePriority","Vf","Wf","Xf","unstable_LowPriority","Yf","unstable_IdlePriority","Zf","$f","ag","bg","cg","dg","O","eg","fg","gg","hg","ig","jg","kg","ReactCurrentBatchConfig","lg","defaultProps","mg","ng","og","pg","qg","rg","_currentValue","sg","childLanes","tg","dependencies","firstContext","lanes","ug","vg","observedBits","responders","wg","xg","updateQueue","baseState","firstBaseUpdate","lastBaseUpdate","shared","effects","yg","zg","eventTime","lane","payload","Ag","Bg","Cg","A","C","Dg","Eg","Fg","Component","refs","Gg","Kg","isMounted","_reactInternals","enqueueSetState","Hg","Ig","Jg","enqueueReplaceState","enqueueForceUpdate","Lg","shouldComponentUpdate","isPureReactComponent","Mg","contextType","updater","Ng","componentWillReceiveProps","UNSAFE_componentWillReceiveProps","Og","getDerivedStateFromProps","getSnapshotBeforeUpdate","UNSAFE_componentWillMount","componentWillMount","componentDidMount","Pg","Qg","_owner","_stringRef","Rg","Sg","lastEffect","nextEffect","firstEffect","Tg","Ug","elementType","Vg","implementation","Wg","Xg","Yg","Zg","$g","bh","ch","dh","eh","tagName","fh","gh","ih","memoizedProps","revealOrder","jh","kh","lh","mh","nh","oh","pendingProps","ph","qh","rh","th","uh","_workInProgressVersionPrimary","vh","ReactCurrentDispatcher","wh","yh","zh","Ah","Bh","Ch","Dh","Eh","Fh","Gh","Hh","baseQueue","Ih","Jh","Kh","lastRenderedReducer","action","eagerReducer","eagerState","lastRenderedState","dispatch","Lh","Mh","_getVersion","_source","mutableReadLanes","Nh","U","useState","getSnapshot","subscribe","useEffect","setSnapshot","Oh","Ph","Qh","Rh","deps","Sh","Th","Uh","Vh","Wh","Xh","Yh","Zh","$h","ai","bi","ci","di","readContext","useCallback","useContext","useImperativeHandle","useLayoutEffect","useMemo","useReducer","useRef","useDebugValue","useDeferredValue","useTransition","useMutableSource","useOpaqueIdentifier","unstable_isNewReconciler","uf","ReactCurrentOwner","fi","gi","ii","ji","compare","ki","baseLanes","ni","oi","pi","UNSAFE_componentWillUpdate","componentWillUpdate","componentDidUpdate","qi","getDerivedStateFromError","ri","pendingContext","Bi","Ci","Di","Ei","si","retryLane","ti","fallback","unstable_avoidThisFallback","ui","unstable_expectedLoadTime","xi","yi","zi","isBackwards","rendering","renderingStartTime","tailMode","Ai","Fi","Gi","wasMultiple","multiple","onClick","onclick","createElementNS","createTextNode","V","Hi","Ii","W","Ji","Ki","Li","Mi","Ni","Oi","WeakMap","Pi","element","Qi","Ri","Si","componentDidCatch","Ti","componentStack","Ui","WeakSet","Vi","Wi","Xi","__reactInternalSnapshotBeforeUpdate","Yi","Zi","$i","focus","aj","display","bj","onCommitFiberUnmount","componentWillUnmount","cj","dj","ej","fj","gj","hj","insertBefore","_reactRootContainer","ij","jj","kj","lj","mj","nj","oj","pj","X","Y","qj","rj","sj","tj","uj","vj","wj","ck","Z","xj","yj","zj","Aj","Bj","Cj","Dj","Ej","Fj","Gj","Hj","Ij","Jj","Sc","Kj","Lj","Mj","callbackNode","expirationTimes","callbackPriority","Tc","Nj","Oj","Pj","Qj","Rj","Sj","Tj","finishedWork","finishedLanes","Uj","timeoutHandle","Wj","Xj","pingCache","Yj","Zj","va","ak","bk","rangeCount","focusedElem","selectionRange","ek","createRange","setStart","removeAllRanges","addRange","setEnd","scrollLeft","top","scrollTop","onCommitFiberRoot","fk","gk","ik","isReactComponent","pendingChildren","jk","mutableSourceEagerHydrationData","lk","mk","nk","ok","qk","hydrationOptions","mutableSources","_internalRoot","rk","tk","hasAttribute","sk","uk","kk","hk","_calculateChangedBits","unstable_observedBits","unmount","querySelectorAll","form","Vj","vk","wk","findFiberByHostInstance","bundleType","rendererPackageName","xk","rendererConfig","overrideHookState","overrideHookStateDeletePath","overrideHookStateRenamePath","overrideProps","overridePropsDeletePath","overridePropsRenamePath","setSuspenseHandler","scheduleUpdate","currentDispatcherRef","findHostInstanceByFiber","findHostInstancesForRefresh","scheduleRefresh","scheduleRoot","setRefreshHandler","getCurrentFiber","__REACT_DEVTOOLS_GLOBAL_HOOK__","yk","isDisabled","supportsFiber","inject","createPortal","findDOMNode","flushSync","unmountComponentAtNode","unstable_batchedUpdates","unstable_createPortal","unstable_renderSubtreeIntoContainer","checkDCE","__self","__source","jsx","jsxs","Fragment","StrictMode","Profiler","Suspense","setState","forceUpdate","_status","_result","IsSomeRendererActing","only","PureComponent","cloneElement","createContext","_currentValue2","_threadCount","Provider","Consumer","createFactory","createRef","forwardRef","isValidElement","lazy","memo","performance","MessageChannel","unstable_forceFrameRate","cancelAnimationFrame","requestAnimationFrame","port2","port1","onmessage","sortIndex","startTime","expirationTime","priorityLevel","unstable_Profiling","unstable_continueExecution","unstable_getFirstCallbackNode","unstable_next","unstable_pauseExecution","delay","unstable_wrapCallback","Nouns","Adjectives","data_1","generator_1","counter","REST","MSB","MAX_SAFE_INTEGER","oldOffset","INT","MSBALL","encodingLength","N1","N2","N3","N4","N5","N6","N7","N8","N9","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","leafPrototypes","getProto","__esModule","ns","def","definition","toStringTag","encodeUint8Array","decodeUint8Array","encodeUint8ArrayList","decodeUint8ArrayList","d8b","MAX_SAFE_NUMBER_INTEGER","BigInt","MIN_SAFE_NUMBER_INTEGER","MIN_SAFE_INTEGER","toBigInt","fromBigInt","negative","TWO_32","readFixed32End","Uint8ArrayReader","int64Number","int64String","uint64Number","uint64String","sint64Number","sint64String","fixed64Number","fixed64String","sfixed64Number","sfixed64String","decodeMessage","codec","createReader","ALPHABET","BASE_MAP","BASE","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","it3","it4","vch","pbegin","pend","b58","it1","it2","Encoder","baseEncode","Decoder","baseDecode","prefixCodePoint","codePointAt","decoder","ComposedDecoder","decoders","Codec","encoder","_ref","baseX","_ref2","basex","rfc4648","_ref3","bitsPerChar","codes","written","SyntaxError","base10","base16","base16upper","base2","alphabetBytesToChars","alphabetCharsToBytes","base256emoji","byts","byt","base32upper","base32pad","base32padupper","base32hex","base32hexupper","base32hexpad","base32hexpadupper","base32z","base36","base36upper","base58btc","base58flickr","base64pad","base64urlpad","base8","identity","TextDecoder","TextEncoder","textEncoder","textDecoder","encode_1","REST$1","MSB$1","encodeTo","int","varint","sizeOffset","digestOffset","Digest","Hasher","sha","async","bases","identityBase","createCodec","ascii","latin1","bufferPool","Uint8ArrayWriter","writeVarint32","super","uint8ArrayFromString","encodeMessage","lengthDelimited","CODEC_TYPES","RateLimitProof","WakuMessage","FilterRequest","MessagePush","FilterRpc","TopicOnlyMessage","FilterSubscribeRequest","FilterSubscribeResponse","PushRequest","PushResponse","PushRpc","Index","PagingInfo","ContentFilter","HistoryQuery","HistoryResponse","HistoryRpc","PeerInfo","PeerExchangeQuery","PeerExchangeResponse","PeerExchangeRPC","WakuMetadataRequest","WakuMetadataResponse","enumeration","findValue","VARINT","enumValue","LENGTH_DELIMITED","isDefined","groupByContentTopic","groupedDecoders","decs","contentTopic","_codec","proof","merkleRoot","epoch","shareX","shareY","nullifier","rlnIdentifier","timestamp","rateLimitProof","ephemeral","topic","contentFilters","messages","requestId","request","FilterSubscribeType","__FilterSubscribeTypeValues","filterSubscribeType","pubsubTopic","contentTopics","SUBSCRIBER_PING","statusCode","statusDesc","wakuMessage","isSuccess","info","response","receiverTime","senderTime","Direction","__DirectionValues","pageSize","cursor","direction","pagingInfo","endTime","HistoryError","__HistoryErrorValues","query","enr","numPeers","peerInfos","clusterId","shards","toAsyncIterator","receiver","iteratorOptions","iteratorDelay","unsubscribe","isWithTimeout","timeoutMs","wait","isWireSizeUnderCap","isSafeInteger","outputLen","blockLen","exists","checkFinished","destroyed","finished","createView","rotr","asyncLoop","iters","tick","utf8ToBytes","toBytes","abytes","concatBytes","sum","Hash","_cloneInto","toStr","wrapConstructor","hashCons","hashC","bytesLength","Maj","HashMD","padOffset","isLE","take","roundClean","digestInto","fill","setBigUint64","_32n","_u32_max","wl","setUint32","oview","outLen","SHA256_K","SHA256_IV","SHA256_W","SHA256","getUint32","W15","W2","T2","Chi","Protocols","PageDirection","Tags","EPeersByDiscoveryEvents","EConnectionStateEvents","DefaultPubsubTopic","DEFAULT_CLUSTER_ID","bytesToUtf8","byteArrays","totalLength","acc","singleShardInfoToPubsubTopic","shardInfo","shard","shardInfoToPubsubTopics","contentTopicToPubsubTopic","application","pubsubTopicToSingleShardInfo","pubsubTopics","ensurePubsubTopicIsConfigured","configuredTopics","contentTopicToShardIndex","networkShards","generation","fields","topicName","ensureValidContentTopic","dataview","getBigUint64","determinePubsubTopic","pubsubTopicShardInfo","ensureShardingConfigured","isShardsConfigured","isContentTopicsConfigured","isApplicationVersionConfigured","shardingParams","decodeRelayShard","byteIndex","bitIndex","numIndices","encodeRelayShard","APP_NAME","Logger","_info","_warn","_error","createDebugNamespace","logger","OneMillion","DecodedMessage","proto","_rawTimestamp","metaSetter","toWire","toProtoObj","protoMessage","createEncoder","fromWireToProtoObj","fromProtoObj","createDecoder","messageHashStr","pubsubTopicBytes","contentTopicBytes","messageHash","entry","arrays","findBufAndOffset","bufs","bufEnd","isUint8ArrayList","Uint8ArrayList","appendAll","append","_len2","_key2","prepend","_len3","_key3","prependAll","consume","trunc","beginInclusive","endExclusive","_subList","sublist","list","bufStart","sliceStartInBuf","sliceEndsInBuf","needle","rightmostPositions","Int32Array","lastPatIndex","getBigInt64","setBigInt64","getFloat32","setFloat32","getFloat64","setFloat64","other","fromUint8Arrays","isAsyncIterable","thing","defaultEncoder","lengthLength","lengthBuf","encodeLength","lengthEncoder","maybeYield","single","ReadMode","defaultDecoder","LENGTH","dataLength","lengthDecoder","maxLengthLength","maxDataLength","errCode","dataLengthLength","onLength","DATA","onData","pDefer","deferred","promise","fromReader","FixedFIFO","btm","hwm","FIFO","splitLimit","calculateSize","AbortError","pushable","_pushable","getNext","onNext","ended","onEnd","drain","bufferNext","objectMode","bufferError","queueMicrotask","_return","throw","readableLength","onEmpty","signal","throwIfAborted","cancel","race","sources","syncSources","all","pipe","isDuplex","duplex","isIterable","rest","fns","sink","duplexPipelineFn","rawPipe","stream","sourceWrap","StreamManager","multicodec","getConnections","streamPool","handlePeerUpdateStreamPool","getStream","peer","peerIdStr","streamPromise","newStream","prepareNewStream","status","connection","connections","latestConnection","timeline","open","selectConnection","protocols","BaseProtocol","components","addLibp2pEventListener","removeLibp2pEventListener","streamManager","connectionManager","peerStore","allPeers","peers","getPeersForProtocol","connectedPeers","getPeers","maxBootstrapPeers","connectedPeersForProtocolAndShard","peerPromises","remotePeer","some","protocol","encodedPeerShardInfo","metadata","peerShardInfo","getConnectedPeersForProtocolAndShard","filteredPeers","bootstrapPeers","tags","BOOTSTRAP","nonBootstrapPeers","selectedPeers","randomIndex","randomPeer","filterPeersByDiscovery","sortedFilteredPeers","pingBytes","ping","sort","sortPeersByLatency","randomUUID","rnds8","byteToHex","unsafeStringify","native","rnds","FilterPushRpc","FilterSubscribeRpc","createSubscribeRequest","uuid","SUBSCRIBE","createUnsubscribeRequest","UNSUBSCRIBE","createUnsubscribeAllRequest","UNSUBSCRIBE_ALL","createSubscriberPingRequest","FilterCodecs","Subscription","receivedMessagesHashStr","subscriptionCallbacks","remotePeers","decodersArray","decodersGroupedByCT","promises","lp","allSettled","handleErrors","subscriptionCallback","unsubscribeRequest","unsubscribeAll","processMessage","hashedMessageStr","decodePromises","dec","decoded","decodedMessage","any","pushMessage","rejectedResult","reason","errorCounts","uniqueErrorMessages","Filter","activeSubscriptions","getActiveSubscription","setActiveSubscription","subscription","numPeersToUse","libp2p","handle","onRequest","createSubscription","toSubscriptionIterator","streamData","createRequest","LightPushCore","preparePushMessage","EMPTY_PAYLOAD","isMessageSizeUnderCap","SIZE_TOO_BIG","ENCODE_FAILED","GENERIC_FAIL","send","preparationError","success","failure","peerId","REMOTE_PEER_FAULT","DECODE_FAILED","REMOTE_PEER_REJECTED","EmptyMessage","createQuery","pageDirection","BACKWARD","FORWARD","directionToProto","StoreCore","queryPerPage","queryOpts","currentCursor","historyRpcQuery","reply","protoMsg","wire","nextCursor","responsePageSize","queryPageSize","TimeoutError","getDOMException","errorMessage","DOMException","getAbortedReason","pTimeout","milliseconds","customTimers","timer","cancelablePromise","aborted","POSITIVE_INFINITY","timeoutError","finally","normalizeEmitter","pEvent","arrayPromise","rejectionEvents","multiArgs","resolveImmediately","flat","items","onItem","arguments_","rejectHandler","rejectionEvent","timeout","pEventMultiple","waitForRemotePeer","waku","relay","Relay","store","Store","lightPush","LightPush","getEnabledProtocols","isStarted","getMeshPeers","gossipSub","waitForGossipSubPeerInMesh","waitForConnectedPeer","services","rejectReason","awaitTimeout","rejectOnTimeout","metadataService","confirmOrAttemptHandshake","_resolve","setMaxListeners","eventTargets","TypedEventEmitter","EventTarget","dispatchEvent","safeDispatchEvent","CustomEvent","CustomEventPolyfill","Event","KeepAliveManager","pingKeepAliveTimers","relayKeepAliveTimers","libp2pPing","pingKeepAlive","pingPeriodSecs","relayKeepAlive","relayPeriodSecs","interval","setInterval","patch","intervals","scheduleRelayPings","clearInterval","stopAll","connectionsExist","ConnectionManager","configuredPubsubTopics","static","keepAliveManager","dialAttemptsForPeer","dialErrorsForPeer","currentActiveParallelDialCount","pendingPeerDialQueue","online","isConnected","toggleOnline","CONNECTION_STATUS","toggleOffline","keepAliveOptions","instances","getPeersByDiscovery","peersDiscovered","peersConnected","conn","peersDiscoveredByBootstrap","peersDiscoveredByPeerExchange","peersDiscoveredByLocal","peersConnectedByBootstrap","peersConnectedByPeerExchange","peersConnectedByLocal","getTagNamesForPeer","PEER_EXCHANGE","LOCAL","DISCOVERED","CONNECTED","maxDialAttemptsForPeer","maxBootstrapPeersAllowed","maxParallelDials","run","dialPeerStorePeers","dialPromises","peerInfo","find","attemptDial","startPeerDiscoveryListener","startPeerConnectionListener","startPeerDisconnectionListener","onEventHandlers","dialPeer","dialAttempt","dial","AggregateError","processDialQueue","dropConnection","hangUp","shouldDialPeer","dispatchDiscoveryEvent","PEER_CONNECT_BOOTSTRAP","PEER_CONNECT_PEER_EXCHANGE","isPeerTopicConfigured","getPeerShardInfo","isPeerDialableBasedOnBootstrapStatus","isBootstrap","PEER_DISCOVERY_BOOTSTRAP","PEER_DISCOVERY_PEER_EXCHANGE","shardInfoBytes","MetadataCodec","Metadata","libp2pComponents","handshakesConfirmed","registrar","encodedShardInfo","proto_metadata","encodedResponse","decodeMetadataResponse","savePeerShardInfo","NO_PEER_AVAILABLE","wakuMetadata","raceSignal","errorCode","QueuelessPushable","readNext","haveNext","nextResult","CodeError","byteStream","readBuffer","abortPromise","unwrap","originalStream","yieldBytes","lpStream","decodeLength","lengthBuffer","writeV","flatMap","defer","piped","NOISE_MSG_MAX_LENGTH_BYTES","DUMP_SESSION_KEYS","u32","isBytes","isPlainObject","ensureBytes","wrapCipher","u8to16","Poly1305","t0","t3","t4","t5","t6","t7","hibit","r0","r3","r4","r5","r6","r7","r8","r9","h8","h9","d0","d3","d4","d5","d6","d7","d8","d9","aexists","aoutput","opos","poly1305","wrapConstructorWithKey","sigma16","sigma32","sigma16_32","sigma32_32","rotl","isAligned32","BLOCK_LEN","BLOCK_LEN32","MAX_COUNTER","U32_EMPTY","core","allowShortKeys","extendNonceFn","counterLength","counterRight","rounds","defaults","checkOpts","anumber","abool","nonce","toClean","sigma","k32","nonceNcLen","n32","isAligned","d32","o32","pos32","posj","runCipher","chachaCore","cnt","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","chacha20","xchacha20","ZEROS16","updatePadded","ZEROS32","computeTag","AAD","authKey","_poly1305_aead","xorStream","plaintext","plength","clength","ciphertext","equalBytes","chacha20poly1305","nonceLength","U32_MASK64","fromBig","lst","Al","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","rotr32L","rotlSH","rotlSL","rotlBH","rotlBL","Bl","add3L","Cl","add3H","add4L","Dl","add4H","add5H","add5L","El","SHA512_Kh","SHA512_Kl","u64","SHA512_W_H","SHA512_W_L","SHA512","Fl","Gl","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","_1n","_2n","hexes","padStart","hexToNumber","asciis","_0","_9","_A","_F","_a","_f","asciiToBase16","hl","al","n2","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","title","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reseed","gen","sl","genUntil","pred","validatorFns","bigint","function","boolean","stringOrUint8Array","field","Fp","isValid","validateObject","validators","optValidators","checkField","fieldName","isOptional","checkVal","entries","_0n","_3n","_4n","_5n","_8n","power","modulo","pow2","invert","FpSqrt","p1div4","eql","sqr","mul","nv","legendreC","Q1div2","neg","tonelliShanks","isNegativeLE","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","Field","ORDER","bitLen","redef","BYTES","sqrtP","MASK","is0","isOdd","lhs","rhs","FpPow","sqrN","addN","subN","mulN","inv","sqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","fromBytes","getFieldBytesLength","fieldOrder","getMinHashLength","wNAF","constTimeNegate","condition","windows","windowSize","unsafeLadder","elm","precomputeWindow","points","precomputes","maxNumber","shiftBy","wbits","offset1","offset2","cond1","cond2","wNAFCached","precomputesMap","transform","_WINDOW_SIZE","comp","validateBasic","curve","validateField","Gx","Gy","VERIFY_DEFAULT","zip215","twistedEdwards","curveDef","CURVE","ut","adjustScalarBytes","domain","uvRatio","mapToCurve","validateOpts","CURVE_ORDER","prehash","cHash","cofactor","modP","phflag","inBig","inRange","in0MaskRange","assertInRange","assertGE0","pointPrecomputes","isPoint","Point","ey","ez","toAffine","fromAffine","normalizeZ","toInv","_setWindowSize","assertValidity","X2","Y2","Z2","Z4","aX2","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","X3","Y3","T3","Z3","wnaf","scalar","multiplyUnsafe","isSmallOrder","isTorsionFree","iz","ax","ay","zz","clearCofactor","fromHex","normed","lastByte","y2","isXOdd","isLastByteOdd","fromPrivateKey","privKey","getExtendedPublicKey","point","toRawBytes","modN","modN_LE","hashed","pointBytes","hashDomainToScalar","msgs","verifyOpts","utils","randomPrivateKey","precompute","getPublicKey","sig","SB","ExtendedPoint","montgomery","montgomeryBits","powPminus2","Gu","montgomeryBytes","fieldLen","cswap","swap","x_2","x_3","dummy","assertFieldElement","a24","encodeUCoordinate","scalarMult","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","getSharedSecret","ED25519_P","ED25519_SQRT_M1","_10n","_20n","_40n","_80n","ed25519_pow_2_252_3","b80","b160","b240","b250","pow_p_5_8","vx2","root1","root2","useRoot1","useRoot2","noRoot","ed25519Defaults","ed25519","ed25519_domain","x25519","ELL2_C1","FpSqrtEven","HMAC","assertHash","iHash","oHash","assertExists","assertBytes","extract","ikm","HKDF_COUNTER","EMPTY_BUFFER","expand","prk","assertNumber","okm","HMACTmp","defaultCrypto","hashSHA256","getHKDF","generateX25519KeyPair","secretKey","generateX25519KeyPairFromSeed","generateX25519SharedKey","chaCha20Poly1305Encrypt","ad","chaCha20Poly1305Decrypt","uint16BEEncode","uint8ArrayAllocUnsafe","uint16BEDecode","UnexpectedPeerError","InvalidCryptoExchangeError","AggregateCodeError","ERR_TIMEOUT","bigIntegerToUintBase64url","uint8ArrayConcat","uint8ArrayToString","base64urlToBigInteger","base64urlToBuffer","isPromise","PUBLIC_KEY_BYTE_LENGTH","PRIVATE_KEY_BYTE_LENGTH","KEYS_BYTE_LENGTH","concatKeys","privateKeyRaw","nativeCrypto","derivedEmptyPasswordKey","alg","ext","key_ops","kty","exporter","saltLength","webcrypto","aesGcm","cryptoKey","importKey","deriveParams","runtimeDerivedEmptyPassword","deriveKey","rawKey","ciphers","encryptedKey","KeyType","__KeyTypeValues","PublicKey","PrivateKey","Data","Ed25519PublicKey","ensureKey","marshal","pbm","Ed25519","uint8ArrayEquals","Ed25519PrivateKey","_publicKey","public","export","unmarshalEd25519PrivateKey","privateKeyBytes","publicKeyBytes","unmarshalEd25519PublicKey","generateKeyPairFromSeed","types","unmarshalPrivateKey","derivePublicFromPrivate","jwKey","convertKey","fkey","jwk2pub","jwk2priv","keySize","jwk","MAX_KEY_SIZE","RsaPublicKey","RSA","RsaPrivateKey","genSecret","randB","dp","dq","unmarshalRsaPrivateKey","unmarshalRsaPublicKey","fromJwk","b2n","h2b","DER","Err","_parseInt","toSig","sBytes","rBytesLeft","hexFromSig","shl","rhl","rl","weierstrassPoints","allowedPrivateKeyLengths","wrapPrivateKey","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","_c","_isCompressed","weierstrassEquation","x2","x3","isWithinCurveOrder","assertGE","normPrivateKeyToScalar","assertPrjPoint","px","py","pz","hasEvenY","U1","U2","k1neg","k2neg","k2","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","isCompressed","_bits","ProjectivePoint","weierstrass","bits2int","bits2int_modN","lowS","compressedLen","uncompressedLen","invN","cat","sqrtError","suffix","numToNByteStr","isBiggerThanHalfOrder","slcNum","Signature","recovery","fromCompact","fromDER","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","ir","u1","u2","hasHighS","normalizeS","toDERRawBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","minLen","reduced","isProbPub","delta","ORDER_MASK","int2octets","prepSig","defaultSigOpts","extraEntropy","ent","h1int","seedArgs","k2sig","kBytes","normS","defaultVerOpts","privateA","publicB","drbg","_sig","derError","getHash","secp256k1P","secp256k1N","divNearest","sqrtMod","_6n","_11n","_22n","_23n","_44n","_88n","b88","b176","b220","b223","secp256k1","defHash","createCurve","POW_2_128","validatePublicKey","secp","Secp256k1PublicKey","keysProtobuf","Secp256k1","Secp256k1PrivateKey","unmarshalSecp256k1PrivateKey","unmarshalSecp256k1PublicKey","supportedKeys","unsupportedKey","keysPBM","peerIdSymbol","isPeerId","multihash","cid","toStringV0","baseCache","toStringV1","CID","asCID","toV0","DAG_PB_CODE","SHA_256_CODE","createV0","toV1","createV1","unknown","toJSON","encodeCID","cidSymbol","decodeFirst","specs","inspectBytes","prefixSize","multihashSize","multihashBytes","digestBytes","digestSize","multihashCode","initialBytes","parseCIDtoBytes","codeOffset","hashOffset","inspect","baseDecoder","LIBP2P_KEY_CODE","MARSHALLED_ED225519_PUBLIC_KEY_LENGTH","MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH","PeerIdImpl","toCID","startsWith","Ed25519PeerIdImpl","Secp256k1PeerIdImpl","RSAPeerIdImpl","peerIdFromCID","peerIdFromBytes","peerIdFromString","peerIdFromKeys","NoiseExtensions","NoiseHandshakePayload","getPayload","localPeer","staticPublicKey","extensions","signedPayload","signPayload","getHandshakePayload","libp2pPublicKey","identityKey","identitySig","webtransportCerthashes","createHandshakePayload","getPeerIdFromPayload","decodePayload","verifySignedPayload","noiseStaticKey","payloadPeerId","generatedPayload","unmarshalPublicKey","isValidPublicKey","pk","uint8ArrayAlloc","Nonce","getUint64","assertValue","AbstractHandshake","forComponent","encryptWithAd","decryptWithAd","valid","hasKey","isEmptyKey","createEmptyKey","encryptAndHash","mixHash","encryptedMessage","decryptAndHash","derivedU8","mixKey","tempK","initializeKey","initializeSymmetric","protocolName","protocolNameBytes","hashProtocolName","tempk1","tempk2","cs1","cs2","writeMessageRegular","readMessageRegular","XX","initializeInitiator","prologue","rs","psk","initializeResponder","writeMessageA","hs","writeMessageB","spk","writeMessageC","messageBuffer","readMessageA","readMessageB","valid1","valid2","readMessageC","initSession","initiator","sendMessage","session","resultingBuffer","recvMessage","resultingPlaintext","resultingValid","logLocalEphemeralKeys","keyLogger","logRemoteEphemeralKey","XXHandshake","isInitiator","remoteExtensions","xx","staticKeypair","handshake","propose","trace","encode0","receivedMessageBuffer","decode0","exchange","decode1","decodedPayload","setRemoteNoiseExtension","encode1","encode2","decode2","getCS","getRemoteStaticKey","encryption","Noise","staticKeys","metrics","staticNoiseKey","prologueBytes","xxHandshakeSuccesses","registerCounter","help","xxHandshakeErrors","encryptedPackets","decryptedPackets","decryptErrors","registerMetrics","secureOutbound","wrappedConnection","performHandshake","createSecureConnection","secureInbound","performXXHandshake","secure","user","duplexPair","network","encryptStream","decrypted","decryptStream","noise","peerDiscoverySymbol","asUint8Array","MAX_IPV6_LENGTH","MAX_IPV4_LENGTH","parser","new","readAtomically","parseWith","peekChar","readChar","readGivenChar","readSeparator","sep","readNumber","radix","maxDigits","allowZeroPrefix","maxBytes","digitCount","leadingChar","hasLeadingZero","maxValue","digit","readIPv4Addr","ix","readIPv6Addr","readGroups","groups","ipv4","headSize","headIp4","limit","tailSize","readIPAddr","isIPv4","parseIPv4","isIPv6","parseIPv6","isIP","parseIP","isV4","isV6","sections","v4Buffer","argv","getProtocol","row","resolvable","path","createProtocol","convertToString","ipBuff","ipString","bytes2ip","bytes2str","bytes2port","address","bytes2mh","bytes2onion","bytes2mb","convertToBytes","ip2bytes","str2bytes","port2bytes","mh2bytes","addr","port","portBuf","onion2bytes","onion32bytes","mbstr","anybaseDecoder","mb2bytes","addrBytes","portBytes","bytesToMultiaddrParts","tuples","stringTuples","sizeForAddr","ParseError","stringAddr","stringTuplesToString","tup","cleanPath","tuplesToBytes","DNS_CODES","resolvers","isMultiaddr","DefaultMultiaddr","stringToMultiaddrParts","toOptions","family","transport","host","zone","tcp","udp","ip4","ip6","dns6","ip6zone","protos","protoCodes","protoNames","encapsulate","decapsulate","addrString","lastIndexOf","decapsulateCode","getPeerId","_ref4","p2p","tuple","getPath","resolvableProto","resolver","nodeAddress","isThinWaistAddress","multiaddr","DNS4","DNS6","DNSADDR","DNS","IP","TCP","UDP","UTP","QUIC","QUICV1","_WebSockets","WebSockets","_WebSocketsSecure","WebSocketsSecure","HTTP","HTTPS","_WebRTCDirect","WebRTCDirect","_WebTransport","WebTransport","P2PWebRTCStar","P2PWebRTCDirect","Reliable","_P2P","_Circuit","CircuitRecursive","Circuit","P2P","makeMatchesFunction","partialMatch","arg","matches","pnames","Multiaddr","MultiaddrClass","Bootstrap","peerData","multiaddrs","_discoverBootstrapPeers","tagValue","ttl","tagTTL","ENVELOPE_PAYLOAD_TYPE_PEER_RECORD","PeerRecord","AddressInfo","seq","addresses","peerRecord","Protobuf","seqNumber","DOMAIN","CODEC","marshaled","localeCompare","every","arrayEquals","pbkdf2Init","_password","_salt","_opts","asyncTick","DK","PRF","PRFSalt","pbkdf2Output","prfW","pbkdf2Async","utilFromBase","inputBuffer","inputBase","utilToBase","internalReserved","internalValue","biggest","retBuf","retView","basis","utilConcatView","outputLength","prevLength","views","utilDecodeTC","valueHex","condition1","condition2","warnings","bigIntBuffer","bigIntView","bigInt","smallIntBuffer","smallIntView","padNumber","inputNumber","fullLength","dif","assertBigInt","checkBufferParams","baseBlock","inputOffset","ViewWriter","final","powers2","digitsString","EMPTY_STRING","EMPTY_VIEW","END_OF_CONTENT_NAME","OCTET_STRING_NAME","BIT_STRING_NAME","HexBlock","BaseClass","isHexOnly","valueHexView","pvtsutils","fromBER","endLength","toBER","sizeOnly","NAME","LocalBaseBlock","valueBeforeDecode","valueBeforeDecodeView","blockName","ValueBlock","LocalIdentificationBlock","idBlock","_b","_d","tagNumber","isConstructed","firstOctet","encodedBuf","pvutils","encodedView","curView","inputView","intBuffer","tagNumberMask","intTagNumberBuffer","tagNumberBufferMaxLength","tempBufferView","LocalLengthBlock","lenBlock","isIndefiniteForm","longFormUsed","lenOffset","lengthBufferView","typeStore","BaseBlock","primitiveSchema","valueBlockType","valueBlock","resultOffset","_writer","prepareIndefiniteForm","idBlockBuf","valueBlockBuf","lenBlockBuf","onAsciiEncoding","inputBuffer1","inputBuffer2","view1","view2","Constructed","BaseStringBlock","fromBuffer","LocalPrimitiveValueBlock","_a$w","_a$v","_a$u","_a$t","_a$s","_a$r","_a$q","_a$p","_a$o","_a$n","_a$m","_a$l","_a$k","_a$j","_a$i","_a$h","_a$g","_a$f","_a$e","_a$d","_a$c","_a$b","_a$a","_a$9","_a$8","_a$7","_a$6","_a$5","_a$4","_a$3","_a$2","_a$1","Primitive","localFromBER","incomingOffset","returnObject","newASN1Type","EndOfContent","Integer","BitString","OctetString","Null","ObjectIdentifier","Enumerated","Utf8String","RelativeObjectIdentifier","TIME","Sequence","NumericString","PrintableString","TeletexString","VideotexString","UTCTime","GeneralizedTime","GraphicString","VisibleString","GeneralString","UniversalString","CharacterString","BmpString","DATE","TimeOfDay","DateTime","Duration","newObject","inputObject","newType","localChangeType","LocalConstructedValueBlock","currentOffset","indefiniteLength","LocalEndOfContentValueBlock","override","LocalBooleanValueBlock","octet","LocalOctetStringValueBlock","currentBlockName","asn","content","LocalBitStringValueBlock","unusedBits","bitsStr","viewAdd","second","firstView","secondView","firstViewCopy","firstViewCopyLength","secondViewCopy","secondViewCopyLength","power2","newValue","viewSub","LocalIntegerValueBlock","_valueDec","setValueHex","valueDec","modValue","tempBuf","tempView","toDER","updatedView","firstBit","currentByte","bitNumber","asn1View","flag","byteNumber","bigIntValue","secondInt","convertToDER","convertFromDER","LocalSidValueBlock","isFirstSid","valueBigInt","sidValue","LocalObjectIdentifierValueBlock","sidBlock","retBuffers","valueBuf","pos1","pos2","sid","plus","parsedSID","sidStr","sidArray","LocalRelativeSidValueBlock","LocalRelativeObjectIdentifierValueBlock","LocalStringValueBlock","LocalSimpleStringValueBlock","LocalSimpleStringBlock","inputString","strLen","LocalUtf8StringValueBlock","LocalBmpStringValueBlock","LocalUniversalStringValueBlock","copyBuffer","valueView","strLength","codeBuf","codeView","valueDate","day","hour","minute","fromDate","toBuffer","inputDate","toDate","UTC","parserArray","outputArray","toISOString","millisecond","getUTCMilliseconds","timeString","dateTimeString","fractionPart","hourDifference","minuteDifference","differencePosition","differenceString","fractionPointPosition","fractionPartCheck","fractionResult","tempDate","getUTCDay","bnToBuf","bn","u8","bufToBn","KEY_SIZE","ITERATIONS","MAX_RSA_KEY_SIZE","der","asn1js","keyBuf","keyArr","encryptionKey","pbkdf2Params","finalWrapperBuf","Envelope","payloadType","RecordEnvelope","envelopeData","record","signData","formatSignaturePayload","envelope","createFromProtobuf","domainUint8Array","uint8arraysFromString","domainLength","payloadTypeLength","payloadLength","vals","pattern","literal","certhash","matcher","matchers","fmt","toParts","exactMatch","_DNS4","_DNS6","_DNSADDR","_DNS","_IP4","_IP6","_IP","_IP_OR_DOMAIN","IP_OR_DOMAIN","_TCP","_UDP","TCP_OR_UDP","_QUIC","_QUICV1","QUIC_V0_OR_V1","_WEB","pbStream","isEnvWithDom","isElectron","detectElectron","isBrowser","isElectronMain","isElectronRenderer","release","isWebWorker","importScripts","WorkerGlobalScope","isReactNative","product","Identify","protocolVersion","agentVersion","listenAddrs","observedAddr","signedPeerRecord","MAX_IDENTIFY_MESSAGE_SIZE","defaultValues","identifyProtocolStr","identifyPushProtocolStr","started","addressManager","maxInboundStreams","maxOutboundStreams","maxPushIncomingStreams","maxPushOutgoingStreams","maxIdentifyMessageSize","maxObservedAddresses","runOnTransientConnection","protocolPrefix","nodeInfo","runOnConnectionOpen","identify","AgentVersion","ProtocolVersion","_handleIdentify","_handlePush","unhandle","pushToConnections","listenAddresses","getAddresses","seal","supportedProtocols","getProtocols","pushes","AbortSignal","IdentifyMessage","close","abort","_identify","cleanObservedAddr","getCleanMultiaddr","getObservedAddrs","addObservedAddr","peerRecordEnvelope","remoteAddr","isCertified","openAndCertify","existingPeer","storedEnvelope","storedRecord","IdentifyClass","closeSource","getIterator","createAbortError","clearMethods","defaultClear","defaultSet","timeoutId","settle","rejectFunction","signalListener","delayPromise","createDelay","RateLimiter","memoryStorage","duration","blockDuration","execEvenly","execEvenlyMinDelayMs","keyPrefix","MemoryStorage","pointsToConsume","rlKey","getKey","secDuration","_getKeySecDuration","incrby","remainingPoints","consumedPoints","msBeforeNext","isFirstInDuration","delayMs","penalty","reward","msDuration","initPoints","customDuration","parseKey","durationSec","existing","msBeforeExpires","expiresAt","getTime","durationMs","unref","MessageTypes","MessageTypeNames","InitiatorMessageTypes","NEW_STREAM","MESSAGE","MESSAGE_INITIATOR","CLOSE","CLOSE_INITIATOR","RESET","RESET_INITIATOR","ReceiverMessageTypes","MESSAGE_RECEIVER","CLOSE_RECEIVER","RESET_RECEIVER","MAX_MSG_SIZE","_buffer","_headerInfo","_maxMessageSize","_maxUnprocessedMessageQueueSize","maxMessageSize","maxUnprocessedMessageQueueSize","_decodeHeader","readVarInt","POOL_SIZE","_pool","_poolOffset","AbstractStream","readStatus","writeStatus","sinkController","sinkEnd","closed","endErr","streamSource","onCloseRead","onCloseWrite","onReset","onAbort","sendCloseWriteTimeout","sendingData","AbortController","onSourceEnd","sendNewStream","abortListener","sendData","sendCloseWrite","onSinkEnd","closeRead","closeWrite","sendCloseRead","sendReset","_closeSinkAndSource","_closeSink","_closeSource","remoteCloseWrite","remoteCloseRead","sourcePush","sourceReadableLength","MplexStream","streamId","maxDataSize","toSend","printMessage","MplexStreamMuxer","_streamId","_streams","closeController","rateLimiter","closeTimeout","initiators","receivers","_createSink","disconnectThreshold","streams","registry","_newStream","_newReceiverStream","maxMsgSize","createStream","onStreamEnd","_handleIncoming","onIncomingStream","maxBufferSize","maxStreamBufferSize","Mplex","createStreamMuxer","mplex","ERR_WRONG_PING_ACK","PingService","handleMessage","openConnection","PingServiceClass","transportSymbol","FaultTolerance","ASSUME_HTTP_CODES","extractSNI","sniProtoCode","hasTLS","interpretNext","headProtoCode","headProtoVal","restMa","interpreter","interpreters","restVal","tailProto","dnsaddr","dns4","dns","ipfs","http","maHasTLS","sni","baseVal","tls","https","ws","wss","p2p-websocket-star","p2p-webrtc-star","p2p-webrtc-direct","socket","readyState","cleanup","handleOpen","handleErr","closeOnEnd","ready","CLOSING","CLOSED","wasClean","binaryType","connected","connError","cleanUp","cont","onOpen","onMessage","connect","endsWith","wsUrl","httpProto","wsProto","wsurl","connectedSource","remoteAddress","remotePort","hostname","CONNECTING","OPEN","WebSocket","websocket","CODE_P2P","CODE_CIRCUIT","testMa","mafmt","maConn","socketToMaConn","_connect","upgrader","upgradeOutbound","cOpts","errorPromise","rawSocket","uri","assumeHttp","toUri","createListener","filters","webSockets","StrictSign","StrictNoSign","TopicValidatorResult","FloodsubID","GossipsubIDv10","GossipsubIDv11","GossipsubMaxIHaveLength","defaultDecodeRpcLimits","maxSubscriptions","maxMessages","maxIhaveMessageIDs","maxIwantMessageIDs","maxControlMessages","maxPeerInfos","RPC","SignaturePolicy","PublishConfigType","RejectReason","ValidateError","MessageStatus","MessageSource","InclusionReason","ChurnReason","ScorePenalty","IHaveIgnoreReason","ScoreThreshold","SubOpts","Message","ControlMessage","ControlIHave","ControlIWant","ControlGraft","ControlPrune","seqno","ihave","iwant","graft","prune","limits","topicID","messageIDs","backoff","peerID","subscriptions","control","MessageCache","gossip","msgIdToStrFn","history","notValidatedCount","historyCapacity","put","messageId","validated","msgIdStr","originatingPeers","iwantCounts","observeDuplicate","msgId","fromPeerIdStr","getWithIWantCount","getGossipIDs","topics","msgIdsByTopic","msgIds","cacheEntry","rejectReasonFromAcceptance","acceptance","Ignore","Reject","ERR_INVALID_PEER_SCORE_PARAMS","defaultPeerScoreParams","topicScoreCap","appSpecificScore","appSpecificWeight","IPColocationFactorWeight","IPColocationFactorThreshold","IPColocationFactorWhitelist","behaviourPenaltyWeight","behaviourPenaltyThreshold","behaviourPenaltyDecay","decayInterval","decayToZero","retainScore","defaultTopicScoreParams","topicWeight","timeInMeshWeight","timeInMeshQuantum","timeInMeshCap","firstMessageDeliveriesWeight","firstMessageDeliveriesDecay","firstMessageDeliveriesCap","meshMessageDeliveriesWeight","meshMessageDeliveriesDecay","meshMessageDeliveriesCap","meshMessageDeliveriesThreshold","meshMessageDeliveriesWindow","meshMessageDeliveriesActivation","meshFailurePenaltyWeight","meshFailurePenaltyDecay","invalidMessageDeliveriesWeight","invalidMessageDeliveriesDecay","createPeerScoreParams","topicScoreParams","createTopicScoreParams","validateTopicScoreParams","defaultPeerScoreThresholds","gossipThreshold","publishThreshold","graylistThreshold","acceptPXThreshold","opportunisticGraftThreshold","createPeerScoreThresholds","removeItemsFromSet","superSet","ineed","cond","subset","MapDef","getDefault","getOrDefault","computeScore","pstats","peerIPs","score","tstats","topicParams","topicScore","inMesh","meshTime","p2","firstMessageDeliveries","meshMessageDeliveriesActive","meshMessageDeliveries","deficit","meshFailurePenalty","invalidMessageDeliveries","p5","knownIPs","peersInIP","numPeersInIP","surplus","behaviourPenalty","excess","DeliveryRecordStatus","MessageDeliveries","records","getRecord","ensureRecord","drec","firstSeenTsMs","expire","PeerScore","peerStats","scoreCache","deliveryRecords","_backgroundInterval","scoreCacheValidityMs","componentLogger","validatePeerScoreParams","background","refreshScores","dumpPeerScoreStats","fromEntries","stats","messageFirstSeenTimestampMs","tparams","graftTime","removeIPsForPeer","scoreFnCalls","inc","cacheUntil","scoreFnRuns","scoreCachedDelta","addPenalty","penaltyLabel","onScorePenalty","addPeer","addIP","removeIP","peersWithIP","removePeer","threshold","getPtopicStats","validateMessage","deliverMessage","markFirstMessageDelivery","markDuplicateMessageDelivery","rejectInvalidMessage","markInvalidMessageDelivery","rejectMessage","Blacklisted","ignored","invalid","duplicateMessage","cap","validatedTime","deliveryDelayMs","isLateDelivery","onDuplicateMsgDelivery","ipsToRemove","ipToRemove","peerSet","topicStats","computeScoreWeights","topicStrToLabel","byTopic","topicLabel","topicScores","p1w","p2w","p3w","p3bw","p4w","capF","p5w","p6w","p7w","OutboundStream","rawStream","errCallback","pushPrefixed","InboundStream","IWantTracer","gossipsubIWantFollowupMs","requestMsByMsg","requestMsByMsgExpire","requestMsByMsgSize","addPromise","expireByPeer","iwantPromiseStarted","getBrokenPromises","brokenPromises","iwantPromiseBroken","isDuplicate","trackMessage","iwantPromiseResolved","iwantPromiseResolvedFromDuplicate","iwantPromiseResolvedPeers","maxMs","iwantMessagePruned","requestMs","iwantPromiseDeliveryTime","typeToKey","SignPrefix","createGossipRpc","ensureControl","rpc","messageIdToString","shuffle","seqnoBytes","msgIdFnStrictSign","sequenceNumber","msgIdFnStrictNoSign","Protocol","SimpleTimeCache","validityMs","validUntilMs","GossipStatusCode","GossipSub","globalSignaturePolicy","multicodecs","constants","publishConfig","dataTransform","streamsInbound","streamsOutbound","outboundInflightQueue","direct","floodsubPeers","seenCache","acceptFromWhitelist","mesh","fanout","fanoutLastpub","peerhave","iasked","outbound","msgIdFn","fastMsgIdFn","fastMsgIdCache","publishedMessageIds","mcache","topicValidators","heartbeatTicks","gossipTracer","directPeerInitial","decodeRpcLimits","stopped","allowedTopics","heartbeatTimer","fallbackToFloodsub","floodPublish","batchPublish","doPX","directPeers","Dlo","Dhi","Dscore","Dout","Dlazy","heartbeatInterval","fanoutTTL","mcacheLength","mcacheGossip","seenTTL","prunePeers","pruneBackoff","unsubcribeBackoff","graftFloodThreshold","opportunisticGraftPeers","opportunisticGraftTicks","directConnectTicks","scoreParams","scoreThresholds","debugName","messageCache","metricsRegister","metricsTopicStrToLabel","maxMeshMessageDeliveriesWindowMs","topicParam","register","protocolsEnabled","gauge","labelNames","topicSubscriptionStatus","topicPeersCount","meshPeerCounts","meshPeerInclusionEventsFanout","meshPeerInclusionEventsRandom","meshPeerInclusionEventsSubscribed","meshPeerInclusionEventsOutbound","meshPeerInclusionEventsNotEnough","meshPeerInclusionEventsOpportunistic","meshPeerInclusionEventsUnknown","meshPeerChurnEventsDisconnected","meshPeerChurnEventsBadScore","meshPeerChurnEventsPrune","meshPeerChurnEventsExcess","meshPeerChurnEventsUnknown","peersPerProtocol","heartbeatDuration","histogram","buckets","heartbeatSkipped","acceptedMessagesTotal","ignoredMessagesTotal","rejectedMessagesTotal","unknownValidationResultsTotal","asyncValidationMcacheHit","asyncValidationDelayFromFirstSeenSec","asyncValidationUnknownFirstSeen","peerReadStreamError","rpcRecvBytes","rpcRecvCount","rpcRecvSubscription","rpcRecvMessage","rpcRecvControl","rpcRecvIHave","rpcRecvIWant","rpcRecvGraft","rpcRecvPrune","rpcDataError","rpcRecvError","rpcRecvNotAccepted","rpcSentBytes","rpcSentCount","rpcSentSubscription","rpcSentMessage","rpcSentControl","rpcSentIHave","rpcSentIWant","rpcSentGraft","rpcSentPrune","msgPublishCount","msgPublishPeersByTopic","directPeersPublishedTotal","floodsubPeersPublishedTotal","meshPeersPublishedTotal","fanoutPeersPublishedTotal","msgPublishBytes","msgPublishTime","msgForwardCount","msgForwardPeers","msgReceivedPreValidation","msgReceivedError","prevalidationInvalidTotal","prevalidationValidTotal","prevalidationDuplicateTotal","prevalidationUnknownTotal","msgReceivedInvalid","msgReceivedInvalidByTopic","duplicateMsgDeliveryDelay","maxMeshMessageDeliveriesWindowSec","duplicateMsgLateDelivery","duplicateMsgIgnored","peersByScoreThreshold","avgMinMax","scoreWeights","scorePerMesh","scoringPenalties","ihaveRcvIgnored","ihaveRcvMsgids","ihaveRcvNotSeenMsgids","iwantRcvMsgids","iwantRcvDonthaveMsgids","gossipPromiseExpireSec","iwantPromiseUntracked","connectedPeersBackoffSec","cacheSize","mcacheSize","mcacheNotValidatedCount","fastMsgIdCacheCollision","newConnectionCount","toTopic","topicStr","onJoin","onLeave","onAddToMesh","Fanout","Random","Subscribed","Outbound","NotEnough","Opportunistic","onRemoveFromMesh","BadScore","Prune","Excess","onReportValidation","messageRecord","firstSeenTimestampMs","hit","Accept","onIhaveRcv","idonthave","onIwantRcv","iwantByTopic","iwantDonthave","onForwardMsg","tosendCount","onPublishMsg","tosendGroupCount","dataLen","floodsub","onMsgRecvPreValidation","onMsgRecvError","onPrevalidationResult","duplicate","onMsgRecvInvalid","onPublishDuplicateMsg","onPeerReadStreamError","onRpcRecvError","onRpcDataError","onRpcRecv","rpcBytes","onRpcSent","registerScores","scores","graylist","publish","registerScoreWeights","wsTopic","registerScorePerMesh","scoreByPeer","peersPerTopicLabel","peersInMesh","meshScores","getMetrics","addCollect","onScrapeMetrics","signaturePolicy","Signing","author","Anonymous","getPublishConfigFromPeerId","createOutboundStream","addrs","topology","onConnect","onPeerConnected","onDisconnect","onPeerDisconnected","notifyOnTransient","registrarTopologyIds","heartbeatTimeout","runHeartbeat","hearbeatStartMs","unregister","closePromises","outboundStream","inboundStream","createInboundStream","maxOutboundBufferSize","sendSubscriptions","priorInboundStream","maxInboundDataLength","pipePeerReadStream","currentIP","multiaddrToIPStr","peersInTopic","getSubscribers","getTopics","control$","prune$","awaitRpcHandler","handleReceivedRpc","handlePeerReadStreamError","acceptFrom","subOpt","handleReceivedSubscription","handleReceivedMessagePromise","handleReceivedMessage","awaitRpcMessageHandler","handleControlMessage","topicSet","rpcMsg","validationResult","validateReceivedMessage","validationCode","asyncValidation","emitSelf","propagationSource","forwardMessage","fastMsgIdStr","msgIdCached","SignaturePresent","SeqnoPresent","FromPresent","InvalidSeqno","InvalidSignature","InvalidPeerId","fromPeerId","rpcMsgPreSign","validateToRawMessage","inboundTransform","TransformFailed","topicValidator","getScore","toPeer","sendRpc","controlMsg","handleIHave","handleIWant","handleGraft","handlePrune","sent","iwantMessageIds","messagesAccepted","acceptUntil","LowScore","MaxIhave","MaxIasked","iask","iwantList","GraftBackoff","floodCutoff","addBackoff","makePrune","doAddBackoff","pxConnect","intervalMs","applyIwantPenalties","BrokenPromise","clearBackoff","directConnect","toconnect","consumePeerRecord","getTopologies","wasSubscribed","leave","toAdd","fanoutPeers","fanoutCount","getRandomGossipPeers","sendGraft","meshPeers","sendPrune","selectPeersToForward","excludePeers","tosend","selectPeersToPublish","newFanoutPeers","rawMsg","startMs","transformedData","outboundTransform","originalData","buildRawMessage","ignoreDuplicatePublishError","recipients","willSendToSelf","allowPublishToZeroPeers","sendRpcInBatch","prefixedData","reportMessageValidationResult","ctrl","piggybackControl","piggybackGossip","outRpc","sendGraftPrune","tograft","toprune","noPX","onUnsubscribe","pruning","emitGossip","peersToGossipByTopic","gossipIDsByTopic","peersToGossip","doEmitGossip","candidateToGossip","factor","peerMessageIDs","pushGossip","flush","controlIHaveMsgs","backoffMs","xid","startTimer","heartbeat","msToNextHeartbeat","candidateMeshPeers","shuffledPeers","peerStreams","prunePeer","graftPeer","newMeshPeers","removeFirstNItemsFromSet","peersArray","rotate","peersList","medianIndex","medianScore","lastpb","topicPeers","candidateFanoutPeers","backoffSize","expiredMs","peerIdStrs","swPeer","swPeerTopic","swTopic","computeAllPeersScoreWeights","RelayCodecs","contentRoutingSymbol","peerRoutingSymbol","defaultLogger","createDisabledLogger","mapIterable","PeerSet","predicate","intersection","difference","union","marshalPublicKey","createEd25519PeerId","createFromPrivKey","createFromJSON","createFromParts","pubKey","createFromPubKey","PeerMap","PriorityQueue","enqueue","comparator","step","it","lowerBound","dequeue","PQueue","carryoverConcurrencyCount","intervalCap","concurrency","autoStart","queueClass","throwOnTimeout","canInitializeInterval","job","newConcurrency","function_","operation","addAll","functions","pause","onSizeLessThan","onIdle","sizeBy","observable","WORKER_REQUEST_READ_LOCK","WORKER_RELEASE_READ_LOCK","MASTER_GRANT_READ_LOCK","WORKER_REQUEST_WRITE_LOCK","WORKER_RELEASE_WRITE_LOCK","MASTER_GRANT_WRITE_LOCK","handleWorkerLockRequest","masterEvent","requestType","releaseType","grantType","requestEvent","identifier","MessageEvent","handler","releaseEventListener","releaseEvent","makeWorkerLockRequest","responseEvent","defaultOptions","singleProcess","mutexes","createReleaseable","createMortice","observer","isWorker","readLock","writeLock","impl","createMutex","masterQueue","readQueue","localReadQueue","readPromise","ERR_INVALID_PARAMETERS","Peer","Address","Tag","Peer$metadataEntry","Peer$tagsEntry","expiry","bytesToPeer","PeerPB","peerIdFromPeerId","pathSepS","pathSepB","pathSep","Key","_buf","clean","uint8Array","withNamespaces","asKey","less","list1","list2","baseNamespace","namespaceType","namespaceValue","parent","isAncestorOf","isDecendantOf","isTopLevel","NAMESPACE_COMMON","peerIdToDatastoreKey","b32key","dedupeFilterAndSortAddresses","addressMap","maStr","existingAddr","toPeerPB","strategy","uint8arrayEquals","createSortedMap","validateMetadata","validateTag","mapTag","metadataEntries","tagsEntries","mergedTags","addressFilter","decodePeer","cached","PersistentStore","datastore","lock","mortice","existingBuf","peerPb","peerCache","orders","mapQuery","previous","updated","PersistentPeerStore","expectedPeer","iterable","peekable","sorter","BaseDatastore","putMany","_this","getMany","_this2","deleteMany","_this3","batch","puts","dels","commit","_all","_allKeys","queryKeys","MemoryDatastore","defaultAddressFilter","stripPeerId","observedPeerIdStr","DefaultAddressManager","announce","observed","announceFilter","_updatePeerStoreAddresses","debounce","getAnnounceAddrs","transportManager","getAddrs","confident","getListenAddrs","confirmObservedAddr","startingConfidence","removeObservedAddr","_ref5","addrSet","isStartable","DefaultComponents","_started","_invokeStartableMethod","startable","beforeStart","afterStart","beforeStop","afterStop","OPTIONAL_SERVICES","NON_SERVICE_PROPERTIES","NETMASK_RANGES","ipRange","isPrivateIp","ipAddr","ipv4Check","connectionGater","denyDialPeer","denyDialMultiaddr","denyInboundConnection","denyOutboundConnection","denyInboundEncryptedConnection","denyOutboundEncryptedConnection","denyInboundUpgradedConnection","denyOutboundUpgradedConnection","filterMultiaddrForPeer","isPrivate","defaultAddressSort","publicResult","isAPrivate","isBPrivate","publicAddressesFirst","relayResult","isACircuit","isBCircuit","circuitRelayAddressesLast","certifiedResult","certifiedAddressesFirst","CustomProgressEvent","getTypes","DEFAULT_TYPES","RecordType","DEFAULT_TTL","toDNSResponse","Status","TC","flag_tc","RD","flag_rd","RA","flag_ra","AD","flag_ad","CD","flag_cd","Question","questions","question","Answer","answers","answer","TTL","DEFAULT_QUERY_CONCURRENCY","dnsJsonOverHttps","httpQueue","queryConcurrency","fqdn","searchParams","URLSearchParams","onProgress","fetch","accept","statusText","CachedAnswers","lru","maxSize","hashlru","foundAllAnswers","getAnswers","cachedAnswers","expires","tld","dnsaddrCode","dnsaddrResolver","recursionLimit","maxRecursiveDepth","DNSClass","TXT","resolved","DefaultConfig","noAnnounce","addressSorter","faultTolerance","FATAL_ALL","validateConfig","resultingOptions","mergeOptions","connectionProtector","LIBP2P_FORCE_PNET","ERR_PROTECTOR_REQUIRED","ERR_INVALID_KEY","getPeerAddress","ERR_INVALID_MULTIADDR","maPeerIdStr","maPeerId","raceEvent","eventName","eventListener","JobRecipient","where","Job","controller","created","recipient","Queue","metricName","registerMetricGroup","calculate","running","queued","tryToStartAnother","toGenerator","onQueueJobComplete","onQueueError","onQueueIdle","onSignalAbort","PeerQueue","LAST_DIAL_FAILURE_KEY","minConnections","maxQueueLength","autoDialConcurrency","autoDialPriority","autoDialInterval","autoDialPeerRetryThreshold","autoDialDiscoveredPeersDebounce","AutoDial","autoDialIntervalMs","autoDialMaxQueueLength","autoDialPeerRetryThresholdMs","autoDial","getConnectionsMap","numConnections","sheduleNextAutodial","dialQueue","getDialQueue","peerValues","peersThatHaveNotFailed","peerAValue","peerBValue","lastDialFailure","lastDialFailureTimestamp","maxConnections","allow","ConnectionPruner","maybePruneConnections","toPrune","sortedConnections","connectionALifespan","connectionBLifespan","toClose","maxDialQueueLength","maxPeerAddrsToDial","dialTimeout","DialQueue","shutDownController","peerIdOrMultiaddr","existingConnection","force","existingDial","createDialAbortController","addrsToDial","calculateMultiaddrs","dialed","ERR_TOO_MANY_ADDRESSES","ERR_TRANSPORT_DIAL_FAILED","userSignal","signals","anySignal","ERR_DIALED_SELF","ERR_PEER_DIAL_INTERCEPTED","ERR_NOT_FOUND","peerRouting","findPeer","ERR_NO_ROUTERS_AVAILABLE","resolvedAddresses","resolveMultiaddrs","peerIdMultiaddr","lastProto","filteredAddrs","transportForMultiaddr","addrPeerId","dedupedAddrs","dedupedMultiaddrs","ERR_NO_VALID_ADDRESSES","gatedAdrs","sortedGatedAddrs","DefaultConnectionManager","deny","maxIncomingPendingConnections","incomingPendingConnections","connectionPruner","inboundConnectionRateLimiter","inboundConnectionThreshold","metric","inbound","conns","allStreams","counts","keepAlivePeers","tasks","connectionList","_onConnect","storedConns","isNewPeer","storedConn","ERR_NODE_NOT_STARTED","transient","peerConnections","trackedConnection","closeConnections","acceptIncomingConnection","afterUpgradeInbound","statusMap","errored","complete","CompoundContentRouting","routers","findProviders","seen","router","provide","NOT_STARTED_YET","DefaultPeerRouting","ERR_FIND_SELF","NOT_FOUND","getClosestPeers","ordered","ops","sourceErr","slotAvailable","resultAvailable","sourceFinished","opErred","valuesAvailable","yieldOrderedValues","yieldUnOrderedValues","task","parallel","useCache","DefaultRegistrar","topologies","_onDisconnect","_onPeerUpdate","_onPeerIdentify","getHandler","ERR_NO_HANDLER_FOR_PROTOCOL","ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED","TrackedMap","registerMetric","updateComponentMetric","deleted","DefaultTransportManager","transports","trackedMap","ERR_DUPLICATE_TRANSPORT","ERR_TRANSPORT_UNAVAILABLE","getTransports","getListeners","couldNotListen","supportedAddrs","findIndex","NO_FATAL","removeAll","PROTOCOL_ID","MAX_PROTOCOL_LENGTH","NewLine","readString","multistream","select","negotiateFully","originalSink","originalSource","negotiated","negotiating","doneNegotiating","sentProtocol","sendingProtocol","doneSendingProtocol","readProtocol","readingProtocol","doneReadingProtocol","negotiate","doSendProtocol","doReadProtocol","sentData","protocolString","originalCloseRead","originalCloseWrite","originalClose","optimisticSelect","connectionSymbol","ConnectionImpl","multiplexer","_close","_abort","_getStreams","getStreams","countStreams","streamCount","DefaultUpgrader","connectionEncryption","muxers","inboundUpgradeTimeout","encrypter","muxer","shouldBlockConnection","connectionType","ERR_CONNECTION_INTERCEPTED","upgradeInbound","ERR_CONNECTION_DENIED","encryptedConn","upgradedConn","muxerFactory","cryptoProtocol","trackMultiaddrConnection","protectedConn","skipProtection","protector","protect","skipEncryption","_encryptInbound","idStr","remotePeerId","multiplexed","_multiplexInbound","_createConnection","_encryptOutbound","ERR_INVALID_PEER","_multiplexOutbound","muxedStream","mss","incomingLimit","findIncomingStreamLimit","ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS","trackProtocolStream","_onStream","ERR_MUXER_UNAVAILABLE","outgoingLimit","findOutgoingStreamLimit","ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS","ERR_UNSUPPORTED_PROTOCOL","_timeline","Proxy","upgraded","errConnectionNotMultiplexed","ERR_CONNECTION_NOT_MULTIPLEXED","ERR_ENCRYPTION_FAILED","Libp2pNode","contentRouting","originalDispatch","internalResult","externalResult","service","defaultComponents","configureComponent","streamMuxers","peerRouters","contentRouters","peerDiscovery","createService","component","dialProtocol","ERR_INVALID_PROTOCOLS_FOR_STREAM","getMultiaddrs","peerKey","ERR_DISCOVERED_SELF","createLibp2p","createLibp2pNode","BaseProtocolSDK","LightPushSDK","successes","failures","TOPIC_NOT_CONFIGURED","sendPromises","StoreSDK","queryGenerator","decodersAsMap","validateDecodersAndPubsubTopic","constructOptions","responseGenerator","queryWithOrderedCallback","processMessages","queryWithPromiseCallback","page","_promises","msgPromise","createCursor","messageTime","uniquePubsubTopicsInQuery","pubsubTopicForQuery","timeFilter","processedMessages","shouldReverseOrder","createLightNode","libp2pOptions","defaultBootstrap","wakuDnsDiscovery","enrTree","DEFAULT_NODE_REQUIREMENTS","wakuLocalPeerCacheDiscovery","wakuPeerExchangeDiscovery","wakuGossipSub","hideWebSocketInfo","pubsubService","pubsub","filterAll","DefaultUserAgent","defaultLibp2p","createLibp2pAndUpdateOptions","wakuStore","wakuLightPush","wakuFilter","WakuNode","prepareSubscription","_protocols","mapToPeerIdOrMultiaddr","codecs","subscribeToContentTopic","getLocalMultiaddrWithID","localMultiaddr","TEST","SANDBOX","DEFAULT_BOOTSTRAP_TAG_NAME","groupLen","USE_ENDOMORPHISM","ShaError","assertJacPoint","JacobianPoint","toAffineBatch","scratch","Z1Z1","Z2Z2","S1","S2","x1b","HH","HHH","P0","normalizeScalar","affinePoint","invZ","iz1","iz2","iz3","fromCompressedHex","isShort","bytesToNumber","isValidFieldElement","rt","isYOdd","fromUncompressedHex","normalizePrivateKey","fromSignature","normalizeSignature","truncateHash","rinv","numTo32bStr","toHexX","toRawX","aP","bQ","sliceDER","parseDERInt","parseDERSignature","HALF","sHex","numberToHexUnpadded","rHex","sHexL","rHexL","sLen","rLen","uint8a","POW_2_256","numTo32b","hexByte","truncateOnly","bits2int_2","_sha256Sync","_hmacSha256Sync","HmacDrbg","hmacSha256","hmacSync","checkSync","incr","reseedSync","kmdToSig","kinv","normalizePublicKey","bits2octets","z1","initSigArgs","finalizeSig","recSig","recovered","canonical","vopts","nodeCrypto","web","TAGGED_HASH_PREFIXES","_bigintTo32Bytes","_normalizePrivateKey","hashToPrivateKey","_len4","_key4","createHash","_len5","_key5","ckey","createHmac","sha256Sync","hmacSha256Sync","taggedHash","tagP","tagH","_len6","_key6","taggedHashSync","_len7","_key7","_JacobianPoint","defineProperties","keccak256","sha3","verifySignature","sinv","ERR_INVALID_ID","locationMultiaddrFromEnrFields","isIpv6","ipVal","protoName","protoVal","ipFamily","ipBytes","protocolBytes","multiaddrFromFields","createPeerIdFromPublicKey","encodeMultiaddrs","encodeWaku2","RawEnr","kvs","rsv","getStringValue","setStringValue","getNumberAsStringValue","setNumberAsStringValue","tcp6","udp6","multiaddrBytes","decodeMultiaddrs","deleteUndefined","waku2","decodeWaku2","TransportProtocol","TransportProtocolPerIpVersion","ENR","nodeId","uncompressedPubkey","getLocationMultiaddr","setLocationMultiaddr","getAllLocationMultiaddrs","_multiaddrs","getFullMultiaddr","locationMultiaddr","getFullMultiaddrs","_permanentCensorErrors","_censorErrors","LogLevels","warning","_logLevel","_globalLogger","_normalizeError","missing","normalize","_checkNormalize","LogLevel","ErrorCode","HEX","_log","logLevel","throwArgumentError","levels","INFO","WARNING","makeError","UNKNOWN_ERROR","messageDetails","NUMERIC_FAULT","fault","CALL_EXCEPTION","INSUFFICIENT_FUNDS","MISSING_NEW","NONCE_EXPIRED","REPLACEMENT_UNDERPRICED","TRANSACTION_REPLACED","UNPREDICTABLE_GAS_LIMIT","throwError","INVALID_ARGUMENT","argument","assert","assertArgument","checkNormalize","UNSUPPORTED_OPERATION","checkSafeUint53","checkArgumentCount","expectedCount","MISSING_ARGUMENT","UNEXPECTED_ARGUMENT","checkNew","kind","checkAbstract","globalLogger","setCensorship","censorship","permanent","setLogLevel","isHexable","toHexString","addSlice","isBytesLike","isHexString","arrayify","allowMissingPrefix","hexPad","HexCharacters","hexlify","arrayifyInteger","unarrayifyInteger","_encode","_decodeChildren","childOffset","_decode","consumed","BUFFER_OVERRUN","EnrDecoder","encoded","RECORD_PREFIX","fromRLP","RLP","checkValues","_seq","decodeSeq","rlpEncodedBytes","checkSignature","fromValues","v4Regex","v6Regex","isFormat","buff","hexN","decN","prevColon","useDec","sizeOf","toType","rcode","opcode","klass","toClass","toCode","SURROGATE_A","SURROGATE_B","nextCode","numA","isU8Arr","bytelength","P_24","P_16","P_8","readUInt32BE","readUInt16BE","writeUInt32BE","writeUInt16BE","targetStart","sourceStart","sourceEnd","sourceLen","_copyActual","FLUSH_MASK","consumedBytes","jumped","toUtf8","jumpOffset","authorities","additionals","flag_qr","opcodes","flag_aa","flag_z","rcodes","runknown","dLen","rns","rsoa","mname","rname","serial","refresh","retry","minimum","rtxt","rnull","rhinfo","cpu","os","rptr","rsrv","weight","rcaa","issuerCritical","ISSUER_CRITICAL","rmx","preference","raaaa","roption","optioncodes","spl","sourcePrefixLength","fam","ipBuf","ipLen","scopePrefixLength","tagsLen","padded","ropt","rdlen","encodingLengthList","encodeList","rdnskey","keydata","PROTOCOL_DNSSEC","ZONE_KEY","SECURE_ENTRYPOINT","rrrsig","typeCovered","labels","originalTTL","expiration","inception","keyTag","signersName","rrp","mbox","txt","typebitmap","typelist","typesByWindow","typeid","windowBuf","windowLength","extents","rnsec","nextDomain","rrtypes","rnsec3","hashLength","rds","digestdata","digestType","renc","udpPayloadSize","extendedRcode","ednsVersion","classes","class","flag_do","RECURSION_DESIRED","packet","allocing","decodeList","sanitizeSingle","sanitized","make","charset","paddingMode","byCharCode","byNum","padCode","safeLen","safeEnd","base64URL","HTTPStatusError","endpoint","ResponseError","cause","reduceError","baseParts","httpFlags","updFlags","parseFlags","InvalidProtocolError","BaseEndpoint","isHTTP","UDPEndpoint","ipv6","UDP4Endpoint","UDP6Endpoint","safeHost","HTTPEndpoint","v6Parts","toEndpoint","post","parseEndpoint","contentType","requestRaw","abortSignal","xhr","XMLHttpRequest","setRequestHeader","responseType","ontimeout","onreadystatechange","onload","utf8Codec","onabort","processResolvers","cors","lib","endpoints","resolverByName","byName","endpointByName","backup","description","country","lat","queryOne","queryDoh","UPDATE_URL","isNameString","wellknown","updateURL","localStoragePrefix","maxAge","_dataP","_data","outdated","cacheKey","maxTime","filterDoh","filterDns","retries","queryN","singleQuery","toMultiQuery","DnsOverHttps","_endpoints","resolveTXT","ENRTree","parseAndVerifyRoot","ROOT_PREFIX","rootValues","parseRootValues","decodedPublicKey","signedComponent","signedComponentBuffer","signatureBuffer","eRoot","lRoot","parseTree","tree","TREE_PREFIX","parseBranch","branch","BRANCH_PREFIX","isSatisfied","wanted","actual","addCapabilities","helpsSatisfyCapabilities","missingCapabilities","DnsNodeDiscovery","_DNSTreeCache","_errorTolerance","dnsOverHttp","dnsClient","enrTreeUrls","wantedNodeCapabilityCount","networkIndex","visits","errorTolerance","getNode","maxSearches","totalSearches","fetchNodesUntilCapabilitiesFulfilled","_search","getNextPeer","peerNodeIds","yieldNodesUntilCapabilitiesFulfilled","subdomain","_getTXTRecord","branches","entryType","getEntryType","circularRefs","selectRandomPath","PeerDiscoveryDns","nextPeer","_components","_options","enrUrls","peerEnr","tagsToUpdate","isPeerChanged","PeerExchangeCodec","WakuPeerExchange","rpcQuery","DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS","DEFAULT_MAX_RETRIES","DEFAULT_PEER_EXCHANGE_TAG_NAME","PeerExchangeDiscovery","peerExchange","queryingPeers","queryAttempts","handleDiscoveredPeer","startRecurringQueries","queryInterval","maxRetries","currentAttempt","abortQueriesForPeer","_peerInfo","DEFAULT_LOCAL_TAG_NAME","LocalPeerCacheDiscovery","getPeersFromLocalStorage","handleNewPeers","savePeersToLocalStorage","websocketMultiaddr","wsMultiaddr","getWsMultiaddrFromMultiaddrs","localStoragePeers","existingPeerIndex","_peer","storedPeersData","isValidStoredPeer","ContentPairContext","React","useContentPair","ContentPairProvider","setEncoder","setDecoder","useCreateContentPair","useCreateLightNode","setNode","isLoading","setLoading","setError","cancelled","useCreateNode","useLightPush","WakuContext","useWaku","LightNodeProvider","handleCommand","setNick","replaceAll","parseInput","command","nick","peerMultiaddr","strConnections","ChatList","renderedMessages","_message$sentTimestam","_jsxs","className","_jsx","formatDisplayDate","payloadAsUtf8","sentTimestamp","AlwaysScrollToBottom","toLocaleString","hour12","elementRef","scrollIntoView","MessageInput","hasLightPushPeers","inputText","setInputText","isActive","setActiveButton","onChange","onKeyDown","ReaderClass","ReaderBufferClass","WriterClass","WriterBufferClass","patchReader","patchWriter","ChatMessage","_ChatMessage","fromUtf8String","timestampNumber","chatMessage","cmp","fromWakuMessage","wakuMsg","chatMsg","OrderedSet","orderCmp","insertInOrder","getPeerIdsForProtocol","useMessages","newMessages","setMessage","unsubscribeFn","useFilterMessages","storedMessages","filteredMessages","useStoreMessages","localMessages","setLocalMessages","allMessages","tomorrow","setDate","getDate","_msgs","useNodePeers","discoveredBootstrapPeers","setBootstrapPeers","connectedBootstrapPeers","setConnectedBootstrapPeers","discoveredPeerExchangePeers","setPeerExchangePeers","connectedPeerExchangePeers","setConnectedPeerExchangePeers","handleDiscoveryBootstrap","isPeerDialable","handleConnectBootstrap","handleDiscoveryPeerExchange","handleConnectPeerExchange","initHookData","usePeers","setPeers","peerIds","allConnected","storePeers","filterPeers","lightPushPeers","isMultiaddrConnectable","Room","onPush","allConnectedLength","orZero","lightPushPeersLength","filterPeersLength","storePeersLength","commandHandler","App","pushLocalMessages","usePersistentNick","persistedNick","commandMessages","ReactDOM","getElementById"],"sourceRoot":""} \ No newline at end of file diff --git a/flush-notes/404.html b/flush-notes/404.html index 9ce6bdf..548f4ba 100644 --- a/flush-notes/404.html +++ b/flush-notes/404.html @@ -1 +1 @@ -Share notes

Loading...

\ No newline at end of file +Share notes

Loading...

\ No newline at end of file diff --git a/flush-notes/_next/static/chunks/990-35c20412112b0913.js b/flush-notes/_next/static/chunks/990-221729f16830b71b.js similarity index 100% rename from flush-notes/_next/static/chunks/990-35c20412112b0913.js rename to flush-notes/_next/static/chunks/990-221729f16830b71b.js diff --git a/flush-notes/_next/static/chunks/app/layout-728a76cd335ea299.js b/flush-notes/_next/static/chunks/app/layout-6076b03a814c7003.js similarity index 86% rename from flush-notes/_next/static/chunks/app/layout-728a76cd335ea299.js rename to flush-notes/_next/static/chunks/app/layout-6076b03a814c7003.js index edaf913..b04586d 100644 --- a/flush-notes/_next/static/chunks/app/layout-728a76cd335ea299.js +++ b/flush-notes/_next/static/chunks/app/layout-6076b03a814c7003.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{5856:function(){},2678:function(){},5819:function(){},4112:function(){},8080:function(t,i,e){Promise.resolve().then(e.bind(e,5685))},5685:function(t,i,e){"use strict";e.r(i),e.d(i,{default:function(){return h}});var n=e(7437),s=e(1654),r=e.n(s),a=e(2265),u=e(7441),l=e(1177),o=e(6309);let c=a.createContext({status:l.c.Initializing,waku:void 0}),d=t=>{let i=a.useRef(),[e,s]=a.useState(l.c.Initializing);return(a.useEffect(()=>{if(i.current)return;let t=t=>{s(t.detail)};return u.H5.addEventListener(u.J9.Status,t),u.H5.init().then(()=>{i.current=u.H5}),()=>{u.H5.removeEventListener(u.J9.Status,t)}},[i,s]),e===l.c.Failed)?(0,n.jsx)(n.Fragment,{children:e}):e!==l.c.Connected?(0,n.jsx)(o.g,{}):(0,n.jsx)(c.Provider,{value:{status:e,waku:i.current},children:t.children})};function h(t){let{children:i}=t;return(0,n.jsxs)("html",{lang:"en",children:[(0,n.jsx)("title",{children:"Share notes"}),(0,n.jsx)("body",{className:r().className,children:(0,n.jsx)(d,{children:i})})]})}e(2489)},6309:function(t,i,e){"use strict";e.d(i,{g:function(){return s}});var n=e(7437);let s=()=>(0,n.jsx)("div",{className:"loading-block",children:(0,n.jsx)("p",{children:"Loading..."})})},1177:function(t,i,e){"use strict";var n,s;e.d(i,{c:function(){return n},m:function(){return r}});let r="/flush-notes/1/note/proto";(s=n||(n={})).Initializing="Initializing...",s.WaitingForPeers="Waiting for peers...",s.Connected="Connected",s.Failed="Failed to initialize(see logs)"},7441:function(t,i,e){"use strict";e.d(i,{H5:function(){return l},J9:function(){return n}});var n,s=e(1177),r=e(8089),a=e(9527);(n||(n={})).Status="status";class u{async init(){if(!this.initialized&&!this.initializing){this.initializing=!0;try{this.emitStatusEvent(s.c.Initializing),this.pubsubTopic=(0,a.L3)(s.m);let t=await (0,r.pq)({defaultBootstrap:!0,contentTopics:[s.m]});await t.start(),this.emitStatusEvent(s.c.WaitingForPeers),await (0,r.gT)(t,[r.Uw.Filter,r.Uw.LightPush,r.Uw.Store]),this.node=t,this.initialized=!0,this.emitStatusEvent(s.c.Connected)}catch(t){console.error("Failed to initialize Waku node:",t),this.emitStatusEvent(s.c.Failed)}this.initializing=!1}}addEventListener(t,i){return this.emitter.addEventListener(t,i)}removeEventListener(t,i){return this.emitter.removeEventListener(t,i)}send(t,i){var e;return this.ensureWakuInitialized(),null===(e=this.node)||void 0===e?void 0:e.lightPush.send(t,i)}async getHistory(t){this.ensureWakuInitialized();let i=[];for await(let e of this.node.store.queryGenerator([t])){let t=await Promise.all(e),n=t.filter(t=>!!t);i=[...i,...n]}return i}async subscribe(t,i){return this.ensureWakuInitialized(),this.node.filter.subscribe(t,i)}emitStatusEvent(t){this.emitter.dispatchEvent(new CustomEvent("status",{detail:t}))}ensureWakuInitialized(){if(!l.initialized){let t="Waku is not initialized.";throw console.log(t),Error(t)}}constructor(){this.emitter=new EventTarget,this.initialized=!1,this.initializing=!1}}let l=new u},2489:function(){},1654:function(t){t.exports={style:{fontFamily:"'__Inter_d65c78', '__Inter_Fallback_d65c78'",fontStyle:"normal"},className:"__className_d65c78"}}},function(t){t.O(0,[948,971,472,744],function(){return t(t.s=8080)}),_N_E=t.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{5856:function(){},2678:function(){},5819:function(){},4112:function(){},8080:function(t,i,e){Promise.resolve().then(e.bind(e,5685))},5685:function(t,i,e){"use strict";e.r(i),e.d(i,{default:function(){return h}});var n=e(7437),s=e(1654),r=e.n(s),a=e(2265),u=e(7441),l=e(1177),o=e(6309);let c=a.createContext({status:l.c.Initializing,waku:void 0}),d=t=>{let i=a.useRef(),[e,s]=a.useState(l.c.Initializing);return(a.useEffect(()=>{if(i.current)return;let t=t=>{s(t.detail)};return u.H5.addEventListener(u.J9.Status,t),u.H5.init().then(()=>{i.current=u.H5}),()=>{u.H5.removeEventListener(u.J9.Status,t)}},[i,s]),e===l.c.Failed)?(0,n.jsx)(n.Fragment,{children:e}):e!==l.c.Connected?(0,n.jsx)(o.g,{}):(0,n.jsx)(c.Provider,{value:{status:e,waku:i.current},children:t.children})};function h(t){let{children:i}=t;return(0,n.jsxs)("html",{lang:"en",children:[(0,n.jsx)("title",{children:"Share notes"}),(0,n.jsx)("body",{className:r().className,children:(0,n.jsx)(d,{children:i})})]})}e(2489)},6309:function(t,i,e){"use strict";e.d(i,{g:function(){return s}});var n=e(7437);let s=()=>(0,n.jsx)("div",{className:"loading-block",children:(0,n.jsx)("p",{children:"Loading..."})})},1177:function(t,i,e){"use strict";var n,s;e.d(i,{c:function(){return n},m:function(){return r}});let r="/flush-notes/1/note/proto";(s=n||(n={})).Initializing="Initializing...",s.WaitingForPeers="Waiting for peers...",s.Connected="Connected",s.Failed="Failed to initialize(see logs)"},7441:function(t,i,e){"use strict";e.d(i,{H5:function(){return l},J9:function(){return n}});var n,s=e(1177),r=e(8089),a=e(9527);(n||(n={})).Status="status";class u{async init(){if(!this.initialized&&!this.initializing){this.initializing=!0;try{this.emitStatusEvent(s.c.Initializing),this.pubsubTopic=(0,a.L3)(s.m);let t=await (0,r.pq)({defaultBootstrap:!0,contentTopics:[s.m]});await t.start(),this.emitStatusEvent(s.c.WaitingForPeers),await (0,r.gT)(t,[r.Uw.Filter,r.Uw.LightPush,r.Uw.Store]),this.node=t,this.initialized=!0,this.emitStatusEvent(s.c.Connected)}catch(t){console.error("Failed to initialize Waku node:",t),this.emitStatusEvent(s.c.Failed)}this.initializing=!1}}addEventListener(t,i){return this.emitter.addEventListener(t,i)}removeEventListener(t,i){return this.emitter.removeEventListener(t,i)}send(t,i){var e;return this.ensureWakuInitialized(),null===(e=this.node)||void 0===e?void 0:e.lightPush.send(t,i)}async getHistory(t){this.ensureWakuInitialized();let i=[];for await(let e of this.node.store.queryGenerator([t])){let t=await Promise.all(e),n=t.filter(t=>!!t);i=[...i,...n]}return i}async subscribe(t,i){return this.ensureWakuInitialized(),this.node.filter.subscribe(t,i)}emitStatusEvent(t){this.emitter.dispatchEvent(new CustomEvent("status",{detail:t}))}ensureWakuInitialized(){if(!this.initialized){let t="Waku is not initialized.";throw console.log(t),Error(t)}}constructor(){this.emitter=new EventTarget,this.initialized=!1,this.initializing=!1}}let l=new u},2489:function(){},1654:function(t){t.exports={style:{fontFamily:"'__Inter_d65c78', '__Inter_Fallback_d65c78'",fontStyle:"normal"},className:"__className_d65c78"}}},function(t){t.O(0,[948,971,472,744],function(){return t(t.s=8080)}),_N_E=t.O()}]); \ No newline at end of file diff --git a/flush-notes/_next/static/chunks/app/page-6f37c3f6b755896a.js b/flush-notes/_next/static/chunks/app/page-1fab92edd07a9fd3.js similarity index 93% rename from flush-notes/_next/static/chunks/app/page-6f37c3f6b755896a.js rename to flush-notes/_next/static/chunks/app/page-1fab92edd07a9fd3.js index a293823..45f294c 100644 --- a/flush-notes/_next/static/chunks/app/page-6f37c3f6b755896a.js +++ b/flush-notes/_next/static/chunks/app/page-1fab92edd07a9fd3.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{5856:function(){},7761:function(){},2678:function(){},5819:function(){},4112:function(){},7747:function(t,e,i){Promise.resolve().then(i.bind(i,5721))},5721:function(t,e,i){"use strict";i.r(e),i.d(e,{default:function(){return o}});var n=i(7437),s=i(2265),r=i(4033),a=i(7923);function o(){let t=(0,r.useRouter)(),{note:e,onNoteChange:i}=u(),s=async()=>{if(e)try{let{id:i,key:n}=await a.$.createNote(e);t.push("/view/".concat(i).concat("?key=".concat(n)))}catch(t){console.error("Failed to create a note:",t)}};return(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"note-info",children:"Your record will be stored for couple of days. Markdown is supported."}),(0,n.jsxs)("div",{className:"create-header",children:[(0,n.jsx)("div",{}),(0,n.jsx)("button",{onClick:s,className:"save-note",children:"Save note"})]}),(0,n.jsx)("textarea",{className:"note-value",value:e,onChange:i})]})}let u=()=>{let[t,e]=s.useState("");return{note:t,onNoteChange:t=>{var i;e(null==t?void 0:null===(i=t.currentTarget)||void 0===i?void 0:i.value)}}}},1177:function(t,e,i){"use strict";var n,s;i.d(e,{c:function(){return n},m:function(){return r}});let r="/flush-notes/1/note/proto";(s=n||(n={})).Initializing="Initializing...",s.WaitingForPeers="Waiting for peers...",s.Connected="Connected",s.Failed="Failed to initialize(see logs)"},7923:function(t,e,i){"use strict";i.d(e,{$:function(){return l}});var n=i(7441),s=i(1177),r=i(5136),a=i(8089),o=i(9710);class u{async createNote(t){var e;let i=(0,r.oQ)(),u=(0,r.Mf)({contentTopic:s.m,symKey:i,pubsubTopic:n.H5.pubsubTopic}),l=self.crypto.randomUUID();if(36!==l.length)throw"Unexpected uuid length";let c=await n.H5.send(u,{payload:(0,a.iY)(l+t)});return(null==c?void 0:null===(e=c.failures)||void 0===e?void 0:e.length)&&c.failures.length>0&&console.error("Failures when pushing note: ",c.failures.map(t=>t.error)),{id:l,key:(0,o.ci)(i)}}async readNote(t,e){await this.initMessages((0,o.nr)(e));let i=this.messages.map(t=>{try{let e=(0,a.Md)(t.payload),i=e.substring(0,36),n=e.substring(36);return{id:i,content:n}}catch(t){console.log("Failed to read message:",t)}}).find(e=>{if((null==e?void 0:e.id)===t)return!0});return null==i?void 0:i.content}async initMessages(t){if(this.subscription)return;let e=(0,r.UF)(s.m,t,n.H5.pubsubTopic);this.messages=await n.H5.getHistory(e),this.subscription=await n.H5.subscribe(e,t=>{this.messages.push(t)})}constructor(){this.messages=[]}}let l=new u},7441:function(t,e,i){"use strict";i.d(e,{H5:function(){return u},J9:function(){return n}});var n,s=i(1177),r=i(8089),a=i(9527);(n||(n={})).Status="status";class o{async init(){if(!this.initialized&&!this.initializing){this.initializing=!0;try{this.emitStatusEvent(s.c.Initializing),this.pubsubTopic=(0,a.L3)(s.m);let t=await (0,r.pq)({defaultBootstrap:!0,contentTopics:[s.m]});await t.start(),this.emitStatusEvent(s.c.WaitingForPeers),await (0,r.gT)(t,[r.Uw.Filter,r.Uw.LightPush,r.Uw.Store]),this.node=t,this.initialized=!0,this.emitStatusEvent(s.c.Connected)}catch(t){console.error("Failed to initialize Waku node:",t),this.emitStatusEvent(s.c.Failed)}this.initializing=!1}}addEventListener(t,e){return this.emitter.addEventListener(t,e)}removeEventListener(t,e){return this.emitter.removeEventListener(t,e)}send(t,e){var i;return this.ensureWakuInitialized(),null===(i=this.node)||void 0===i?void 0:i.lightPush.send(t,e)}async getHistory(t){this.ensureWakuInitialized();let e=[];for await(let i of this.node.store.queryGenerator([t])){let t=await Promise.all(i),n=t.filter(t=>!!t);e=[...e,...n]}return e}async subscribe(t,e){return this.ensureWakuInitialized(),this.node.filter.subscribe(t,e)}emitStatusEvent(t){this.emitter.dispatchEvent(new CustomEvent("status",{detail:t}))}ensureWakuInitialized(){if(!u.initialized){let t="Waku is not initialized.";throw console.log(t),Error(t)}}constructor(){this.emitter=new EventTarget,this.initialized=!1,this.initializing=!1}}let u=new o}},function(t){t.O(0,[948,990,971,472,744],function(){return t(t.s=7747)}),_N_E=t.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{5856:function(){},7761:function(){},2678:function(){},5819:function(){},4112:function(){},7747:function(t,e,i){Promise.resolve().then(i.bind(i,5721))},5721:function(t,e,i){"use strict";i.r(e),i.d(e,{default:function(){return o}});var n=i(7437),s=i(2265),r=i(4033),a=i(7923);function o(){let t=(0,r.useRouter)(),{note:e,onNoteChange:i}=u(),s=async()=>{if(e)try{let{id:i,key:n}=await a.$.createNote(e);t.push("/view/".concat(i).concat("?key=".concat(n)))}catch(t){console.error("Failed to create a note:",t)}};return(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"note-info",children:"Your record will be stored for couple of days. Markdown is supported."}),(0,n.jsxs)("div",{className:"create-header",children:[(0,n.jsx)("div",{}),(0,n.jsx)("button",{onClick:s,className:"save-note",children:"Save note"})]}),(0,n.jsx)("textarea",{className:"note-value",value:e,onChange:i})]})}let u=()=>{let[t,e]=s.useState("");return{note:t,onNoteChange:t=>{var i;e(null==t?void 0:null===(i=t.currentTarget)||void 0===i?void 0:i.value)}}}},1177:function(t,e,i){"use strict";var n,s;i.d(e,{c:function(){return n},m:function(){return r}});let r="/flush-notes/1/note/proto";(s=n||(n={})).Initializing="Initializing...",s.WaitingForPeers="Waiting for peers...",s.Connected="Connected",s.Failed="Failed to initialize(see logs)"},7923:function(t,e,i){"use strict";i.d(e,{$:function(){return l}});var n=i(7441),s=i(1177),r=i(5136),a=i(8089),o=i(9710);class u{async createNote(t){var e;let i=(0,r.oQ)(),u=(0,r.Mf)({contentTopic:s.m,symKey:i,pubsubTopic:n.H5.pubsubTopic}),l=self.crypto.randomUUID();if(36!==l.length)throw"Unexpected uuid length";let c=await n.H5.send(u,{payload:(0,a.iY)(l+t)});return(null==c?void 0:null===(e=c.failures)||void 0===e?void 0:e.length)&&c.failures.length>0&&console.error("Failures when pushing note: ",c.failures.map(t=>t.error)),{id:l,key:(0,o.ci)(i)}}async readNote(t,e){await this.initMessages((0,o.nr)(e));let i=this.messages.map(t=>{try{let e=(0,a.Md)(t.payload),i=e.substring(0,36),n=e.substring(36);return{id:i,content:n}}catch(t){console.log("Failed to read message:",t)}}).find(e=>{if((null==e?void 0:e.id)===t)return!0});return null==i?void 0:i.content}async initMessages(t){if(this.subscription)return;let e=(0,r.UF)(s.m,t,n.H5.pubsubTopic);this.messages=await n.H5.getHistory(e),this.subscription=await n.H5.subscribe(e,t=>{this.messages.push(t)})}constructor(){this.messages=[]}}let l=new u},7441:function(t,e,i){"use strict";i.d(e,{H5:function(){return u},J9:function(){return n}});var n,s=i(1177),r=i(8089),a=i(9527);(n||(n={})).Status="status";class o{async init(){if(!this.initialized&&!this.initializing){this.initializing=!0;try{this.emitStatusEvent(s.c.Initializing),this.pubsubTopic=(0,a.L3)(s.m);let t=await (0,r.pq)({defaultBootstrap:!0,contentTopics:[s.m]});await t.start(),this.emitStatusEvent(s.c.WaitingForPeers),await (0,r.gT)(t,[r.Uw.Filter,r.Uw.LightPush,r.Uw.Store]),this.node=t,this.initialized=!0,this.emitStatusEvent(s.c.Connected)}catch(t){console.error("Failed to initialize Waku node:",t),this.emitStatusEvent(s.c.Failed)}this.initializing=!1}}addEventListener(t,e){return this.emitter.addEventListener(t,e)}removeEventListener(t,e){return this.emitter.removeEventListener(t,e)}send(t,e){var i;return this.ensureWakuInitialized(),null===(i=this.node)||void 0===i?void 0:i.lightPush.send(t,e)}async getHistory(t){this.ensureWakuInitialized();let e=[];for await(let i of this.node.store.queryGenerator([t])){let t=await Promise.all(i),n=t.filter(t=>!!t);e=[...e,...n]}return e}async subscribe(t,e){return this.ensureWakuInitialized(),this.node.filter.subscribe(t,e)}emitStatusEvent(t){this.emitter.dispatchEvent(new CustomEvent("status",{detail:t}))}ensureWakuInitialized(){if(!this.initialized){let t="Waku is not initialized.";throw console.log(t),Error(t)}}constructor(){this.emitter=new EventTarget,this.initialized=!1,this.initializing=!1}}let u=new o}},function(t){t.O(0,[948,990,971,472,744],function(){return t(t.s=7747)}),_N_E=t.O()}]); \ No newline at end of file diff --git a/flush-notes/_next/static/chunks/app/view/page-40306218709107ea.js b/flush-notes/_next/static/chunks/app/view/page-40306218709107ea.js deleted file mode 100644 index 6dc05f4..0000000 --- a/flush-notes/_next/static/chunks/app/view/page-40306218709107ea.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[803],{5856:function(){},7761:function(){},2678:function(){},5819:function(){},4112:function(){},629:function(t,e,i){Promise.resolve().then(i.bind(i,8815))},8815:function(t,e,i){"use strict";i.r(e),i.d(e,{default:function(){return c}});var n=i(7437),s=i(2265),r=i(9149),a=i(4033);let u=()=>{let t=(0,a.usePathname)(),e=(0,a.useSearchParams)(),i=t.split("/"),n=i.indexOf("view"),s=e.get("key"),r=i[n+1];return{key:s,id:r}};var o=i(7923),l=i(6309),c=()=>{let t=(0,a.useRouter)(),{id:e,key:i}=u(),[c,d]=s.useState("");return(s.useEffect(()=>{if(!e){t.replace("/404");return}o.$.readNote(e,i).then(t=>d(t||""))},[e,i,d]),c)?(0,n.jsx)(r.U,{children:c}):(0,n.jsx)(l.g,{})}},6309:function(t,e,i){"use strict";i.d(e,{g:function(){return s}});var n=i(7437);let s=()=>(0,n.jsx)("div",{className:"loading-block",children:(0,n.jsx)("p",{children:"Loading..."})})},1177:function(t,e,i){"use strict";var n,s;i.d(e,{c:function(){return n},m:function(){return r}});let r="/flush-notes/1/note/proto";(s=n||(n={})).Initializing="Initializing...",s.WaitingForPeers="Waiting for peers...",s.Connected="Connected",s.Failed="Failed to initialize(see logs)"},7923:function(t,e,i){"use strict";i.d(e,{$:function(){return l}});var n=i(7441),s=i(1177),r=i(5136),a=i(8089),u=i(9710);class o{async createNote(t){var e;let i=(0,r.oQ)(),o=(0,r.Mf)({contentTopic:s.m,symKey:i,pubsubTopic:n.H5.pubsubTopic}),l=self.crypto.randomUUID();if(36!==l.length)throw"Unexpected uuid length";let c=await n.H5.send(o,{payload:(0,a.iY)(l+t)});return(null==c?void 0:null===(e=c.failures)||void 0===e?void 0:e.length)&&c.failures.length>0&&console.error("Failures when pushing note: ",c.failures.map(t=>t.error)),{id:l,key:(0,u.ci)(i)}}async readNote(t,e){await this.initMessages((0,u.nr)(e));let i=this.messages.map(t=>{try{let e=(0,a.Md)(t.payload),i=e.substring(0,36),n=e.substring(36);return{id:i,content:n}}catch(t){console.log("Failed to read message:",t)}}).find(e=>{if((null==e?void 0:e.id)===t)return!0});return null==i?void 0:i.content}async initMessages(t){if(this.subscription)return;let e=(0,r.UF)(s.m,t,n.H5.pubsubTopic);this.messages=await n.H5.getHistory(e),this.subscription=await n.H5.subscribe(e,t=>{this.messages.push(t)})}constructor(){this.messages=[]}}let l=new o},7441:function(t,e,i){"use strict";i.d(e,{H5:function(){return o},J9:function(){return n}});var n,s=i(1177),r=i(8089),a=i(9527);(n||(n={})).Status="status";class u{async init(){if(!this.initialized&&!this.initializing){this.initializing=!0;try{this.emitStatusEvent(s.c.Initializing),this.pubsubTopic=(0,a.L3)(s.m);let t=await (0,r.pq)({defaultBootstrap:!0,contentTopics:[s.m]});await t.start(),this.emitStatusEvent(s.c.WaitingForPeers),await (0,r.gT)(t,[r.Uw.Filter,r.Uw.LightPush,r.Uw.Store]),this.node=t,this.initialized=!0,this.emitStatusEvent(s.c.Connected)}catch(t){console.error("Failed to initialize Waku node:",t),this.emitStatusEvent(s.c.Failed)}this.initializing=!1}}addEventListener(t,e){return this.emitter.addEventListener(t,e)}removeEventListener(t,e){return this.emitter.removeEventListener(t,e)}send(t,e){var i;return this.ensureWakuInitialized(),null===(i=this.node)||void 0===i?void 0:i.lightPush.send(t,e)}async getHistory(t){this.ensureWakuInitialized();let e=[];for await(let i of this.node.store.queryGenerator([t])){let t=await Promise.all(i),n=t.filter(t=>!!t);e=[...e,...n]}return e}async subscribe(t,e){return this.ensureWakuInitialized(),this.node.filter.subscribe(t,e)}emitStatusEvent(t){this.emitter.dispatchEvent(new CustomEvent("status",{detail:t}))}ensureWakuInitialized(){if(!o.initialized){let t="Waku is not initialized.";throw console.log(t),Error(t)}}constructor(){this.emitter=new EventTarget,this.initialized=!1,this.initializing=!1}}let o=new u}},function(t){t.O(0,[948,990,149,971,472,744],function(){return t(t.s=629)}),_N_E=t.O()}]); \ No newline at end of file diff --git a/flush-notes/_next/static/chunks/app/view/page-df1439bdda084351.js b/flush-notes/_next/static/chunks/app/view/page-df1439bdda084351.js new file mode 100644 index 0000000..09429bb --- /dev/null +++ b/flush-notes/_next/static/chunks/app/view/page-df1439bdda084351.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[803],{5856:function(){},7761:function(){},2678:function(){},5819:function(){},4112:function(){},629:function(t,i,e){Promise.resolve().then(e.bind(e,8815))},8815:function(t,i,e){"use strict";e.r(i),e.d(i,{default:function(){return c}});var n=e(7437),s=e(2265),r=e(9149),a=e(4033);let o=()=>{var t,i;let e=new URLSearchParams((null===(i=window)||void 0===i?void 0:null===(t=i.location)||void 0===t?void 0:t.search)||""),n=e.get("id")||"",s=e.get("key")||"";return{key:s,id:n}};var u=e(7923),l=e(6309),c=()=>{let t=(0,a.useRouter)(),{id:i,key:e}=o(),[c,d]=s.useState("");return(s.useEffect(()=>{if(!i){t.replace("/404");return}u.$.readNote(i,e).then(t=>d(t||""))},[i,e,d,t]),c)?(0,n.jsx)(r.U,{children:c}):(0,n.jsx)(l.g,{})}},6309:function(t,i,e){"use strict";e.d(i,{g:function(){return s}});var n=e(7437);let s=()=>(0,n.jsx)("div",{className:"loading-block",children:(0,n.jsx)("p",{children:"Loading..."})})},1177:function(t,i,e){"use strict";var n,s;e.d(i,{c:function(){return n},m:function(){return r}});let r="/flush-notes/1/note/proto";(s=n||(n={})).Initializing="Initializing...",s.WaitingForPeers="Waiting for peers...",s.Connected="Connected",s.Failed="Failed to initialize(see logs)"},7923:function(t,i,e){"use strict";e.d(i,{$:function(){return l}});var n=e(7441),s=e(1177),r=e(5136),a=e(8089),o=e(9710);class u{async createNote(t){var i;let e=(0,r.oQ)(),u=(0,r.Mf)({contentTopic:s.m,symKey:e,pubsubTopic:n.H5.pubsubTopic}),l=self.crypto.randomUUID();if(36!==l.length)throw"Unexpected uuid length";let c=await n.H5.send(u,{payload:(0,a.iY)(l+t)});return(null==c?void 0:null===(i=c.failures)||void 0===i?void 0:i.length)&&c.failures.length>0&&console.error("Failures when pushing note: ",c.failures.map(t=>t.error)),{id:l,key:(0,o.ci)(e)}}async readNote(t,i){await this.initMessages((0,o.nr)(i));let e=this.messages.map(t=>{try{let i=(0,a.Md)(t.payload),e=i.substring(0,36),n=i.substring(36);return{id:e,content:n}}catch(t){console.log("Failed to read message:",t)}}).find(i=>{if((null==i?void 0:i.id)===t)return!0});return null==e?void 0:e.content}async initMessages(t){if(this.subscription)return;let i=(0,r.UF)(s.m,t,n.H5.pubsubTopic);this.messages=await n.H5.getHistory(i),this.subscription=await n.H5.subscribe(i,t=>{this.messages.push(t)})}constructor(){this.messages=[]}}let l=new u},7441:function(t,i,e){"use strict";e.d(i,{H5:function(){return u},J9:function(){return n}});var n,s=e(1177),r=e(8089),a=e(9527);(n||(n={})).Status="status";class o{async init(){if(!this.initialized&&!this.initializing){this.initializing=!0;try{this.emitStatusEvent(s.c.Initializing),this.pubsubTopic=(0,a.L3)(s.m);let t=await (0,r.pq)({defaultBootstrap:!0,contentTopics:[s.m]});await t.start(),this.emitStatusEvent(s.c.WaitingForPeers),await (0,r.gT)(t,[r.Uw.Filter,r.Uw.LightPush,r.Uw.Store]),this.node=t,this.initialized=!0,this.emitStatusEvent(s.c.Connected)}catch(t){console.error("Failed to initialize Waku node:",t),this.emitStatusEvent(s.c.Failed)}this.initializing=!1}}addEventListener(t,i){return this.emitter.addEventListener(t,i)}removeEventListener(t,i){return this.emitter.removeEventListener(t,i)}send(t,i){var e;return this.ensureWakuInitialized(),null===(e=this.node)||void 0===e?void 0:e.lightPush.send(t,i)}async getHistory(t){this.ensureWakuInitialized();let i=[];for await(let e of this.node.store.queryGenerator([t])){let t=await Promise.all(e),n=t.filter(t=>!!t);i=[...i,...n]}return i}async subscribe(t,i){return this.ensureWakuInitialized(),this.node.filter.subscribe(t,i)}emitStatusEvent(t){this.emitter.dispatchEvent(new CustomEvent("status",{detail:t}))}ensureWakuInitialized(){if(!this.initialized){let t="Waku is not initialized.";throw console.log(t),Error(t)}}constructor(){this.emitter=new EventTarget,this.initialized=!1,this.initializing=!1}}let u=new o}},function(t){t.O(0,[948,990,149,971,472,744],function(){return t(t.s=629)}),_N_E=t.O()}]); \ No newline at end of file diff --git a/flush-notes/_next/static/Wn00J-QkjvXTJhi4lpAoC/_buildManifest.js b/flush-notes/_next/static/uspfk6pqKRl83s-QjjuPw/_buildManifest.js similarity index 100% rename from flush-notes/_next/static/Wn00J-QkjvXTJhi4lpAoC/_buildManifest.js rename to flush-notes/_next/static/uspfk6pqKRl83s-QjjuPw/_buildManifest.js diff --git a/flush-notes/_next/static/Wn00J-QkjvXTJhi4lpAoC/_ssgManifest.js b/flush-notes/_next/static/uspfk6pqKRl83s-QjjuPw/_ssgManifest.js similarity index 100% rename from flush-notes/_next/static/Wn00J-QkjvXTJhi4lpAoC/_ssgManifest.js rename to flush-notes/_next/static/uspfk6pqKRl83s-QjjuPw/_ssgManifest.js diff --git a/flush-notes/index.html b/flush-notes/index.html index e2a5188..2975123 100644 --- a/flush-notes/index.html +++ b/flush-notes/index.html @@ -1 +1 @@ -Share notes

Loading...

\ No newline at end of file +Share notes

Loading...

\ No newline at end of file diff --git a/flush-notes/index.txt b/flush-notes/index.txt index ac39fee..5b12e1a 100644 --- a/flush-notes/index.txt +++ b/flush-notes/index.txt @@ -1,11 +1,11 @@ 1:HL["/_next/static/media/a34f9d1faa5f3315-s.p.woff2","font",{"crossOrigin":"","type":"font/woff2"}] 2:HL["/_next/static/css/93e318bfbcd18d37.css","style",{"crossOrigin":""}] -0:["Wn00J-QkjvXTJhi4lpAoC",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/93e318bfbcd18d37.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] -5:I[5685,["948","static/chunks/948-50bbf5866eb892b4.js","185","static/chunks/app/layout-728a76cd335ea299.js"],""] +0:["uspfk6pqKRl83s-QjjuPw",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/93e318bfbcd18d37.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] +5:I[5685,["948","static/chunks/948-50bbf5866eb892b4.js","185","static/chunks/app/layout-6076b03a814c7003.js"],""] 6:I[6954,[],""] 7:I[7264,[],""] 9:I[8297,[],""] -a:I[5721,["948","static/chunks/948-50bbf5866eb892b4.js","990","static/chunks/990-35c20412112b0913.js","931","static/chunks/app/page-6f37c3f6b755896a.js"],""] +a:I[5721,["948","static/chunks/948-50bbf5866eb892b4.js","990","static/chunks/990-221729f16830b71b.js","931","static/chunks/app/page-1fab92edd07a9fd3.js"],""] b:{} 3:[null,["$","$L5",null,{"children":["$","$L6",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L7",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$L8",["$","$L9",null,{"propsForComponent":{"params":{}},"Component":"$a","isStaticGeneration":true}],null],"segment":"__PAGE__"},"styles":null}],"params":"$b"}],null] 4:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","link","2",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"32x32"}],["$","meta","3",{"name":"next-size-adjust"}]] diff --git a/flush-notes/view.html b/flush-notes/view.html index c0f3459..34db8c7 100644 --- a/flush-notes/view.html +++ b/flush-notes/view.html @@ -1 +1 @@ -Share notes

Loading...

\ No newline at end of file +Share notes

Loading...

\ No newline at end of file diff --git a/flush-notes/view.txt b/flush-notes/view.txt index 0eb0b59..402f398 100644 --- a/flush-notes/view.txt +++ b/flush-notes/view.txt @@ -1,11 +1,11 @@ 1:HL["/_next/static/media/a34f9d1faa5f3315-s.p.woff2","font",{"crossOrigin":"","type":"font/woff2"}] 2:HL["/_next/static/css/93e318bfbcd18d37.css","style",{"crossOrigin":""}] -0:["Wn00J-QkjvXTJhi4lpAoC",[[["",{"children":["view",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/93e318bfbcd18d37.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] -5:I[5685,["948","static/chunks/948-50bbf5866eb892b4.js","185","static/chunks/app/layout-728a76cd335ea299.js"],""] +0:["uspfk6pqKRl83s-QjjuPw",[[["",{"children":["view",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/93e318bfbcd18d37.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] +5:I[5685,["948","static/chunks/948-50bbf5866eb892b4.js","185","static/chunks/app/layout-6076b03a814c7003.js"],""] 6:I[6954,[],""] 7:I[7264,[],""] 9:I[8297,[],""] -a:I[8815,["948","static/chunks/948-50bbf5866eb892b4.js","990","static/chunks/990-35c20412112b0913.js","149","static/chunks/149-4f27ed9900df2b44.js","803","static/chunks/app/view/page-40306218709107ea.js"],""] +a:I[8815,["948","static/chunks/948-50bbf5866eb892b4.js","990","static/chunks/990-221729f16830b71b.js","149","static/chunks/149-4f27ed9900df2b44.js","803","static/chunks/app/view/page-df1439bdda084351.js"],""] b:{} 3:[null,["$","$L5",null,{"children":["$","$L6",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L7",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$","$L6",null,{"parallelRouterKey":"children","segmentPath":["children","view","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L7",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$L8",["$","$L9",null,{"propsForComponent":{"params":{}},"Component":"$a","isStaticGeneration":true}],null],"segment":"__PAGE__"},"styles":null}],"segment":"view"},"styles":null}],"params":"$b"}],null] 4:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","link","2",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"32x32"}],["$","meta","3",{"name":"next-size-adjust"}]]